text:
Q: A function to split long rows into shorter rows in google spreadsheets? I have a Google spreadsheet that receives data from a form. Every answer in this form results in a 224 column long row in my spreadsheet.
What I need is a function that splits every one of these rows into several rows, each containing only 7 columns.
This is a live form that will continue adding more lines the spreadsheet. Thus I need a formula that:

*

*Splits a row into several rows.

*Does this for every row from the form without overwriting itself.

*Automatically does this for every new row of data that is received.

As I have tried to achieve this seemingly simple thing for several hours without success i now ask the internet for help. I would be so grateful if someone can help me with this.

A: I doubt a regular spreadsheet formulas composition will do it. You'll need Google Apps Script, please read the guide and tutorials to see that this is not very difficult.


text:
Q: How to implement notification like icon/image I need to build a somewhat dynamic icon/image in the notification style common in mobile devices. I must clarify though that the primary display will be on desktops. The image will lie before some text
For example
Some Text
This consists of 2 images: the telescope and the gear plus a number that is dynamic.
I am almost completely new to css, so I am struggling how to place the gear with respect to the telescope and how to scale the gear depending on the number (for example if the number is 10000 the gear needs to be larger than if it is 3).
Of course the whole combo needs to scale well with the screen size as well.
How to go about this in a somewhat elegant way?
My html looks like

                Labs

but right now my lab-image is just the telescope image.

A: What you are looking for is a badge with a custom background-image
So, based on this I've create this fiddle

$(document).ready(function(){
var cw = $('.inner-badge').width();
$('.inner-badge').css({'height':cw+'px'});
})
body {
  margin: 25px
}
.outter-badge {
  position: relative;
  margin: 10px;
  background: #fff;
  width: 64px;
}
.inner-badge {
  display: table;
  position: absolute;
  top: -15px;
  right: -25px;
  background-image: url('https://openclipart.org/image/2400px/svg_to_png/174149/fancy-badge.png');
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
}
.inner-badge p{
  display: table-cell;
    vertical-align: middle;
padding: 8px;
}

1000

A: NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(intent);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    notificationBuilder.setSmallIcon(intent.getResources().getIdentifier(appIcon + "_transparent", "drawable", intent.getPackageName()));
}else{
    notificationBuilder.setSmallIcon(intent.getResources().getIdentifier(appIcon, "drawable", intent.getPackageName()));
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Bitmap icon = BitmapFactory.decodeResource(intent.getResources(), intent.getResources().getIdentifier(appIcon, "drawable", intent.getPackageName()));
    notificationBuilder.setLargeIcon(icon);
}
notificationBuilder.setContentTitle(title)
        .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
        .setContentText(message)
        .setSound(defaultSoundUri)
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Card Game: Two Slightly Different Expected Value derivavations For Christmas my family have been playing a card game called Wordaround. The rules are irrelevant here, other than the fact that each card has $3$ words printed on it and there are $100$ cards. In each "game" of Wordaround, we use exactly one word from each of the $100$ cards. The method by which words are chosen is not important here, so assume each word is chosen with uniform probability of $\frac13$.
Now, after a few games of this, we realised that we were encountering the same words again and again. This is not hard to believe, since it's possible to exhaust all words in exactly $3$ games, though it's quite unlikely. Being obsessed with maths, I was naturally inclined to try and work out the expected value of the number of "unused" words after $n$ games. I began with a simple argument, but was unconvinced, so tried a more complex argument. The two answers agreed, but I'm not sure I'm entirely correct in my first derivation.
My First Attempt: Words are Events
The simple (perhaps naive) approach I took first was to consider the $300$ words as true/false events for each game. In each game, a word has $\frac23$ probability of not being picked. Since choices of a word in successive games are independent events, we can then say that after $n$ games, a word has a $(\frac23)^n$ chance of not being chosen. So the expected value of unused words is just the sum of all the individual expected values i.e. $300(\frac23)^n$. This agrees with a simple observation: after one round, there will be exactly $200$ unused words. But I think I made a subtle mistake here, because choosing one word on a card mutually excludes the choice of the other two.
My Second Attempt: Words left per Card
To ease my worries I calculated the probability a different way. Consider a card and ask: how many unused words are left on it after $n$ games? Clearly after $1$ game, there are exactly $2$ unused words. Let's assume $n \geq 1$. Then there are either $0, 1$ or $2$ unused words. The expected number of unused words is the probability that there is $1$ unused word plus twice the probability that there are $2$ unused words.
The probability of two unused words is the chance that the same word was chosen for all games i.e. for the remaining $n-1$ games the first word repeats, yielding:
$$\left(\frac13\right)^{n-1} = \frac{3}{3^n}$$
The probability of $1$ unused card can be calculated by considering first the number of $n$ digit ternary numbers that use only two digits- excluding numbers that use only one digit. This number is $3 \cdot (2^n - 2)$. That is: $3$ ways to exclude a number, and $(2^n - 2)$ subsets of $n$ corresponding to the choices for the indices of the smaller number remaining, excluding the $2$ corner cases where all indices are the same digit. Dividing this by the total number of ternary $n$ digit numbers gives us the probability.
$$\dfrac{3 \cdot (2^n - 2)}{3^n}$$
So the expected value per card is:
$$2 \cdot \frac{3}{3^n} + \dfrac{3 \cdot (2^n - 2)}{3^n} = \dfrac{3 \cdot (2^n)}{3^n}$$
Multiplying by $100$ cards and we get:
$$300(\frac23)^n$$
Which agrees with the answer derived by the first method.
Question
Are both methods valid paths to the correct answer or is the first answer just a fluke?

A: The first answer has correct reasoning, as well. Your doubt stems from the (true) fact that the survival of one word is not independent from survival of another on the same card. But expectation values are additive, even when the underlying variables are not independent.

A: Both are valid ways to get the answer. A valid justification for the first method goes as follows:
For each of the 300 words ($1 \leq i \leq 300$), let $X_{i,n}$ be the random variable which is $1$ if the $i$-th word has never been chosen after $n$ games, and $0$ otherwise.
As you stated, $E(X_{i,n}) =\text{Pr}(X_{i,n} = 1) = \left(\frac{2}{3}\right)^n.$
Now, the number of unused words after $n$ games is clearly $\sum_{i=1}^{300} X_{i,n}$, hence the expected number of unused words is
$$E\left(\sum_{i=1}^{300}X_{i,n}\right) = \sum_{i=1}^{300}E(X_{i,n}) = 300 \left(\frac{2}{3}\right)^n$$


text:
Q: Issue with disk space on VM instance Our team has encountered an issue with one of our VM instance hosted in region Asia-East zone C.
Problem we have encountered:
The root partition of the VM instance becomes full.
Rebooting the server decreases the disk usage back to 11-15 % utilization.
We tried creating a new VM instance in the same zone but we experienced this problem on the new machine as well.
The new machine (Ubuntu 18.04 LTS) is also in the same zone.
After analyzing all the directories in that partition, the sum does not add up to the total available space on the partition.
Appreciate any help in this case.

A: Look at the sizes of directories in your root volume to see what is large.  ncdu -x /  is good at this, as you can navigate the tree from / to where the space is being used.
Common files that can grow without bound include text log files and database journals.
Rebooting getting space back often means files were deleted without closing them. Review how files are rotated and purged, namely logrotate configurations.

A: Another quickest solution to solve the out of disk space problem is to increase the size of the disk. In general, the partition table allows up to 2 TB in size. Any size more than that will be in vain. Luckily, GCE allows us to grow the disk size without turning off nor restarting. You can do it on the fly by following this guide: https://cloud.google.com/compute/docs/disks/add-persistent-disk#resize_partitions.
I know that this suggestion doesn't help tackle the root cause. The usage of ncdu mentioned earlier is a very useful tool to figure out the culprit file. But I think it may help people who are in need of growing the disk size :) Then, solving the problem from the root cause is the best way to go.


text:
Q: How do i turn a list into a dict? I'm making a Python(3) progam to read this text file:
firstval="myval"
secondval="myotherval"

and turn it into a dict.
I tried this:
lines = file.readlines().split("\n")
values = []

for line in lines:
    values.append(line.split("="))

to turn the file into a list
How do i turn this:
values = ["firstval", "myval", "secondval", "myotherval"]

into this:
values = {
    "firstval": "myval",
    "secondval": "myotherval"
}

A: You can use dict() with zip():
dict(zip(values[::2], values[1::2]))

This outputs:
{'firstval': 'myval', 'secondval': 'myotherval'}


text:
Q: Pressing a key will spawn a lot of screens I have the code below:
        else if (keyboardState.IsKeyDown(Keys.E)) // if the 'E' key is pressed
        {
            form = new InventoryScreen();         //define winform instance
            form.Show();                          //display winform
        }

It works, maybe too well. Because when the user presses and holds the 'E' key, the program generates a lot of winform screens. Is there a way to instruct the program to only run the following only once? Also, how would I write it so that if I press the 'E' key again, the window will disapear?

A: I would create a separate event handler firing on keyup.  Within the handler you can check to see if the key is indeed 'E'.  The keyup event will only fire once when the key is pressed and not fire while the key is held down.
See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx

A: XNA is not event-driven, it is instead a game loop.
There is no built-in event that fires on keys being press or not. One option is to only handle the 'E' event if no form is created.
A second option is to keep the old keyboard state, like this:
KeyboardState oldState;

Update(..):
KeyboardState now = Keyboard.GetState();
if (now.IsKeyUp(Keys.E) && oldState.IsKeyDown(Keys.E))
// i.e. a "release event"
{
  form.Show();
}
oldState = now;

For the variant with disappearing, this might work or something similar, but you should probably instead handle it in the created form:
KeyboardState now = Keyboard.GetState();
if (now.IsKeyUp(Keys.E) && oldState.IsKeyDown(Keys.E))
// i.e. a "release event"
{
  if (form.Visible)
  {
   form.Hide();
  }
 else
{
  form.Show();
}

}
    oldState = now;


text:
Q: Javascript not always returning false This is the code I have. The console always reads wrong. What is happening. I think it is when I objectofy the textbox.

function compare() {
  var test = "test";
  var input = document.getElementById("input").value;
  var inputLen = input.length;
  var tick;
  for (tick = 0; tick < inputLen; tick++) {
    if (input[tick] != test[tick]) {
      break;
    }
  }
  if ((tick - 1) == test.length) {
    console.log("equal");
  } else {
    console.log("wrong");
  }
}
<input type="text" id="input" placeholder="text">
<input type="submit" id="submit" onclick="compare()">

I really could use some help. The console.log always returns "wrong".

A: While performing your for loop, the tick variable increases to 5 on the last iteration before exiting the loop. To resolve this, compare it to test.length without decreasing it with -1:

function compare() {
  var test = "test";
  var input = document.getElementById("input").value;
  var inputLen = input.length;
  var tick;
  for (tick = 0; tick < inputLen; tick++) {
    if (input[tick] != test[tick]) {
      break;
    }
  }
  // After exiting the loop, tick will be equal to 5, not 4.
  if (tick === test.length) {
    console.log("equal");
  } else {
    console.log("wrong");
  }
}
<input type="text" id="input" placeholder="text">
<input type="submit" id="submit" onclick="compare();">

A: Solution 1
var test = "test";
var input = document.getElementById("input").value;
var inputLen = input.length;
var tick;

for (tick=0; tick < inputLen; tick++)
{
    if (input[tick]!=test[tick])
    {
        break;
    }
}

if (tick==test.length)
{
   console.log("equal");
}
else
{
   console.log("wrong");
}

Solution 2
var test = "test";
var input = document.getElementById("input").value;
var inputLen = input.length;
var tick;

for (tick=1; tick <= inputLen; tick++)
{
   if (input[tick-1]!=test[tick-1])
   {
       break;
   }
}

if ((tick - 1)==test.length)
{
   console.log("equal");
}
else
{
   console.log("wrong");
}


text:
Q: Junit Framework Unit Tests : Mockito.doNothing() doesn't work as expected while mocking void methods I am facing an issue where in the "Mockito.doNothing()" doesn't seem to mock the method as expected.
In the below code (pseudo code) "execution of functionC" returns an exception.
And i am trying to test FunctionA by mocking classB and it's methods.
I had expected the Mockito.verify to succeed considering that functionB has been mocked to return to the caller immediately ( without executing functionC ).
But testFunctionA() runs into an exception ( thrown by functionC ), Remember functionC isn't supposed to be executed ( due to the mocking of functionB with Mockito.doNothing() ).
Could you please let me know if i am missing something? Any other alternate methods to mock void methods ( to return immediately ) would be highly appreciated.
Thanks,
Vamsi.
public class classA {
  public void functionA() {
    int localA;
    String localB;
    B b = new B();
    b.functionB(localA, localB);
   }
 }

public class classB {
  public void functionB(int a, String b) {
    functionC(a, b);
  }
}

public class testClassA {
private classA objectA = new classA();

@Mock
classB objectB;

@Test
public void testFunctionA() {
    Mockito.doNothing().when(objectB).functionB(Mockito.anyInt(),Mockito.anyString());
    objectA.functionA();
    Mockito.verify(objectB, Mockito.times(1)).functionB(Mockito.anyInt(),Mockito.anyString());
   }
}

A: You never inject the classB mock in the instance of classA, the class under test. So the recorded behavior will not be effective as you manipulate the object under test :
private classA objectA = new classA();

You could pass ObjectB either in the constructor of ClassA or in the functionA() method.
For example to do that with the method :
public void functionA(ClassB classB) {
    int localA;
    String localB;
    classB.functionB(localA, localB);
}

and in your test :
objectA.functionA(objectB);

A: The problem here is that you never passing your mock of classB to the object under test of classA. Please also refer to Mockito Object Creation Mocking Guide

A: classA creates a new instance of B (I guess this should rather be classB) on each functionA invocation. Thus it will never use the classB mock.
I would suggest to make classB an instance field of classA
public class classA {

   classB b = new classB();

   public void functionA() {
      int localA = 1;
      String localB = "";

      b.functionB(localA, localB);
   }
}

and use InjectMocks
public class testClassA {

  @InjectMocks
  private classA objectA = new classA();

  @Mock
  classB objectB;

  @BeforeMethod
  public void init(){
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testFunctionA() {
    Mockito.doNothing().when(objectB).functionB(Mockito.anyInt(), Mockito.anyString());
    objectA.functionA();
    Mockito.verify(objectB, Mockito.times(1)).functionB(Mockito.anyInt(), Mockito.anyString());
  }
}


text:
Q: Rocco Theme Functions error implode I get this error on my website:
Warning: array_map() [function.array-map]: Argument #2 should be an array in /home/content/77/12366977/html/wp-content/themes/rocco/functions.php on line 86
Warning: implode() [function.implode]: Invalid arguments passed in /home/content/77/12366977/html/wp-content/themes/rocco/functions.php on line 86

I think the line that the error is occuring is this one:
* Excerpt
* --------------------------------------------------------------------------- */
function mfn_excerpt($post, $length = 55, $tags_to_keep = '', $extra = ' [...]') {
if(is_int($post)) {
    $post = get_post($post);
} elseif(!is_object($post)) {
    return false;
}

if(has_excerpt($post->ID)) {
    $the_excerpt = $post->post_excerpt;
    return apply_filters('the_content', $the_excerpt);
} else {
    $the_excerpt = $post->post_content;
}

$the_excerpt = strip_shortcodes(strip_tags($the_excerpt, $tags_to_keep));
$the_excerpt = preg_split('/\b/', $the_excerpt, $length * 2+1);
$excerpt_waste = array_pop($the_excerpt);
$the_excerpt = implode($the_excerpt);
if( $excerpt_waste ) $the_excerpt .= $extra;

return apply_filters('the_content', $the_excerpt);

What should I do and where should I add the code, if adding code is the solution?
Thanks so much for your help!

A: First of all PHP implode takes two arguments if the explode is not standard and proably this is the case. You are using only one
Also there is no "array_map" in your example. Is really the same code?


text:
Q: Storage data created by user on phone. Please see this post My situation is the next one. I am creating an app when you can do a survey, and then, you can see survey answers, clicking on a button, in the applicacion, without going to phone files or something like that. I've created like 55% of that application, but the other 45% is the most important. How many possibilites there are, or what can i do to achieve that, when a person click an in-app button, could see survey answers. I did the interface, buttons, textview, etc.. I created a database, thiniking that creating it, it would be possible to achieve that i want to. I expect to do a system when you can do a survey, and then, press a button, open a new activity and see survey answers. When you close app and open again, survey answers doesn't disappear, they still saved. Thanks!
Here is my code of the survey, XML and JAVA:
Button sig = (Button) findViewById(R.id.env); // cargo el boton
    encuestadoSQLiteHelper encuestado = new encuestadoSQLiteHelper(this, "DBEncuestado", null, 1); // base de datos
    final SQLiteDatabase db = encuestado.getWritableDatabase();

    sig.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = getApplicationContext();
            EditText preg5 = (EditText) findViewById(R.id.editText2);
            EditText preg4 = (EditText) findViewById(R.id.editText);
            Spinner cur = (Spinner) findViewById(R.id.spinnerp);
            EditText nom = (EditText) findViewById(R.id.editText3);
            RadioGroup gruporadio = (RadioGroup) findViewById(R.id.Grupo1);
            RadioGroup gruporadio2 = (RadioGroup) findViewById(R.id.Grupo2);
            RadioGroup gruporadio3 = (RadioGroup) findViewById(R.id.Grupo3);
            String strNombre = nom.getText().toString();
            String nombre = "PabloGonzalez";
            String curso =  cur.getSelectedItem().toString();
            String strPregCinco = preg5.getText().toString();
            String strPregCuatro = preg4.getText().toString();

            if(gruporadio.getCheckedRadioButtonId() == -1 || gruporadio2.getCheckedRadioButtonId() == -1  || gruporadio3.getCheckedRadioButtonId() == -1 )
            {
                Toast.makeText(context,"¡No marcaste ninguna respuesta!",Toast.LENGTH_LONG).show();
            }

            else if (strNombre.matches("") || strPregCinco.matches("") || strPregCuatro.matches(""))
            {
                Toast.makeText(context,"¡Dejaste campos vacíos!",Toast.LENGTH_LONG).show();
            }

            else if(db == null)
            {
                Toast.makeText(context, "No funciona la base de datos.", Toast.LENGTH_LONG).show();
                db.close();
            }

            else
            {
                Intent i = new Intent (encuesta.this, res8.class);
                i.putExtra("nombre", strNombre);
                startActivity(i);
                Intent pas = new Intent(encuesta.this, MainActivity.class);
                Toast.makeText(context,"¡Encuesta enviada!",Toast.LENGTH_LONG).show();
                startActivity(pas);
                db.execSQL("INSERT INTO Encuestado (nombre) " +
                        "VALUES ('" + nombre +"')");
                db.close();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            File sd = Environment.getExternalStorageDirectory();
                            File data = Environment.getDataDirectory();

                            if (sd.canWrite()) {
                                String currentDBPath = "/data/com.example.pablo.myapplication/databases/DBEncuestado";
                                String backupDBPath = "backdatabase.sqlite";
                                File currentDB = new File(data, currentDBPath);
                                File backupDB = new File(sd, backupDBPath);

                                if (currentDB.exists()) {
                                    FileChannel src = new FileInputStream(currentDB).getChannel();
                                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                                    dst.transferFrom(src, 0, src.size());
                                    src.close();
                                    dst.close();
                                }
                            }
                        } catch (Exception e) {
                            System.out.println("error in data base copy:"+e);
                        }
                    }
                }).start();
            }
        }
    });

}

}
If you can see, there is a database, but i dont know if it is not necessary or yes.
XML:
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:text="Nombre del encuestado:"
        android:id="@+id/nomb"
        android:textSize="16dp"
        android:textColor="#000000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="2dp"
        android:ems="15"
        android:inputType="textPersonName"
        android:text="" />

    <TextView
        android:text="Curso:"
        android:textSize="16dp"
        android:textColor="#000000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/spinnerp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"/>

    <TextView
    android:text="1. ¿Cuánto tiempo tarda usted desde su casa al colegio?"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16dp"
    android:textColor="#000000"
    android:id="@+id/textView" />

    <RadioGroup
        android:id="@+id/Grupo1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1/2 hora a 1 hora" />

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1 hora o 2 horas" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="2 horas o más" />
    </RadioGroup>

<TextView
    android:text="2. ¿Cuánto tiempo tarda desde el colegio a su casa?"
    android:layout_marginTop="20dp"
    android:textSize="16dp"
    android:textColor="#000000"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

    <RadioGroup
        android:id="@+id/Grupo2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1/2 hora a 1 hora" />

        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1 hora o 2 horas" />

        <RadioButton
            android:id="@+id/radioButton5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="2 horas o más" />
    </RadioGroup>

<TextView
    android:text="3. ¿Cuáles de las siguientes zonas de Bogotá está localizado su domicilio?"
    android:layout_marginTop="20dp"
    android:textSize="16dp"
    android:textColor="#000000"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView2" />

    <RadioGroup
        android:id="@+id/Grupo3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <RadioButton
        android:id="@+id/radioButton6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Norte de Bogotá (calle 72 en adelante)" />

        <RadioButton
            android:id="@+id/radioButton7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Suba (noroccidente)" />

        <RadioButton
            android:id="@+id/radioButton8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Centro - Chapinero - Teusaquillo" />

        <RadioButton
            android:id="@+id/radioButton9"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Alrededores de Bogotá" />

        <RadioButton
            android:id="@+id/radioButton10"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sur de Bogotá" />

        <RadioButton
            android:id="@+id/radioButton11"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Occidente (Puente Aranada - Fontibón - Engativá)" />
    </RadioGroup>

<TextView
    android:text="4. Si usted fuera alcalde de Bogotá, ¿que solución propondría para mejorar la movilidad de Bogotá?"
    android:textColor="#000000"
    android:textSize="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:id="@+id/textView3" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="13dp"
        android:background="#e4e4e4"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingBottom="8dp"
        android:paddingLeft="10dp"
        android:paddingTop="2dp"
        android:textSize="16dp" />

<TextView
    android:text="5. ¿Cómo cree que influye la movilidad en la calidad de vida de las personas?"
    android:textColor="#000000"
    android:textSize="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:id="@+id/textView4"
    android:layout_below="@+id/editText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="20dp"
        android:background="#e4e4e4"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingBottom="8dp"
        android:paddingLeft="10dp"
        android:paddingTop="2dp"
        android:textSize="16dp" />

    <Button
        android:text="Enviar encuesta"
        android:textSize="14dp"
        android:id="@+id/env"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>

And activity where i want to show the answers is res8.java

A: Bro, Just create a model class like getter and setter first having methods like getQuestion(), setQuestion(), getAnswer(), setAnswer(). And after that , when user answering your survey question just create a object of that model class say like:-
ArrayList<MyModel> datalist = new ArrayList();
    MyModel model = new MyModel();
    model.setQuestion(list.get(i).question);
    model.setAnswer(list.get(i).answer);
    ....
    ....
  dataList.add(model);

like this just capture all user input data , No need for the database in this.
Here list is the list of all question you are having ....
And when you want to getData ...just call datalist.get(i).getQuestion and similarly with answer.


text:
Q: Can't create new instance after installing Angular 2 through CLI I'm trying to use @angular cli to create a new angular 2 project. The install went well, but when I try to create a new site, I get the following error. Has anyone run into this?
/usr/local/lib/node_modules/@angular/cli/models/config/config.js:15
    constructor(_configPath, schema, configJson, fallbacks = []) {
                                                           ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/@angular/cli/models/config.js:2:18)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

Actually, looks like @angular cli didn't install. I can't get a --version and when I look at the install results, I see the following warnings:
npm WARN @ngtools/webpack@1.2.9 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN @ngtools/webpack@1.2.9 requires a peer of @angular/compiler-cli@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN @ngtools/webpack@1.2.9 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN @ngtools/webpack@1.2.9 requires a peer of @angular/tsc-wrapped@^0.5.0 but none was installed.

A: Maybe your Nodejs version is out of date? Make sure you have the latest LTS 6.x


text:
Q: Is $\mathrm{binomial}(n, p)$ family both full and curved for $n$ fixed? Let $n$ be a fixed positive integer. The binomial$(n, p)$ family is given by
$$f(x|p)=\tbinom{n}{x}p^x(1-p)^{n-x}\tag{1}.$$
We may rewrite (1) as
$$f(x|p)=\tbinom{n}{x}(1-p)^n\exp\left[x\log\frac{p}{1-p}\right]$$
and say binomial$(n, p)$ is a full exponential family. However one could rearrange (1) as
$$f(x|p)=\tbinom{n}{x}\exp \left[x\log p+(n-x)\log(1-p)\right].$$
Now it becomes a curved exponential family as $n$ is fixed.
I'm a beginner of statistics. I do know there is an example (ex: normal family) that the distribution is full but curved as parameters satisfy some specific relationship. Is it right that binomial$(n, p)$ family is both full and curved?
[Reference]

*

*Statistical Inference, George Casella and Roger L. Berger

A: From Casella & Berger, p.137-38:

When $n$ is given, (1) is an exponential family. It is full as the parameter space $(0,1)$ is the largest possible. In the sense that
$$\log p - \log (1-p)$$
ranges $(-\infty,+\infty)$ when $p\in(0,1)$. Rewriting it as
$$ f(x|p)=\tbinom{n}{x}\exp \left[x\log p+(n-x)\log(1-p)\right]\tag{2}$$
is seemingly increasing the dimension of the natural statistic and hence gives the impression of a curved exponential family, but this is only an impression since $x$ and $(n-x)$ are linearly dependent:
$$ x+(n-x)=n$$
The representation (2) is thus not minimal. In other words, one can rewrite (2) as
$$\exp \left[x\log p+(n-x)\log(1-p)\right]=\exp \left[x\{\log p-\log(1-p)\}\underbrace{+n\log(1-p)}_{\substack{\text{normalising}\\ \text{constant}}}\right]$$
and deduce there is a dimension-one sufficient statistic.


text:
Q: Data is not written into CSV when I download CSV from Flask I have a CSV that contains data of user activity over various social media apps ranging for a month
Here's  a snippet

for you reference:
Here is the content of the csv
date_time;timestamp;Instagram;Facebook;Snapchat;Twitter;TikTok;YouTube
2020-08-23__04:16:00.705612;1598148961;N;N;N;N;Y;N
2020-08-23__04:17:02.308588;1598149022;N;N;N;N;Y;N
2020-08-23__04:18:03.944537;1598149084;N;N;N;Y;Y;N

This contains more than 50,000 records.
Now when I upload this csv via my Flask App, and make changes in it and also download it, it does get downloaded and this is what I get.

All I do in my code is upload the CSV, and change the format of ``date_time``` from (Y-M-D__H-M-S.ms) to (Y-M-D H-M-S.ms), and when I download the new file, the data is not written into the csv properly
Here is my code for the same
from flask import Flask, flash, render_template, request, make_response
import pandas as pd
import datetime
import csv
import io

@app.route('/mainPage', methods=['GET', 'POST'])
def upload_csv():
    if request.method=='POST':
        f=request.form['csvfile']
        dataset=pd.read_csv(f)
        df=pd.DataFrame(dataset, columns=list(dataset.columns))
        date_time=[]
        dt=df['date_time']
        for i in range(len(dt)):
            cons=dt[i] #considering the current datetime object
            cons=cons.replace('__', ' ')
            date_time_obj = datetime.datetime.strptime(cons, '%Y-%m-%d %H:%M:%S.%f')
            date_time.append(date_time_obj)

        df.drop(columns='date_time')
        col = df.columns.tolist()
        df['date_time']=date_time
        df = df[(['date_time']+col[1:])]
        si = io.StringIO()
        cw = csv.writer(si)
        cw.writerows(df)
        output = make_response(si.getvalue())
        output.headers["Content-Disposition"] = "attachment; filename=new.csv"
        output.headers["Content-type"] = "text/csv"
        return output
    return render_template('home.html')

A: I think there are some problems here.
df.drop(columns='date_time')

should be
df = df.drop(columns='date_time')

or
df.drop(columns='date_time', inplace=True)

Next, the insertion of the new data sounds overly complicated to me. You can just do
df.insert(loc=0, column="date_time", value=date_time)

Lastly, all that complex CSV output is possibly much easier with
df.to_csv(index=False)

Here's my full code (Python only, no Flask):
import pandas as pd
import datetime
from io import StringIO

csvdata = StringIO("""
date_time;timestamp;Instagram;Facebook;Snapchat;Twitter;TikTok;YouTube
2020-08-23__04:16:00.705612;1598148961;N;N;N;N;Y;N
2020-08-23__04:17:02.308588;1598149022;N;N;N;N;Y;N
2020-08-23__04:18:03.944537;1598149084;N;N;N;Y;Y;N""")

def upload_csv():
    dataset=pd.read_csv(csvdata, delimiter=";")
    df=pd.DataFrame(dataset, columns=list(dataset.columns))
    date_time=[]
    dt=df['date_time']
    for i in range(len(dt)):
        cons=dt[i] #considering the current datetime object
        cons=cons.replace('__', ' ')
        date_time_obj = datetime.datetime.strptime(cons, '%Y-%m-%d %H:%M:%S.%f')
        date_time.append(date_time_obj)

    df.drop(columns='date_time', inplace=True)
    df.insert(loc=0, column="date_time", value=date_time)
    return df.to_csv(index=False)

output = upload_csv()


text:
Q: Class does not exist antonioribeiro/tracker Hello guys I am using antonioribeiro/tracker from github and followed all the instructions everything went smooth but when I tried to access the stats panel it returns an error that

class admin does not exists.

In the tracker.php, I found the error is from this line 'authentication_ioc_binding' => ['auth','admin']

A: I tried creating admin class but it did not fix the issue. I was confused with the documentation of the package. The code that I followed is for multiple authentication driver. So I used the default setting authentication_ioc_binding => ['auth'] this solves the issue.


text:
Q: How open the new tab from IE I want to open the html file from IE.
So, I use the ShellExecute API like this.
ShellExecute(NULL, L"open", html file path, NULL, NULL, SW_SHOW);

but, My Default Browser is Chrome.
Html file is open to the Chrome new tab.
So, I try like this.
ShellExecute(NULL, L"open",  IE file path, html file path, NULL, SW_SHOW);

I set parameter to the html file path.
but, That method is create new window.
I want to open the html file from IE.(new tab!)
Thanks.

A: Instead of ShellExecute, you have to use an instace of IShellWindows to open a new tab in Internet Explorer. Check the code taken from Warwick Systems to accomplish this:
void OutputToWebBrowser(const CString & path)
{
    IShellWindows *psw;
    HRESULT hr = CoCreateInstance(CLSID_ShellWindows,NULL,CLSCTX_ALL,IID_IShellWindows,(void**)&psw);
    if (!SUCCEEDED(hr))
        return;
    IWebBrowser2* pBrowser2 = 0;
    bool found = false;
    long nCount = 0;
    hr = psw->get_Count(&nCount);
    if (SUCCEEDED(hr))
    {
      for (long i = nCount - 1; (i >= 0) && (!found); i--) {
        // get interface to item no i
         _variant_t va(i, VT_I4);
      IDispatch * spDisp;
      hr = psw->Item(va,&spDisp);
      hr = spDisp->QueryInterface(IID_IWebBrowserApp,(void **)&pBrowser2);
      if (SUCCEEDED(hr))
         {
              BSTR name;
              pBrowser2->get_FullName(&name);
             CString n(name);
             if (n.Find("IEXPLORE") == -1)
                 pBrowser2->Release();
             else
                 found = true;
           }
      }
     psw->Release();
   }

   if (!found)
         hr = CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,IID_IWebBrowser2,(void**)&pBrowser2);

    if (SUCCEEDED(hr))
   {
      VARIANT vEmpty;
      VariantInit(&vEmpty);
      _variant_t URL, Flag, TargetFrameName, PostData, Headers;
     Flag.ChangeType(VT_I4, &Flag);
     if (found)
         Flag.intVal = 0x800;
     URL.SetString(path);

     hr = pBrowser2->Navigate2(&URL, &Flag, &vEmpty, &vEmpty, &vEmpty);
     if (SUCCEEDED(hr))
     {
          pBrowser2->put_Visible(TRUE);
      }
     else
     {
         pBrowser2->Quit();
      }
     pBrowser2->Release();
   }
}


text:
Q: Compilation errors in firestore.rules: Unexpected 'if' I have this compilation error in my firestore.rules:
Compilation errors in firestore.rules:
[E] 35:7 - Unexpected 'if'.
[E] 38:7 - Unexpected 'else'.
[E] 42:3 - Unexpected '}'.

The excerpt from the firestore.rules is as follows:
service cloud.firestore {
  match /databases/{database}/documents {

    match /requests/{id} {
     allow read: if isSignedIn() && ((getUserKennung() in resource.data.users_read) || userIsXY());
     allow write: if isSignedIn() && ((getUserKennung() in resource.data.users_write) || userIsXY());
    }

    function getUserKennung(){
     let email = request.auth.token.email;
     if(email.lower().matches('.*@provider[.]org')){
       return email[0:7].upper();
     }
     else {
       return 'ERR: Invalid usermail';
     }
    }

    function userIsXY(){
      return request.auth.token.email == 'XY@provider.org';
    }

    function isSignedIn(){
      return request.auth != null;
    }
  }
}

I have no clue why the error occurs.

A: I don't think if...then...else is allowed in custom functions in security rules, so you might want to try a ternary expression like this:
function getUserKennung(){
 let email = request.auth.token.email;
 return email.lower().matches('.*@provider[.]org')
   ? email[0:7].upper()
   : 'ERR: Invalid usermail';
}


text:
Q: How to Deserialize an JSON object with invalid field name in it I have a JSON request which has follwing structure:
"formats":  {
        "flash_embed": "http://a3.vikiassets.com/assets/vikiplayer-922746a667cfd38137a7e45df6ba1b95.swf?auto_play=true&language_codes=en&media_id=74965&partner=16&source=api_v3",
        "m3u8": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965/ios.m3u8",
        "res-150p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_mp4cell_150.mp4",
        "res-240p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_240p.mp4",
        "res-270p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_270p.mp4",
        "res-360p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_360p.mp4",
        "res-480p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_480p.mp4",
        "res-720p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_720p.mp4"
      }
    }

Now res-150p, says invalid name in C# and if I give another name to it then while desiralizing I am not getting any values, that is null inside res-150p.
Edit:
[Serializable]
MoviesListRootObject is the root Object which Contains Response and then Response Contains Formats
public class MoviesListRootObject
{
    public int count { get; set; }
    public Pagination pagination { get; set; }
    public List<Response> response { get; set; }
}

[Serializable]
public class Response
{
    public int id { get; set; }
    public int channel_id { get; set; }
    public string title { get; set; }
    public string title_language { get; set; }
    public string description { get; set; }
    public string description_language { get; set; }
    public string created_at { get; set; }
    public string uri { get; set; }
    public string web_uri { get; set; }
    public List<object> genres { get; set; }
    public string origin_country { get; set; }
    public string image { get; set; }
    public Subtitles subtitles { get; set; }
    public Formats formats { get; set; }
}

[Serializable]
public class Formats
{
    public string flash_embed { get; set; }
    public string m3u8 { get; set; }
    public string __invalid_name__res150p { get; set; }
    public string __invalid_name__res240p { get; set; }
    public string __invalid_name__res270p { get; set; }
    public string __invalid_name__res360p { get; set; }
    public string __invalid_name__res480p { get; set; }
    public string __invalid_name__res720p { get; set; }
    public string __invalid_name__flv480p { get; set; }
    public string __invalid_name__flv360p { get; set; }
    public string __invalid_name__flv270p { get; set; }
    public string __invalid_name__flvvp6360p { get; set; }
    public string __invalid_name__flvvp6270p { get; set; }
}

A: You have to decorate your Formats properties with JsonProperty attributes to tell it what goes where if the name does not exactly match:
partial class Formats
{
    [JsonProperty("res-150p")]
    public string __invalid_name__res150p {get; set;}
}

See also Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class


text:
Q: how to handle / in rest url in java Hi I have The following service

@RequestMapping("/users/{userid}", method=RequestMethod.GET)
public String getUser(@PathVariable String userId) {
  // implementation omitted...
}

input parameter userId = 123/4324/234
how to handle / in url
userId come from database
Please give an example


text:
Q: Issue with lazy loading Framework Entity I am using Entity with lazy loading and I have to following problem,
I'm running a query that doesn't include related properties but when I try to serialize the object, serializer is trying to load the related properties and since my context is disposed I'm getting an exception.
What I want to do is set all related properties to null when they are not loaded (some times I might include them in my query and I'd like them to be serialized in that case).
Is there a way I can do that?

A: Try following code. I use Json.Net for serialization, and set LazyLoadingEnabled = false.
using (var dbContext = new ApplicationDbContext())
{
    dbContext.Configuration.LazyLoadingEnabled = false;

    var list = dbContext.Videos.Take(5).ToList();

    var output = JsonConvert.SerializeObject(list);
}


text:
Q: Accessing a friend TTree using pyROOT I have a pyROOT script where I use TChain::AddFriend to combine two TTrees:
from ROOT import TFile, gDirectory

myfile = TFile("e.root")
mychain = gDirectory.Get("elec_gen")
entries = mychain.GetEntriesFast()

friendFile = TFile("mu.root")
friendChain = gDirectory.Get("muon_gen")
mychain.AddFriend("muon_gen")

elec_gen_evtNum = mychain.evtNum
muon_gen_evtNum = mychain.muon_gen.evtNum

When I run this I get:
$ python friendTest.py
Traceback (most recent call last):
  File "friendTest.py", line 12, in <module>
    muon_gen_evtNum = mychain.muon_gen.evtNum
AttributeError: 'TTree' object has no attribute 'muon_gen'

With the last line commented-out it runs fine. So it appears I am not accessing the leaves of the friend tree (muon_gen) correctly. How do I access them?
I also tried combining the TTrees using:
mychain.AddFriend("muon_gen","mu.root")

but this produces the same error.

A: I had a similar question, and found an answer (well, workaround) on the ROOT forum:
https://root-forum.cern.ch/t/accessing-a-friend-ttree-using-pyroot/25513
although no solution was presented using TFriend.
Instead, RobS found a workaround for his own question of just loading the two TFile and TTree separately and running LoadTree() and GetEvent() on each TChain


text:
Q: Neofetch custom config file - what is required config file format I have a question about using neofetch. As per instructions here, neofetch can be used with a custom config file from the CLI in this way (as an example):
neofetch --config home/UserAbc/Downloads/file_config.txt

The installation is described here but they dont mention how to custom config file.
Does the config file need to have a *.sh file format? eg. must the config file be saved as file_config.sh or can it be saved as file_config.txt?

A: On neofetch's first run the config file is created in $HOME/.config/neofetch/config. You can also copy the default config from /usr/share/neofetch/config. Finally you can also grab the config file from the github repo, here's the link to the config file for the latest release.
https://github.com/dylanaraps/neofetch/blob/e408e6f8d7c30c6fd649523522b51c3239b1364a/config/config
You shouldn't create the config file from scratch since you won't know what to fill it with. :)
I'll update the Readme to explain this better so that other users don't have this issue in the
future.
I hope this helps.
- Dylan,
Author of neofetch


text:
Q: Converting a wrong date into the correct format I have a wrong date in the database 2022-10-14 12:59:00 , I want to change it to 2022-14-10 12:59:00. Is there a direct convert function I could use, or do I have to split and put the date correctly. Just trying to get some ideas to do this the easy way. I tried the convert functions but I guess the original date as to be corrected first is it?

A: You can use the CONVERT() function to go from a date type to a string with a particular "style".  There are styles for different presentation formats to represent the different date presentation formats around the world.
To make this work, the data needs to be in a date type, not just a string.  (or you can convert from a string type to a date type, then convert back to a string).
Date style descriptions


text:
Q: 500 not valid database I'm using Joomfish component then it give error "500 not valid database" For my Component.
When I changed my database MySQL to mysqli then it's working fine.
Why?

A: Unless you are running PHP 5.3, the mysqli extension is not installed by default. You probably haven't installed it, or it isn't configures properly.
Please check the phpinfo() function to see if it is installed and read about setting up mysqli to see how to install and/or configure it.


text:
Q: Assigning onkeyup event to multiple objects at once I am working with qualtrics and I am trying to customize  their matrix control. I am trying to loop through a matrix with 8 rows and 4 columns where each cell contains a textbox and assign each textbox an onkeyup event like so:
for (var j=1; j< 9; j++){
        row_txt[j] = [];
        for (var k=1; k<5; k++){
            txt1= $('QR~QID2~'+j+'~'+k);
            txt1.onkeyup=function(){alert(j+','+k);};
        }
}

However, the onkeyup event returns "9,5" for each textbox changed. Why isn't it displaying the correct indices? How can I assign the same onkeyup event to multiple objects with the corresponding parameters j and k ?
Thank you

A: The issue with the value of j and k is that the actual keyup event occurs sometime in the future.  When that event occurs, the values of j and k have gotten to the end of the for loop and thus all event handlers will show the same values.
The usual way to fix this is by adding a closure that freezes the values of j and k separately for each event handler.
for (var j=1; j< 9; j++){
    row_txt[j] = [];
    for (var k=1; k<5; k++){
        (function(j, k) {
            txt1= $('QR~QID2~'+j+'~'+k);
            txt1.onkeyup=function(){alert(j+','+k);};
        })(j, k);
    }
}

Also, I'm curious what you're doing with this:
$('QR~QID2~'+j+'~'+k);

That will create something like this:
$('QR~QID2~1~9);

Are you actually using HTML tags with that tagname or should this be a class name or an id (e.g prefaced with a . or #)?


text:
Q: Intuition Behind Krantz Theorem The theorem I'm referring to is as follows:
Let $z_0$ be a root of a nonzero holomorphic function $f$ , and let $n$ be the least positive integer such that, the $n$-th derivative of $f$ evaluated at $z_0$ differs from zero. Then the power series of $f$ about $z_0$ begins with the $n$-th term, and $f$ is said to have a root of multiplicity (or "order") $n$. If $n = 1$, the root is called a simple root.
What is the intuition behind this theorem?

A: In other words, if $f(z_0)=0$, we can write $f(z)=(z-z_0)^n\cdot g(z)$ for a holomorphic function $g$, and the maximal such $n$ is called the multiplicity of the root. For example $f(z)=\cos(z)-1$ has root $0$ with multiplicity $2$, as
$$\cos(z)-1=-\frac{z^2}2+\frac{z^4}{4!}-\frac{z^6}{6!}\pm\dots$$
So we can pull out $z^2$


text:
Q: Propel uncaught error "Class not found " I am getting this Uncaught error while calling one of the classes in propel

Fatal error: Uncaught Error: Class 'Archivedb\Archivedb\AbstractQuery' not found in C:\Apache24\htdocs\archivedb\articlesOverview.php:37

The reason I am surprised to see is, it actually exits like all other classes that I am calling.
Here is my php code:
<?php

use Archivedb\Archivedb\AbstractQuery;
use Archivedb\Archivedb\ArticleQuery;
use Archivedb\Archivedb\TypeofarticleQuery;

require_once 'conf/config.php';
require_once 'default.php';

 if( !empty($_GET['magid'] && $_GET['year'] && $_GET['issue'] &&
  $_GET['magName'])){

   $magazineId = $_GET['magid'];
   $year = $_GET['year'];
   $issue = $_GET['issue'];

   $articlesArray = array();
   $articles = ArticleQuery::create()
   ->filterByMagazineId( $magazineId )
   ->filterByYear($year)
   ->distinct()
   ->filterByIssue($issue)
   ->find();

    foreach ($articles as $article) {
    $articlesArray[] = $article->toArray();
    }
   }

   $typeofarticlesArray = array();
   $types = TypeofarticleQuery::create()
   ->find();

   foreach ($types as $type) {
   $typeofarticlesArray[] = $type->toArray();
   }

   $abstract = AbstractQuery::create()
   ->filterByMagazineId($magazineId)
   ->filterByYear($year)
   ->distinct()
   ->filterByIssue($issue)
   ->find();

   $smarty->assign('issueAbstract', $abstract->getIssueAbstract());
   $smarty->assign('magazineName', $_GET['magName']);
   $smarty->assign('magid', $magazineId);
   $smarty->assign('types', $typeofarticlesArray);
   $smarty->assign('year', $year);
   $smarty->assign('issue', $issue);
   $smarty->assign('articles', $articlesArray);
   $smarty->display('views/allArticlesOverview.tpl');

In here all classes are called and are working properly except the AbstractQuery class.
I recently changed my schema.xml to add this new table, and i have done before with other tables, but never encountered this problem.
Can anyone spot, what the problem is?
and here is my table in the schema.xml :
<table name="abstract" idMethod="native" phpName="Abstract" nameSpace="Archivedb">
        <column name="id" phpName="Id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
        <column name="issue_abstract" phpName="IssueAbstract" type="LONGVARCHAR" />
        <column name="year" phpName="Year" type="INTEGER" size="11" />
        <column name="issue" phpName="Issue" type="VARCHAR" size="255" />
        <column name="magazine_id" phpName="MagazineId" type="INTEGER" size="11" />

        <foreign-key foreignTable="magazine" name="fk_abstract_magazine1" onDelete="none" onUpdate="none">
                <reference local="magazine_id" foreign="id"/>
        </foreign-key>

        <vendor type="mysql">
          <parameter name="Engine" value="InnoDB"/>
          <parameter name="Charset" value="utf8mb4"/><parameter name="Collate" value="utf8mb4_general_ci"/>
        </vendor>
    </table>


text:
Q: making matrix using numpy I want to make a matrix with 5 rows and 4 columns. The problem is when I run it there appears an error that "Traceback (most recent call last):
  File "C:\Users\yasini\Desktop\30.py", line 21, in
    ['ART|Ф',0.71], ['N|Ф',0.29], ['V|Ф',0.0001], ['P|Ф',0]]).reshape(5,4)
ValueError: total size of new array must be unchanged".
How can I solve it?
import numpy as np
A = np.array([['ART|ART',0], ['N|ART',1], ['V|ART',0], ['P|ART',0],
     ['ART|N',0.0001], ['N|N',0.13], ['V|N',0.43], ['P|N',0.44],
     ['ART|V',0.65], ['N|V',0.35], ['V|V',0.0001], ['P|V',0.0001],
     ['ART|P',0.74], ['N|P',0.26], ['V|P',0.0001], ['P|P',0.0001],
     ['ART|Ф',0.71], ['N|Ф',0.29], ['V|Ф',0.0001], ['P|Ф',0]]).reshape(5,4)
print (A)

A: Omit the reshape step and print A.shape.  How many items are there in A?  If there aren't 4*5=20, then reshape to (5,4) will produce this error.  When a step gives you an error, make sure the previous one produced what you expected.
My guess is that the shape is (20,2), and dtype is string (or maybe object).  It isn't the 20 pairs of ('str',int) tuples that you expect.
Why are you mixing names and numbers in one array?


text:
Q: How to test contextDestroyed in IntelliJ Jetty Runner I am using Intellij Jetty runner. And I implemented ServletContextListener. But I can't find a way to stop Jetty runner gracefully so that contextDestroyed is invoked. The only way to stop Jetty Runner is to click the "stop" which doesn't seem to invoke contextDestroyed

A: You might configure a stop port in your jetty runner.  In your run configuration that launches the jetty runner, add parameters similar to those in this command line:
java -jar jetty-runner.jar --stop-port 8181 --stop-key abc123

Then you need to send a stop command to that port from a separate process.  Look up the usage of the --stop parameter in conjunction with --stop-port and --stop-key on how you can launch another jetty instance that will issue the stop message to your process.
I use the jetty-maven-plugin with the appropriate stop port and stop key configured, then I invoke
mvn jetty:stop

The stop port and stop key are configured in my pom.xml like this:
<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <configuration>
        ...
        <stopKey>stop-${project.artifactId}</stopKey>
        <stopPort>${jetty.admin.stop-port}</stopPort>
    </configuration>
</plugin>


text:
Q: How to disable submit button which caused post back on ASP.NET UpdatePanel I have an UpdatePanel inside page with couple of buttons. Each button cause PostBack event. But I found that user can click multiple times in button and crash application. I want ot disable all buttons on first click until postback will be handled and new content of UpdatePanel arrived.
I tried to bind (via jquery) to 'click' event of button, set 'disabled; attribute and call 'submit' on parent form. Unfortunately is seems that this method not working - content of UpdatePanel still old.
After that I tried to override 'submit' event but faced another issue - how to submit form again if I came to my handler each time? It may be fixed with introducing flag variable, but I dislike it - another variable just increase code entropy.
Maybe I can do it somehow with ASP.NET methods?

A: Apply ajax UpdateProgress and put your code in UpdatePanel as to disable Button after first click:
<aspAtlas:UpdateProgress ID="upUpdatePanelProgress" runat="server" DisplayAfter="0"
            DynamicLayout="true" AssociatedUpdatePanelID="updpnlProgram">
            <ProgressTemplate>
                <asp:Panel ID="Panel1" CssClass="overlay" runat="server">

                        Loading...
                    </asp:Panel>
            </ProgressTemplate>
        </aspAtlas:UpdateProgress>
 <aspAtlas:UpdatePanel runat="server" ID="updpnlProgram" UpdateMode="Conditional">
        <ContentTemplate>

//--Your code in this div

 </ContentTemplate>
        <Triggers>
            <aspAtlas:PostBackTrigger ControlID="Button_ID" />
        </Triggers>
    </aspAtlas:UpdatePanel>


text:
Q: Can Android NFC Peer2Peer communicate with a non-Android NFC Device (NOT Tag)? I know Android NFC device can use Android Beam to share small size information like URL.
And, I know the Android NFC can't pretend be a tag.
In my potential Access Control project, we want to use similar tech to share 32 bytes Digital Key and Authentication ID (8 bytes) with a NFC PCB module.
Is it possible?
If it is, is there any framework or lib to provide high level API?
Do we need use low layer api to rebuild something like Android Beam?

A: Yes,It's possible.I developed one project like that before.
In non-android device, you should implement LLCP and SNEP(or NPP) protocol. And for the phone, you should develop your own application to provide the message.
In last project, we use libnfc to drive the PN532 chip on PC, then use libllcp for the LLCP layer, and implemented SNEP stack. At last develop our own service and application.
Maybe you can have a try like this way, or implement the protocols I mentioned above.


text:
Q: KryoException: Unable to find class on Linux only I get the next exception when de-serializing an object on linux server, while it works fine on my windows PC.
Exception in thread "main" com.esotericsoftware.kryo.KryoException: Unable to find class: CLASS_PATH
The object is serialized and de-serialized locally only (server or pc)
I checked the path on the server and it is the same as CLASS_PATH, with the same upper/lower cases.

A: I have classes with the same class names but in the different packages.
Using kryo registration of these classes solves the issue.
kryo.register(SomeClass.class);


text:
Q: User facing form to upload image on wordpress I have a client who bought a wordpress theme that is built for posting job listings, a user can create an account and then post job listings but my client wants it converted to post Wheel listings (car wheels).
I have converted it pretty well so far but I need to allow the user to upload an image for a listing.  A listing is simply a post but it is posted from a user facing form instead of in the admin panel.
I would like to utilize the the_post_thumbnail() is possible, is it possible for me to allow a user to upload through this without going into the admin panel?

A: You might want to check out this resource which provides a relatively simple and easy to understand snippet to achieve just that!
Link to the original source from @Matthew Price.
I have pasted the code below for the purpose longevity but please note this is not my code nor am I taking credit for its authorship.
<?php
// if you have this in a file you will need to load "wp-load.php" to get access to WP functions.  If you post to "self" with this code then WordPress is by default loaded
require $_SERVER['DOCUMENT_ROOT'] . "/wp-load.php";
// require two files that are included in the wp-admin but not on the front end.  These give you access to some special functions below.
require $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/file.php";
require $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/image.php";

// required for wp_handle_upload() to upload the file
$upload_overrides = array( 'test_form' => FALSE );

global $current_user;
get_currentuserinfo();
$logged_in_user = $current_user->ID;

// count how many files were uploaded
$count_files = count( $_FILES['files'] );

// load up a variable with the upload direcotry
$uploads = wp_upload_dir();

// foreach file uploaded do the upload
foreach ( range( 0, $count_files ) as $i ) {

    // create an array of the $_FILES for each file
    $file_array = array(
        'name'      => $_FILES['files']['name'][$i],
        'type'      => $_FILES['files']['type'][$i],
        'tmp_name'  => $_FILES['files']['tmp_name'][$i],
        'error'     => $_FILES['files']['error'][$i],
        'size'      => $_FILES['files']['size'][$i],
    );

    // check to see if the file name is not empty
    if ( !empty( $file_array['name'] ) ) {

        // upload the file to the server
        $uploaded_file = wp_handle_upload( $file_array, $upload_overrides );

        // checks the file type and stores in in a variable
        $wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );

        // set up the array of arguments for "wp_insert_post();"
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', basename( $uploaded_file['file'] ) ),
            'post_content' => '',
            'post_author' => $logged_in_user,
            'post_status' => 'inherit',
            'post_type' => 'attachment',
            'post_parent' => $_POST['post_id'],
            'guid' => $uploads['baseurl'] . '/' . $file_array['name']
        );

        // insert the attachment post type and get the ID
        $attachment_id = wp_insert_post( $attachment );

        // generate the attachment metadata
        $attach_data = wp_generate_attachment_metadata( $attachment_id, $uploaded_file['file'] );

        // update the attachment metadata
        wp_update_attachment_metadata( $attachment_id,  $attach_data );

                // this is optional and only if you want to.  it is here for reference only.
                // you could set up a separate form to give a specific user the ability to change the post thumbnail
                // set_post_thumbnail( $_POST['post_id', $attachment_id );

    }
}
// setup redirect.  i used the referer so that i can say "file uploaded" in a div if the files query string variable is set.
header("Location: " . $_SERVER['HTTP_REFERER'] . "/?files=uploaded");
?>

An example of the fron end form would be;
<!-- you can place the upload script into your theme folder or in a plugin -->
<form action="/path/to/upload/script/upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple>
    <!-- The following hidden field contains the post id for which you will be uploading images to -->
    <input type="hidden" name="post_id" value="100">
    <input type="submit" class="btn" value="Start Upload »">
</form>

You can adapt it to meet your needs.

A: You'll need to give users the ability to upload files, I've used User Role Editer to allow image uploads on a directory site. You select the user role of your general user and check the upload_files box to give them upload privileges.


text:
Q: Offline Sonar analysis to signal a broken build Sonar analysis is a nice way to check code compliance against a centrally defined policy. This is why I would like to use a profile with Blocker a Critical rules to signify a broken build.
I am using Jenkins do builds and invoke the SonarRunnerBuilder to get standard analysis on nightly builds of projects.
To achieve the features I outlined it would be best if I could run the analysis, check the results for violations (preferrably not sending them to Sonar server) and fail the build if there were any violations. So far I have not found way to do this using Google and looking through SonarRunner source code.
What I have considered is a workaround. I would implement a Decorator collecting violations and when the decoration reaches the project resource I would throw a RuntimeException to break the analysis. This would in turn fail the build.
would this work? Is there any better way to achieve this?

A: What you are looking for seems to be what the build breaker plugin offers. It relies on the Quality gate configuration to detect when violations (now called issues) in the current analysis require to break the whole build.
Please consider that this plugin won't be supported in SonarQube 5.2. Technically, deep changes in SonarQube's architecture make it impossible to provide the same feature. Philosophically, this plugin does not match the experience SonarQube wants to offer.
Still, another solution which covers the same use case is very likely to be offered in future version of SonarQube but this is yet to be defined.


text:
Q: cp from Linux to CIFS (windows) share mount is very slow I am wondering why cp command of 72GB data from linux server to a mounted CIFS (windows) share works too slow? It takes more then 3 hours already.
Is the any way to see where the gap, bottleneck?
P.S.
Both VM on XenServer 5.5 with 1GB NIC
Linux VM RHEL5.5; 4GB RAM; 4 CPU; 8GB SWAP
Windows VM Windows Server2008; 4GB RAM; 2 CPU

Are the two machines on the same ip subnet? - YES
What is the file structure like (lots of small files?) - YES
User mail boxes, /etc, /var/log what is the disk subsystem that these vm's are using? - VM are seating on iSCSI virtual disk storage which is SAN with iSCSI interface was formated with LVM support by itself.
dd if=/dev/zero of=file.txt bs=1024k count=5000 - took about 5 minutes to create and copied it in a secs.
Looks like I have some problems with network interfaces.

A: are the two machines on the same ip subnet?
what is the file structure like (lots of small files?)
what is the disk subsystem that these vm's are using?
if it is taking 3 hours then you are at about 7MB / per second
can you make a 1gb file and copy it to another part of the same disk on each of the vm's?
on windows you can create a 1gb file with the following command :
fsutil file createnew file.txt 1024000000

on linux :
dd if=/dev/zero of=file.txt bs=1k count=1000

this could tell you if it is the underlying disk system or the network config.


text:
Q: Problems with Hibernate Validator and Spring Webflow I'm trying to validate a form using Spring WebFlow and Hibernate Validator Annotations, but I'm doing something wrong.
If I use the Spring validation way (ValidationContext, MessageContext, validate${state}, etc), all works fine, but I want to use the Hibernate Annotations like @Email, @NotEmpty, etc.
I've read a lot of forums, Spring documentation, but I don't know what I'm doing wrong.
At this moment, this is my view-state and next action code:
<var name="user" class="myproject.web.pojo.User"/>

<view-state id="startSignup" model="user">
    <binder>
        <binding property="email" />
        <binding property="name" />
        <binding property="lastName" />
        <binding property="password" />
    </binder>
    <on-entry>
        <set name="flowScope.user" value="new info.teaming.web.pojo.User()" />
    </on-entry>
    <transition on="dataEntered" to="lookupUser" />
</view-state>

<action-state id="lookupUser">
    <evaluate expression="signupActions.lookupUser(user)" />
    <transition to="startSignup" on-exception="myproject.web.service.exception.UserAlreadyExistsException" />
    <transition to="saveOrder" />
</action-state>
    (...)

This is the startSignup.jsp code:

<sf:form method="POST" commandName="user" >
<input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}" />
<fieldset>

                <fmt:message key="signUp.name"/>

                <sf:input path="name" size="25" id="name" />

            <sf:errors path="name" />

                <fmt:message key="signUp.lastName"/>

                <sf:input path="lastName" size="45" maxlength="45" id="lastName" />

                <fmt:message key="signUp.password"/>

                <sf:password path="password" size="20" showPassword="true" id="password" />

                <fmt:message key="signUp.email"/>

                <sf:input path="email" size="30" id="email" />

                <input type="submit" name="_eventId_dataEntered" value="<fmt:message key="signUp.register"/>"/>

</fieldset>
 </sf:form>

This is the myproject.web.pojo.User POJO code:
import java.io.Serializable;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

@NotEmpty
@Length(min = 2, max = 25)
private String name;

@NotEmpty
@Email
private String email;

@NotEmpty
@Length(min = 2, max = 45)
private String lastName;

@NotEmpty
@Length(min = 6, max = 20)
private String password;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPassword() {
    return password;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getLastName() {
    return lastName;
}

    //  public void validateStartSignup(ValidationContext context) {
    //      MessageContext messages = context.getMessageContext();
    //
    //      messages.addMessage(new   MessageBuilder().error().source("name").code("user.name.notEmpty").build());
    //  }

  }

(note: as you can see, when I work with Spring Validation (uncomment the validate method), the form validates successfully)
And finally, this is my SignupAction code:
import myproject.web.model.UsrUser;
import myproject.web.model.dao.UsrUserDAO;
import myproject.web.pojo.User;
import myproject.web.service.exception.UserAlreadyExistsException;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Component;
import org.springframework.webflow.action.MultiAction;
import org.springframework.webflow.execution.Event;

@Component
public class SignupActions extends MultiAction {

@Resource
UsrUserDAO usrUserDAO;

private static final long serialVersionUID = 1L;

public Event lookupUser(@Valid User user) throws UserAlreadyExistsException {
    try {
        usrUserDAO.findByEmail(user.getEmail());
    } catch (javax.persistence.NoResultException e) {
        return success();
    }

    throw new UserAlreadyExistsException();
}

public void saveUser(UsrUser user) {
    return;
}

}

When I work with Hibernate Validation, the flow arrives to the saveUser method, without any validation.
I'm using Spring 3:

*

*Spring 3.0.5.RELEASE

*Spring WebFlow 2.2.1.RELEASE

*Hibernate Validator 4.0.2.GA

What I'm doing wrong?
Thanks a lot for helping me! :)

A: have you defined your validator in Spring configuration XML file?
According to Spring Webflow reference it shoud be defined like this:
<webflow:flow-registry flow-builder-services="flowBuilderServices" />

<webflow:flow-builder-services id="flowBuilderServices" validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

A: Try,
Changing:
@Resource
UsrUserDAO usrUserDAO;

By:
@Autowired
private UsrUserManager UsrUserManager;

Using MVC manager.
And:
@Transactional
public Event lookupUser(@Valid User user) throws UserAlreadyExistsException { ...

as a Spring MVC controller, or reusing this MVC code if you already desing it ;)


text:
Q: Как указать путь к файлу с использованием %USERNAME%? При создании файла или при его чтении я хочу указать путь таким образом, чтобы не приходилось вводить имя пользователя. Как это делается в windows:
C:\Users\%USERNAME%\Documents\users.xml
Но программа не понимает что такое %USERNAME%. Как решить эту проблему? Я хочу, чтобы программа запускалась на других компьютерах и хранила файл конкретно в данной папке

A: На C# это делается так.
// получить правильный путь к документам текущего пользователя
var docFolder = Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments,
        Environment.SpecialFolderOption.Create);
// добавить имя файла с учётом системно-зависимого разделителя
var path = Path.Combine(docFolder, "users.xml");

Если надо в общем случае раскрыть переменные окружения, используйте Environment.ExpandEnvironmentVariables. Но не забывайте, что домашний каталог текущего пользователя может храниться вовсе не в C:\Users\.

A: Переменная среды, хранящая путь к профилю текущего пользователя называется USERPROFILE, поэтому вам нужен путь: %USERPROFILE%\Documents\users.xml
На википедии есть перечень некоторых переменных среды: Переменная среды Windows


text:
Q: Authenticating SMTP Proxy I have acquired a number of mail users, and I'm wanting to transition them away from their current mail server and onto mine.   I've set up perdition as a proxy which will allow me to proxy IMAP and POP connections - and I have control of the DNS used to direct them to the appropriate mail server.  I do not have access to the old mail server.
The mail proxy server is running Linux
Unfortunately I suspect a lot of people are using the same server for POP3 and SMTP.
I am wanting to set up an SMTP proxy so I can seemlessly provide SMTP services to the customers during the transition - without an open mail relay.  It does not appear that Perdition offers this solution natively.
Is anyone aware of a solution which either proxies SMTP requests (including AUTH requests) - ideally with the ability to map which requests go to which backend ?   [ I've not tried an IPTables DNAT rule - I suspect this might work, but I loose the ability to do authentication to different servers on a per domain / client basis, which makes migration substantially harder ].
EDIT
I have tried configuring Dovecot as a director / proxy in place of Perdition.  This works fine for IMAP and POP, but not for SMTP - Specifically it will authenticate based on username or domain name - it does not check the actual credentials against the SMTP server.

A: For Postfix, see Andy Beverley's article SMTP Authentication and Postfix.
START=yes
MECHANISMS="rimap"
MECH_OPTIONS="imap.example.com"

I would also configure postfix to route directly to your new SMTP Server as a  relay.   Add the IP of your new server to 'my networks' and set relayhost to the new smtp server.
Point it to the perdition proxy for dovecot where the imap server is, it's plain auth between the saslauthd system and imap so you'll need to use the perdition proxy as non-secure to localhost (or just block external access to 143 pending your setup details)

A:
Is anyone aware of  a solution which … proxies SMTP requests (including AUTH requests) – ideally with the ability to map which requests go to which backend

Since Nginx 1.19.4, the Nginx mail module can fulfill all these requirements.
Instructions

*

*Follow the official "Configuring NGINX as a Mail Proxy Server". But only create one server { … } entry, for SMTP proxy.

*Enable proxying the authentication by adding directive proxy_smtp_auth on; to your server block (manual, related answer). This is the functionality that appeared first in Nginx version 1.19.4. (Check with nginx -v. Ubuntu 20.04 still has 1.18.0, for example.)

*Run an Nginx HTTP Authentication Server. This is a small server speaking a special Nginx-defined HTTP based protocol, which can be used both for authentication and for mapping requests to different SMTP backend servers.
HTTP Authentication server options

*

*Custom server script. Examples are available in Python, PHP, or Perl. Best suited for simple cases, esp. when you need the authentication server only to select the backend, while outsourcing authentication to that backend via proxy_smtp_auth  on.

*Server and SQL database. For more advanced use cases, there is the Nginx Mail Auth HTTP Server, written in Go. It can do both authentication and backend selection based on data in a SQL database.

*Nginx config for single backend referral. In the simplest case, you want to refer each client to the same backend server. This can be done with Nginx itself (see). (While this may work, I found it difficult to debug.)

*Nginx config for authentication and single backend referral. If you only need authentication and referral to a single backend server, you still can do that with Nginx itself. This uses HTTP Basic Auth, with usernames and hashed passwords stored in a file. (While this may work, I found it difficult to debug.)
Example
A complete Nginx config example would look like this (not tested, probably not fully functional yet):
mail {
    server_name smtp.example.com;

    # Configure host and port of your Nginx HTTP Authentication server.
    auth_http localhost:8278;

    proxy_pass_error_message on;

    starttls on;
    ssl_certificate     /data/cert/fullchain.pem;
    ssl_certificate_key /data/cert/privkey.pem;

    server {
        listen           25;
        listen           587;
        listen           465 ssl;
        protocol         smtp;
        smtp_auth        login plain cram-md5;
        proxy_smtp_auth  on;
    }
}

A: A Stackoverflow user had the same issue, and created their own solution for this scenario: go-smtpproxy. From the README:

The purpose of this is to provide functions that act as a server to receive SMTP messages from your downstream client. These SMTP messages are relayed through to an upstream server.
The command / response exchanges are passed on transparently.


text:
Q: R2R DAC in reverse Knowing how voltage dividers work, this probably isn't possible. But, is there a way to run an audio signal back through an R2R arrangement and get 8bit digital signals back out without complex circuitry?

A: I think you're looking for a Flash ADC:
https://en.wikipedia.org/wiki/Flash_ADC
You can't use the same arrangement though. You need a lot more resistors.


text:
Q: match numbers if line starts with keyword I've got a file that looks like this:
foo: 11.00 12.00  bar 13.00
bar: 11.00 12.00 bar
foo: 11.00 12.00

and would like to extract all numbers in lines beginning with the keyword "foo:". Expected result:
['11.00', '12.00', '13.00']
['11.00', '12.00']

Now, this is easy, if I use two regexes, like this:
    if re.match('^foo:', line):
        re.findall('\d+\.\d+', line)

but I was wondering, if it is possible to combine these into a single regex?
Thanks for your help,
MD

A: Not exactly what you asked for, but since it's recommended to use standard Python tools instead of regexes where possible, I'd do something like this:
import re

with open('numbers.txt', 'r') as f:
    [re.findall(r'\d+\.\d+', line) for line in f if line.startswith('foo')]

UPDATE
And this will return the numbers after 'foo' even if it's anywhere in the string rather than just in the beginning:
with open('numbers.txt', 'r') as f:
    [re.findall(r'\d+\.\d+', line.partition('foo')[2]) for line in f]

A: If all lines in the file always have the same number of numbers, you can use the following regex:
"^foo:[^\d]*(\d*\.\d*)[^\d]*(\d*\.\d*)[^\d]*(\d*\.\d*)"

Example:
>>> import re
>>> line = "foo: 11.00 12.00 bar 13.00"
>>> re.match("^foo:[^\d]*(\d*\.\d*)[^\d]*(\d*\.\d*)[^\d]*(\d*\.\d*)", line).groups()
('11.00', '12.00', '13.00')
>>>

Using parentheses around a part of the regular expression makes it into a group that can be extracted from the match object. See the Python documentation for more information.

A: You can do without the first regexp and instead filter lines in a list comprehension by comparing the first four characters of the line, and compile the inner regexp:
import re

with open("input.txt", "r") as inp:
    prog=re.compile("\d+\.\d+")
    results=[prog.findall(line) for line in inp if line[:4]=="foo:"]


text:
Q: django select_related vs prefetch_related in tree like table I have a model like this:
class Category(models.Model):
   name = models.CharField(max_length=20)
   parent = models.ForeignKey('self', null=True)

I do the query:
categories = Category.objects.filter(name__contains=something)

And I want to prefetch 2 levels of parents above the categories.
So I will be able to iterate them and do
category.parent.parent

without extra queries.
In SQL that will be equivalent to LEFT JOIN with the same table two times.
How to do this in django ORM?

A: If you are using category.parent.parent, you are following the foreign key forwards two times.  Therefore you can use select_related.
Category.objects.filter(name__contains=something).select_related('parent__parent')

prefetch_related would be useful if you were following the foreign key backwards (i.e. fetching the children of categories).
You may want to look at django-mptt if you are storing a tree of categories. It may make other queries more efficient.


text:
Q: How to select rows from table using particular difference between two dates? I have table "user" in db with such columns: id, url, name, update_at(DateTime), updated_ext(DateTime), created_at(DateTime).
I need to select all rows, with particular conditions:

*

*If in column updated_at the date has difference between today more than 1 day (the name of the variable is on_start)

*If the difference between columns updated_at and updated_ext less than 48 hours (the name of the variable is in_two_days)

on_start = (datetime.now() - timedelta(days=1)),
in_two_days = (datetime.now() - timedelta(days=2))
    q = session.query(user).filter(
        user.object_type == object_type,
        or_(
            user.updated_at <= on_start,
            ((user.updated_at - user.updated_external) < in_two_days)
        )
    )

When I try to run it, I got

HINT:  No operator matches the given name and argument types. You
might need to add explicit type casts.

because I try to find the difference between two dates (updated_at and updated_ext and inside the format like this 'updated_at_1': (datetime.datetime(2021, 7, 8, 11, 5, 3, 620971),), 'param_1': datetime.datetime(2021, 7, 7, 11, 5, 3, 620978)).
Is there another solution to compare two dates?
thanks a lot

A: Bit confusing but I think I know what you mean. This should return an array of indexes where this condition is true
df = your_database
indx_array = where(np.logical_and(user.updated_at <= on_start, (user.updated_at - user.updated_external) < in_two_days))

Edit:
You could also use np.where() to return certain values where the condition is true and false. see https://numpy.org/doc/1.20/reference/generated/numpy.where.html


text:
Q: How do I import the JRE System Library into an existing Java project in Visual Studio Code? I'm currently running Ubuntu 20.04 and have installed openjdk-17-jdk. I also installed the extension pack for Java in VS Code. Creating a new Java project in VS Code includes the JRE System Library from the beginning.
However, when opening an existing Java project (without Maven or Gradle), libraries like java.util or java.io cannot be resolved. The project only contains "Referenced Libraries", missing the JRE System Library.
Both java.configuration.runtimes and java.home are set to /usr/lib/jvm/java-17-openjdk-amd64.
How do I include the JRE System Library when importing a project? How come I even have to do this?


text:
Q: StyleInterval with cut in column I recently started exploring DT and I am stuck on something. Imagine the following table:
dt <- data.table(group = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                 group2 = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                 interval = c(NA, NA, 100, NA, NA, 150, NA, NA, 100),
                 value1 = c(1000, 10, 90, 2000, 30, 120, 1500, 25, 150),
                 value2 = c(1200, 10, 110, 2500, 35, 145, 2200, 40, 90))

Now I want to create a DT with a Style that checks the value in value1 and value2 and compares it with the value in Interval. I tried something like this:
datatable(dt) %>% formatStyle(
    columns = c("value1", "value2"),
    backgroundColor = styleInterval(interval, c("red", "green"))
)

But interval is not recognized as an object. This leads me to believe that I cannot pass a column in the cut parameter. I also tried to pass some kind of function in the valueColumns but this didn't seem to be possible either.
Expected output:

A: It makes no sense to pass the full column to styleInterval. It requires n values for cut and n+1 for values. Try alternative below instead:
myCut <- sort(unique(dt$interval))
myCol <- rainbow(length(myCut) + 1)

formatStyle(datatable(dt),
  columns = c("value1", "value2"),
  backgroundColor = styleInterval(myCut, myCol))


text:
Q: SQL subqueries errors Using the AdventureWorks2012 database, I have to change the query below to select the       top 10% orders with CustomerId greater than 500 and sequence the orders by TotalDue in descending sequence.
 SELECT *
 FROM Sales.SalesOrderHeader h
 INNER JOIN Sales.SalesOrderDetail d
 ON d.SalesOrderId = h.SalesOrderId

Here are two of my attempts at solving the problem, but both contain errors:
  Msg 156, Level 15, State 1, Line 9
  Incorrect syntax near the keyword 'DESC'.
  Msg 156, Level 15, State 1, Line 12
  Incorrect syntax near the keyword 'FROM'.

Attempt 1
 SELECT *
 FROM SalesOrderHeader
 WHERE SalesOrderID IN
 (SELECT TOP 10 PERCENT SalesOrderID
 FROM SalesOrderDetail
 WHERE SalesOrderID > 500
 ORDER BY TotalDue DESC);

What am I doing wrong?  Thanks.

UPDATE:  I removed the comma from the ORDER BY section and managed to execute the query from my first attempt.  However, I get an seemingly endless "Executing Successfully" load.  In other words, I'm getting over 3000 results and counting when I modified the query below:
    SELECT *
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID IN
(SELECT TOP 10 PERCENT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE CustomerID > 500
ORDER BY TotalDue DESC);


text:
Q: How to pause and restart a css3 transition in jquery transit I'm using jquery transit to move and element. I want to pause the animation and continue it  on click of a button. But i'm unable to figure out how to do it.
JSFiddle : http://jsfiddle.net/b4hwq/2/
I did try
stop().transition({});

but it is throwing an error.

A: You can use clearQueue() to stop the animation

clearQueue() : Stop the remaining functions in the queue

jsFiddle here
HTML

<button id="restartTransition">Click Me</button>

CSS
.box{
    opacity: 0.8;
position: absolute;
left: 0;
top: 5%;
background: #505060;
border-radius: 1px;
box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.2);
margin: -16px 0 0 -16px;
width: 32px;
height: 32px;
z-index: 2;
}

jQuery
$(document).ready(function(){
    $("#restartTransition").on("click", function(){
        $('.box').clearQueue().transition({ x: '0px' },10);
        $('.box').transition({ x: '350px' },5000);
    });
});

A: I have update the fiddle with the complete function from the transit library:
$('.box').transition({
            x: '350px',
            duration: 5000,
            complete: function() {
                alert("complete!");
            }
        });

jsfiddle
The complete function is still executed even when using clearQueue() or stop()

A: You were most of the way there with .stop() I just added a little logic to tell it what to do when it stops.
Working Example
$('button').click(function () {
    if (!$('.box').hasClass('stop')) { // if the box does not have class "stop"
        $('.box').stop().transition({  // stop the transition
            x: $('.box').offset().left + $('.box').width() / 2  // where the box should be when it stops
        }, 1).addClass('stop'); // simple add class for easy button control
    } else { // if the box has class "stop"
        $('.box').transition({
            x: '350px'
        }, 5000).removeClass('stop'); // continue with regularly scheduled programming then remove "stop"
    }
});


text:
Q: Running nano WinSSHD and Putty I have following setup;

*

*Windows 7 running WinSSHD

*GitBash (WinSSHD launches this as console when connected)

*Nano 2.2.6 WIN32 version

*Remote Windows with Putty connected via ssh to above server

Everything else works just fine; console, VIM, git, etc. But when I start my favourite editor nano, the keyboard is not working correctly; Arrow keys respond with [ unknown command ], Alt (or AltGr) is completely ignored, as in Finnish keyboard the {[]} are coming from AltGr+7890, so it is tricky to compose code.
I can move around with the Ctrl + P,N,F and B -keys
Nano works fine when started from local cmd-prompt or from gitbash-shell.
Is there any way to fix this keyboard issue with my configuration?


text:
Q: Python cdecimal.Decimal and SQLAlchemy _mysql_exceptions.Warning I am building a django app that uses SQLAlchemy over MySQL. I am using cdecimal instead of the built in Decimal.
In one of my tables, I have a Numeric value column (value = Column(Numeric(10, 5)).
When I create a new entry for this table in my django app, with the following SQL echo:
INSERT INTO my_table (date, value) VALUES (2012-03-11, 875334.670)

This causes the following exception to be thrown upon commit:
_mysql_exceptions.Warning: Out of range value for column 'value' at row 1

When I run the same query in the mysql client, no issues at all.
I even tried wrapping the code that adds the entry with:
import warnings
from sqlalchemy import exc as sa_exc
with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=sa_exc.SAWarning)

What is going on?
Thanks!

A: Try this:
INSERT INTO my_table (date, value) VALUES ('2012-03-11', 875334.670)

A: Here is the issue:
>>> import cdecimal
>>> cdecimal.Decimal(1.23)
Decimal('1.229999999999999982236431605997495353221893310546875')
>>> cdecimal.Decimal('1.23')
Decimal('1.23')
>>>


text:
Q: How can the film of 'World War Z' claim to be based on the book? I've just finished reading the book World War Z and I'm struggling to see how the film World War Z can claim to be 'based on the book'.
The only three things I can see that match in the book and film are:

*

*The title.

*The bit about the Israeli '10th man'.

*Both have zombies in them.

Beyond that, nothing from the book is in the film and nothing from the film is in the book.
So, how can it claim to be based on the book?
[Footnote: I saw the film first so was pleasantly surprised that the book was much better. If I'd have read the book then seen the film, it would have been a great disapointment]

A: In short - its "based" on the book because Max Brooks sold the rights for a movie under the same title.
So the book and the movie have (almost) the same title and they are both about zombies. More or less that's all they have in common.
According to the interview with Max Brooks about the movie :

 :

Interviewer: Which brings me to the movie of the same title
Max Brooks: And pretty much that's all it has. At least what I have seen. I have not read the script
  ...
  looks like "World War Z" name only

A bit later in the interview Brooks also says that after he decided to sell the movie rights to Brad Pitt's studio:

That was pretty much the last decision I was allowed to make.

So practically the movie was done without the involvement of the book author.

A: I was hitch-hiking once and the guy who picked me up turned out to be a scriptwriter. We discussed this issue in general and came to the conclusion that it is impossible to make good movies from good books.
Movies require plot, dialog and action, and not too much of even these - there's only 100 minutes or so available. Good books have long descriptions of scenery, feelings, inner dialogues, weather, what someone would have thought if this other thing had happened, etc. How would you film any of that? Good books frequently have little plot. Good books sometimes have very complicated plots that would be impossible to make into a film of less than ten hours in length. Some great books have very little in the way of characters speaking. How do you film irony? Jane Austen can be hilarious in print, but filmed her novels always become vapid boy-meets-girl costume dramas.
Authors know all this, so if they agree to sell the rights, they do not have much cause to complain if the film turns out very different from their vision or is just plain bad. Filmmakers will buy the rights to a blockbuster with the intent to capitalize on the name but in full knowledge that the book is impossible to make a movie of.


text:
Q: Thoughts on how to navigate between many-to-many relations in Entity Framework 4.1 I am not a huge fan of having to place navigation properties on the objects that are shared by multiple entities in a model. Here is an example of what I am talking about:
    public abstract class SomeEntity
    {
       public Guid Id {get;set;
       public virtual ICollection<Attachment> Attachements {get;set;}
    }

    public class User: SomeEntity
    {
         ...
    }

    public class Thing: SomeEntity
    {
         ...
    }

    public class Attachment
    {
       public Guid Id {get;set;}
       ...
    }

I have tired to avoid having navigation properties on the Attachment entity for Users and Things. My thought behind that is to avoid situations where we are using Lazy Loading.
One thought was to have a ICollection<SomeEntity> Entites on an Attachemnt, but not sure that would work, because I have run into mapping issues with that before. Another thought I had was to manually navigate from Attachments to the entities, but that would mean having to write a method to pass back a collection of objects and figuring out their types.
I am having EF generate link tables like this:
HasMany(e => e.Attachments).WithMany().Map(m => { m.MapLeftKey("AttachmentId");
                                                                  m.MapRightKey("UserId");
                                                                  m.ToTable("User_Attachments");
            });

Looking at my Attachments table there is no FK back to any of the link tables. Which makes sense, because I am not navigating back to them.

A: If you are worried about lazy loading, then you could make the navigation property not virtual so that it will never kick in lazy loading.
Or you could make the navigation property private and then access the contents in a controlled manner. Once you make the navigation property private you will need to use one of the tricks for mapping private properties using the Code First API.  For simplicity I'm using the one that embeds the EntityConfiguration inside the entity:
public class Attachment
{
    public Guid Id { get; set; }

    private ICollection<User> Users { get; set; }

    public class AttachmentConfiguration : EntityTypeConfiguration<Attachment>
    {
        public AttachmentConfiguration()
        {
            HasMany(e => e.Users)
                .WithMany(e => e.Attachements)
                .Map(m =>
                     {
                         m.MapLeftKey("UserId");
                         m.MapRightKey("AttachmentId");
                         m.ToTable("User_Attachments");
                     });
        }
    }
}

Add this configuration inside OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new Attachment.AttachmentConfiguration());
}

You can then access Users from inside Attachment in any way you want or expose the users from methods, etc.
You could also use the DbContext change tracker API to access them from anywhere you have a context. For example:
var users = context.Entry(attachment).Collection<User>("Users").CurrentValue;

If you really want no navigation property at all, then you could drop down to ObjectContext and get the RelatedEnd for the collection, which will be an EntityCollection. This is pretty tricky code for a number of reasons, including needing to know the conceptual model names for the association and end names, which you could find by dumping the EDMX. I'd avoid this approach if at all possible.


text:
Q: Potential downtime during MSI upgrade I'm considering deploying websites to an Win2k3/IIS6 machine using a MSI built with WiX.
The website in question has a collection of .html, .jpg, .js, .swf & .asp files (no ASP.NET)
I'm doing a "Major Upgrade" when installing the MSI (i.e, it first uninstalls the old MSI, then installs the new MSI).  This is the only way I can figure to get the MSI to remove redundant files.
My question is; will there be any downtime for visitors to the site during the uninstall / reinstall process?
Or does IIS cache the files being used by currently open connections?

A: No, you'll definitely be in an outage.  It does not cache that info.

A: If you're that concerned about downtime, you should be thinking about load balancing and redundant webservers.