text:
Q: Too many indices error, in my already micro dataset This is my small test CSV file, because I'm trying to isolate the error.
Destination Port    Flow Duration   Total Fwd Packets   Labels
22  20  100 BENIGN
21  30  200 BENIGN
43  30  100 Bot
15  11  203 Bot

So when I run the following code, to preprocess the data,
import csv
# import itertools
import os
from os.path import join as os_join
import numpy as np

dataroot = r'D:\DDOS\testing_too_many_indices'

attacks = {'BENIGN': 0, 'Bot': 1}
# and many others

features = ['Destination Port', 'Flow Duration', 'Total Fwd Packets']

np.random.seed(1202)

def get_filenames(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isfile(os.path.join(a_dir, name))]

def read_csv(filename, sampling_rate=100):
    with open(filename) as csv_file:
        print('Reading {} ...'.format(filename))
        reader = csv.reader(csv_file)
        # header = next(reader)
        data = [row for row in reader]
        print('#{} rows read'.format(len(data)))
        N = len(data)
        sample_size = N*sampling_rate//100
        indices = np.random.randint(0, N, sample_size)
        sampled_data = [data[i] for i in indices]
    return sampled_data

def read_data(dataroot, sampling_rate=10, seed=0):
    np.random.seed(seed)
    filenames = get_filenames(dataroot)
    data = []
    for filename in filenames:
        data_part = read_csv(os_join(dataroot, filename), sampling_rate)
        data += data_part
    return data

data = read_data(dataroot, sampling_rate=10)

arr = np.array(data)
# X contains feature values and Y the output values.
X = arr[:, :-1].astype(np.float32)  # ERROR HERE.
Y_str = arr[:, -1]

I get the error as follows:-
File "/some_path/temp.py", line 63, in <module>
    X = arr[:, :-1].astype(np.float32)

IndexError: too many indices for array

What should I do? I've wracked my brains on other possibly duplicate links like this one, and this one, etc. Also made the above sample snippet to test in isolation, read about 2D slicing and yet am clueless. Can you help me?


text:
Q: Unable to create a new column using a function in R I'm trying to create a new column within a function.  Basically, I want to use a function to create a new field, based on an old field (using string searching).  Having no luck:
old_field <- c("September 2012", "September 2012")
case_id <- c("1","1")
my_df <- data.frame(case_id, old_field)

old_date_to_new_date <- function(df, new_date, old_date) {

     df[[new_date]][grepl('Sep', old_date, ignore.case = TRUE)] <- '09-01' #if 'sep' found in old date field, put "09-01" in new date field.
     df[[new_date]][grepl('2012', old_date, ignore.case = TRUE)] <- paste('2012-',new_date,sep='')# add year to new date field
    }

    old_date_to_new_date (my_df,"new_field","old_field")

The function runs just fine, but fails to add the new column to the dataframe.  I've tested this and I can't even modify anything within the dataframe using the function.  Code works fine outside of the function and does what expected.  I've tried adding a return(df) statement within the function but still no luck.

A: We need to return the data along with get the value of the column using [[
old_date_to_new_date <- function(df, new_date, old_date) {
     i1 <- grepl('Sep', df[[old_date]], ignore.case = TRUE)
     i2 <- grepl('2012', df[[old_date]], ignore.case = TRUE)
     df[[new_date]][i1] <- '09-01' #if 'sep' found in old date field, put "09-01" in new date field.
     df[[new_date]][i2] <- paste('2012-',df[[new_date]][i2],sep='')# add year to new date field
     df
    }

old_date_to_new_date (my_df,"new_field","old_field")
#   case_id      old_field  new_field
#1       1 September 2012 2012-09-01
#2       1 September 2012 2012-09-01

NOTE: If we need to update the original object, assign the output back to the original object
my_df <- old_date_to_new_date (my_df,"new_field","old_field")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a DAG using the REST API Is it possible to create, by sending the DAG file contents, to Apache Airflow using the API?
For example, it is possible to list all DAGs using the API
curl -u "admin:admin" http://localhost:8080/api/v1/dags
{
  "dags": [],
  "total_entries": 0
}

A: You can not create new DAGs via API.
You can read a discussion about this request in the project https://github.com/apache/airflow/discussions/24744 which also lists the reasons why Airflow won't have it.
In simple words by adding such API it means that the machine(s) where DAGs are deployed to need to have credentials to write those DAG files to all the other components.
For such use case you better to use Git sync to add files to the DAG directory.


text:
Q: Are start and end states in HMM, necessary when implementing the Viterbi Algorithm for POS tagging? I do not fully understand how to use the start and end states in the Hidden Markov Model. Are these necessary in order to design and implement the transition and emission matrices?

A: The start/end states are necessary for modeling whether a tag is likely to come at the beginning or end of a sentence.
For example, if you had a five-word sentence and you were considering two taggings

*

*Det Noun Verb Det Noun

*Det Noun Verb Det Adj

Both of these look pretty good in terms of transitions because Det->Noun and Det->Adj are both very likely.  BUT, it is much less for a sentence to end in an Adj than a Noun, something that you would not get without an end tag.  So what you really want to compare is

*

*START Det Noun Verb Det Noun END

*START Det Noun Verb Det Adj END

Then you will be computing P(END|Noun) and P(END|Adj).

If you're doing supervised training, then getting the probabilities with START/END is no different than the other tags, you just have to append the special tags to each sentence before counting.  So if your training corpus has:
Det Noun Verb
Det Noun Verb Det Noun

Then you would modify it to be
START Det Noun Verb END
START Det Noun Verb Det Noun END

And compute, for example:

*

*P(Det|START) = 2/2

*P(END|Verb) = 1/2

*P(END|Noun) = 1/3

Also, emissions are trivial: P(START|START)=1 and P(END|END)=1

A: I think this question really depends on your corpus. If, say, the corpus you are using consist of full sentences (semantically speaking), then I suggest you add the start and end states, to improve the language model. But if the corpus are full of sentence fragments, then I don't think start/end states will help. They may even backfire.
Basically, in pos tagging, start states try to model what kind of tags are more likely to appear at the beginning of a sentence. The end states are likewise. So if the sentences in your corpus are really sentences, these start/end states will teach your language model how to begin or finish a sentence.


text:
Q: How can i add items to my generic custom list without using the .Add() method? My question is in the title.
How can I add items to my generic, custom list without using the .Add() method ?
public class MyArray<T>
{
    public List<T> _myArray;

    public MyArray()
    {
        _myArray = new List<T>();
    }

    public void Add(T obj)
    {
        //I wanna add item without using the .Add() method.
    }
}

A: Well, you can create an index variable internally:
class MyArray<T>
{
      public List<T> _myArray;
      private int index = 0;

      public MyArray()
      {
          _myArray = new List<T>();
      }

      public void Add(T obj)
      {
          _myArray[index++] = obj;
      }
}

Note, that if/when you add a Remove method, you'll need to make sure the index value is modified to accommodate the change etc.


text:
Q: How to retrieve values related to a hash key present in a Array of Hashes I am using Ruby on Rails 3.2.2 and I would like to retrieve values related to a hash key present in a Array of Hashes. That is, I have the following Array of Hashes:
[
  {
    :key1 => value_a_1,
    :key2 => value_a_2
  },
  {
    :key1 => value_b_1,
    :key2 => value_b_2
  },
  {
    :key1 => value_c_1,
    :key2 => value_c_2
  }
]

I would like to "retrieve" / "build" the following:
[ value_a_1, value_b_1, value_c_1 ]

How can I make that the proper way?

A: If a is the array:
a.map { |i| i[:key1] }


text:
Q: Sending Email with php / own seerver I'm wondering how you send a mail with the data filled in in a form. I have read that you can't adjust the php code, to prevent the mail entering the spam folder.
I have read that the server, which you send it from, responsible is for this.
I'm making a CMS on a server from school , for a school project. How can i fix the server settings or something to prevent that the email with register data goes to the spam folder.
Just like facebook (if you register you get a validation link in your mailbox), how did they prevent that the mail doesn't enter the spam folder?
Thanks in advance!

A: Honestly, I'd recommend you to use something like Mailgun. They take care of all that stuff so that you can focus on your app.


text:
Q: use of the word "assume" in this sentence Apologies for the bad question title, I lack sufficient vocabulary. From the vocabulary I know I could not find a duplicate question.
I am having trouble understanding how the word "assume" can be used in this sentence (from Google define: "Social Proof"):
"Social proof:
Social proof, also known as informational social influence, is a psychological phenomenon where people assume the actions of others in an attempt to reflect correct behavior for a given situation."

A: For me, to assume the actions of others means to: make the actions of others one's own by copying or imitating those actions (behavior). I would have written the sentence differently:
behave as others do in an attempt to act in a manner perceived as correct in a given situation.

A: The original meaning of assume is "take on": it is still used in this meaning with objects like "role", "position", "authority", but it is rather literary.
So "assume the actions of others" (in a scholarly text) means "take on the actions of those others", or in simpler language, "copy them".
In normal use, the later meaning draw a conclusion or more particularly act on a conclusion drawn is much more common.


text:
Q: Multiple text boxes when making an Oracle Report to Adobe reader I have an Oracle Report, which creates a report with multiple fields of text, and saves it in Adobe Reader format. This report is made into three different languages (three reports on the same template).
The problem I'm having is, when opened with Adobe Reader Professional, the report has one large textbox in one language, and a few different textboxes in another language. I need that all the text in the reports would always be in one textbox in Adobe Reader format, and not in multiple textboxes.
Is it possible to do that?


text:
Q: outputLimits Matlab equivalent for python I am trying to convert a matlab code to python, unfortunately I am facing the problem that I don't find an equivalent of the matlab function outputLimits.
The function is suppose to :
Estimate the output spatial limits corresponding to a set of input spatial limits, xLimitsIn and yLimitsIn, given 2-D geometric transformation tform.
Maybe it exists an equivalent in opencv but I can't find it.
The matlab source is : https://de.mathworks.com/help/images/ref/affinetform2d.outputlimits.html

A: If you take the corner points of the original image, and transform them using the tform matrix, you will get their new location. These new locations will be the output limits of the new image.


text:
Q: How to Upgrade to Linuxmint 17.2 In the Linux Mint upgrade manual I found this entry:

Upgrading to 17.2 is relatively easy:
In the Update Manager, click on the Refresh button to check for any
new version of mintupdate and mint-upgrade-info. If there are updates
for these packages, apply them. Launch the System Upgrade by clicking
on "Edit->Upgrade to Linux Mint 17.2 Rafaela".

but in the Update Manager I don't have that option
My update manager Screen Shot:

how do I make this option available?

A: The common way of upgrading Linux Mint is the Update Manager, but there is always the lesser known alternative, using the command line. To do so open a terminal and type:
sudo cp -v /etc/apt/sources.list.d/official-package-repositories.list /etc/apt/sources.list.d/official-package-repositories.list.bak
Press [ENTER] and then type your password when prompted. Then replace your Qiana sources with Rebecca sources:
sudo sed -i 's/qiana/rebecca/g' /etc/apt/sources.list.d/official-package-repositories.list
Then update your repository list with sudo apt-get update. It should not take over 2-3 minutes. Then perform the actual upgrade with sudo apt-get dist-upgrade. This should take a while (It could take a VERY long time if you have slower hardware). When it is finished updating, reboot your computer, and you should be running 17.2 Rafaela.
A note of Caution
Although the correct way of upgrading from the command line, this method is not without risk, and it sometimes fails. As the old saying goes, "If it ain't broke, don't fix it". This applies here as well. If Qiana is working fine and there is no actual need for an OS upgrade, then stick with what works. If you are curious(which is a good thing), then you can go ahead and follow these instructions carefully, although I highly recommend making either a full backup of your computer, or at least moving all your important files and documents into a directory and ZIPing it... If you are upgrading because there is an important bug fix or feature in the new update, then by all means, go ahead and update - just be careful.
For more information on upgrading to Rafaela, go to this page.
Regards,
Interesting...


text:
Q: How to inject converting String to class in Google Guice 3.0 I am trying Google Guice3.0 for light-weight DI. I would like to read properties and convert it to Class type and inject to a class. Here is my code.
setting.properties
port = 31200
handler=com.mypackage.handler.MyHandler

Module
public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        Properties properties = new Properties();
        try {
            properties.load(getClass().getResourceAsStream("setting.properties"));
            Names.bindProperties(binder(), properties);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

@Singleton
public class MyServer {

     @Inject @Name("port") int port;

     @Inject @Name("handler") Class<? extends BaseHandler> handlerClass;
}

public interface BaseHanlder {
   //
}

public MyHandler implements BaseHandler {
  //
}

I want to convert handler property from the properties to Class and inject it into MyServer. How can I achieve it?
Thanks in advance.

A: Like @gontard said, this works as Guice already contains converter for class.
It uses Class.forName(fqn) to get the Class.
You can add other custom converters using the Pluggable Type Converters see Binder#convertToTypes.
By default you have converters for all primitives types, enums and class. For implementation details you can see here.


text:
Q: A min-heap with better than O(logn) increase key? I'm using a priority queue that initially bases the priority of its elements on a heuristic.  As elements are dequeued the heuristic is updated and elements currently in the queue may have their keys increased.
I know there are heaps (Fibonacci heaps specifically) that have amortized O(1) decrease key operations, but are there any heap structures that have similar bounds on the increase key operations?
For my application this is far from a performance issue (a binary heap works fine) it's really just about academic curiosity.
Edit: to clarify, I'm looking for a data structure that has a faster than O(logn) time for the increase key operation, not decrease key.  My application never decreases the key as the heuristic over-estimates the priority.

A: Binary heaps are too unflexible to beat logarithmic complexity.
Binomial heaps just allow a more efficient join-operation.
Other heaps with good decrease-key performance are pairing heaps and 2-3 heaps

A: Binomial heaps take o(log n) time for decrease key operations! Isn't this slower than fibonacci heaps?

A: Actually, with Fibonacci heaps, the increase key operation is the same as decrease key. IMHO, it is only a tradition to name the operation "decrease key", because it is used in some algorithms. But the Fibonacci heap implementation allows both.


text:
Q: difference between foldLeft and reduceLeft in Scala I have learned the basic difference between foldLeft and reduceLeft
foldLeft:

*

*initial value has to be passed

reduceLeft:

*

*takes first element of the collection as initial value

*throws exception if collection is empty

Is there any other difference ?
Any specific reason to have two methods with similar functionality?

A: For reference, reduceLeft will error if applied to an empty container with the following error.
java.lang.UnsupportedOperationException: empty.reduceLeft

Reworking the code to use
myList foldLeft(List[String]()) {(a,b) => a+b}

is one potential option.  Another is to use the reduceLeftOption variant which returns an Option wrapped result.
myList reduceLeftOption {(a,b) => a+b} match {
  case None    => // handle no result as necessary
  case Some(v) => println(v)
}

A: foldLeft is more generic, you can use it to produce something completely different than what you originally put in. Whereas reduceLeft can only produce an end result of the same type or super type of the collection type. For example:
List(1,3,5).foldLeft(0) { _ + _ }
List(1,3,5).foldLeft(List[String]()) { (a, b) => b.toString :: a }

The foldLeft will apply the closure with the last folded result (first time using initial value) and the next value.
reduceLeft on the other hand will first combine two values from the list and apply those to the closure. Next it will combine the rest of the values with the cumulative result. See:
List(1,3,5).reduceLeft { (a, b) => println("a " + a + ", b " + b); a + b }

If the list is empty foldLeft can present the initial value as a legal result. reduceLeft on the other hand does not have a legal value if it can't find at least one value in the list.

A: The basic reason they are both in Scala standard library is probably because they are both in Haskell standard library (called foldl and foldl1). If reduceLeft wasn't, it would quite often be defined as a convenience method in different projects.

A: From Functional Programming Principles in Scala (Martin Odersky):

The function reduceLeft is defined in terms of a more general function, foldLeft.
foldLeft is like reduceLeft but takes an accumulator z, as an additional parameter, which is returned when foldLeft is called on an empty list:
(List (x1, ..., xn) foldLeft z)(op) =  (...(z op x1) op ...) op x

[as opposed to reduceLeft, which throws an exception when called on an empty list.]
The course (see lecture 5.5) provides abstract definitions of these functions, which illustrates their differences, although they are very similar in their use of pattern matching and recursion.
abstract class List[T] { ...
  def reduceLeft(op: (T,T)=>T) : T = this match{
    case Nil     => throw new Error("Nil.reduceLeft")
    case x :: xs => (xs foldLeft x)(op)
  }
  def foldLeft[U](z: U)(op: (U,T)=>U): U = this match{
    case Nil     => z
    case x :: xs => (xs foldLeft op(z, x))(op)
  }
}

Note that foldLeft returns a value of type U, which is not necessarily the same type as List[T], but reduceLeft returns a value of the same type as the list).

A: Few things to mention here, before giving the actual answer:

*

*Your question doesn't have anything to do with left, it's rather about the difference between reducing and folding

*The difference is not the implementation at all, just look at the signatures.

*The question doesn't have anything to do with Scala in particular, it's rather about the two concepts of functional programming.

Back to your question:
Here is the signature of foldLeft (could also have been foldRight for the point I'm going to make):
def foldLeft [B] (z: B)(f: (B, A) => B): B

And here is the signature of reduceLeft (again the direction doesn't matter here)
def reduceLeft [B >: A] (f: (B, A) => B): B

These two look very similar and thus caused the confusion. reduceLeft is a special case of foldLeft (which by the way means that you sometimes can express the same thing by using either of them).
When you call reduceLeft say on a List[Int] it will literally reduce the whole list of integers into a single value, which is going to be of type Int (or a supertype of Int, hence [B >: A]).
When you call foldLeft say on a List[Int] it will fold the whole list (imagine rolling a piece of paper) into a single value, but this value doesn't have to be even related to Int (hence [B]).
Here is an example:
def listWithSum(numbers: List[Int]) = numbers.foldLeft((List.empty[Int], 0)) {
   (resultingTuple, currentInteger) =>
      (currentInteger :: resultingTuple._1, currentInteger + resultingTuple._2)
}

This method takes a List[Int] and returns a Tuple2[List[Int], Int] or (List[Int], Int). It calculates the sum and returns a tuple with a list of integers and it's sum. By the way the list is returned backwards, because we used foldLeft instead of foldRight.
Watch One Fold to rule them all for a more in depth explanation.

A: reduceLeft is just a convenience method. It is equivalent to
list.tail.foldLeft(list.head)(_)

A: To really understand what are you doing with fold/reduce,
check this: http://wiki.tcl.tk/17983
very good explanation. once you get the concept of fold,
reduce will come together with the answer above:
list.tail.foldLeft(list.head)(_)

A: Scala 2.13.3, Demo:
val names = List("Foo", "Bar")
println("ReduceLeft: "+ names.reduceLeft(_+_))
println("ReduceRight: "+ names.reduceRight(_+_))
println("Fold: "+ names.fold("Other")(_+_))
println("FoldLeft: "+ names.foldLeft("Other")(_+_))
println("FoldRight: "+ names.foldRight("Other")(_+_))

outputs:
ReduceLeft: FooBar
ReduceRight: FooBar
Fold: OtherFooBar
FoldLeft: OtherFooBar
FoldRight: FooBarOther


text:
Q: getting null pointer exception exporting data from database to xml Im trying this java code to export data from database using sql query, But getting a null pointer exception. getting no clue to remove it . Im getting this exception at the line in Bold font.
try {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);

    Class.forName("oracle.jdbc.OracleDriver");
    Connection con = DriverManager
            .getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");

    ResultSet rs = con.createStatement().executeQuery("select * from departments");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            row.appendChild(node);
            **node.appendChild(doc.createTextNode(value.toString()));**
        }
    }

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();

} catch (Exception e) {
    e.printStackTrace();
}

Stack trace :
java.lang.NullPointerException
at org.ProjectXML.ui.DataBaseToXML.main(DataBaseToXML.java:61)

Any ideas?

A: The trick is to add this simple piece of code inside the while loop:
if (value != null)
  node.appendChild(doc.createTextNode(value.toString()));
else
  node.appendChild(doc.createTextNode(""));
  row.appendChild(node);

Full code:
public static String ConvertToXML1(ResultSet rs, String view)
  throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement(view);
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
      Element row = doc.createElement("Row");
      results.appendChild(row);
      for (int i = 1; i <= colCount; i++) {
        String columnName = rsmd.getColumnName(i);
        Object value = rs.getObject(i);
        Element node = doc.createElement(columnName);
        // The added code is here
        if (value != null)
          node.appendChild(doc.createTextNode(value.toString()));
        else
          node.appendChild(doc.createTextNode(""));
        row.appendChild(node);
      }
    }

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);

    transformer.transform(domSource, sr);

    return sw.toString();
  }


text:
Q: Error in if (condition) with the arguments dms2deg I´ve download the package celestial in R to convert data from degree minutes seconds to degrees format but an error appear. The data is in Longitude and Latitude in this format 80'13'007.
targetCounts$LongitudeDD <- dms2deg(targetCounts$Longitude, sep = "'")
targetCounts$LatitudeDD <- dms2deg(targetCounts$Latitude, sep = "'")

Error in if (any(d < -90 | d > 90) & sign[1] == "d") { :
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(d, -90) : '<' not meaningful for factors
2: In Ops.factor(d, 90) : '>' not meaningful for factors

targetCounts$LongitudeDD <- dms2deg(targetCounts$Longitude, sign = "d", sep = "'")

Error in if (any(d < -90 | d > 90) & sign[1] == "d") { :
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(d, -90) : '<' not meaningful for factors
2: In Ops.factor(d, 90) : '>' not meaningful for factors

There is no blank space in my data, so now I know that is not the problem.
> is.na(targetCounts$Longitude)
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[16] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[31] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[46] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[61] FALSE FALSE FALSE FALSE FALSE

> str(targetCounts)
'data.frame':   65 obs. of  5 variables:
 $ Trip     : int  1638 1638 1638 1638 1638 1638 1639 1639 1639 1639 ...
 $ Lance    : int  1 2 3 4 5 6 1 2 3 4 ...
 $ Fecha    : Factor w/ 54 levels "01/04/2017","02/03/2017",..: 36 38 40 43
46 48 2 4 7 10 ...
 $ Latitude : Factor w/ 65 levels "06'19'365","06'21'050",..: 39 12 10 13 2
6 4 3 5 21 ...
 $ Longitude: Factor w/ 65 levels "79'44'179","79'46'107",..: 16 52 58 65 64
60 56 57 55 36 ...

Any help is appreciated.


text:
Q: How to add $id = $_GET['student_id']; and show all same id Im so very paranoid for my code because this is our thesis.
I want to show all row with the same id using $_GET['student_id'] but datatables error this is my code.
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$id = $_GET['student_id'];
$query = 'SELECT * FROM personal WHERE student_id LIKE "%'.$_GET["student_id"].'%" ';
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
    $image = '';
    if($row["image"] != '')
    {
        $image = '';
    }
    else
    {
        $image = '';
    }
    $sub_array = array();
    $sub_array[] = $row["student_id"];
    $sub_array[] = $row["firstname"]." ".$row['middlename']." ".$row['lastname'];
    $sub_array[] = 'Personal Info'." ".
    '<button type="button" id="'.$row["student_id"].'" class="btn btn-info btn-xs update">Grades</button>'." ".
    '<button type="button" id="'.$row["student_id"].'" class="btn btn-info btn-xs update">Payment</button>';
    $sub_array[] = 'View';
    $sub_array[] = '<button type="button" name="delete" id="'.$row["student_id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
    $data[] = $sub_array;
}
$output = array(
    "draw"              =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records(),
    "data"              =>  $data
);
echo json_encode($output);
?>

Thanks in advance.

A: Assuming student_id is numeric:
$id = intval($_GET['student_id']);
$query = 'SELECT * FROM personal WHERE student_id = '.$id;

Would be safe enough.
Also, this looks like an AJAX call. Let's see your Javascript calling and HTML to see if Datatable is being called right from your AJAX call

A: You should escape the $_GET['student_id'] with mysqli_real_escape_string or any other procedure... for security or even better use PDO for make queries.


text:
Q: Laver's Proof that $V$ and $V[G]$ have the $\delta$-approximation property. Let $V$ be a transitive model of ZFC, $\mathbb{P} \in V$ be a forcing poset such that $(|\mathbb{P}| < \delta)^{V}$ for some regular cardinal $\delta$ in $V$, and $G$ be a $V$-generic filter over $\mathbb{P}$. I wish to show that $\langle V, V[G]\rangle$ has the $\delta$-approximation property. That is, for every $X \in V[G]$ such that $X \subset V$, if $Y \cap X \in V$ for every $Y \in V$ with $(|Y| < \delta)^V$, then $X \in V$.
In "Certain very large cardinals are not created in small forcing extensions" (page 3), Laver gives the following argument.
Let $A$ be a set of ordinals in $V[G] \setminus V$. In $V$, we define $B$ as follows.
$$B = \{\alpha : \text{for some } r\in \mathbb{P}, \alpha \text{ is the least ordinal such that for some forcing conditions } p , q > r, p \Vdash \alpha \in A \land q \Vdash \alpha \notin A\}$$
$B$ must be nonempty (otherwise $A$ is definable in $V$) and have size $<\delta$. Then Laver claims that $B\cap A \notin V$. My first question is that I don't understand why $B\cap A \notin V$. It'd appreciated if anyone could explain it in detail.
My second question is: why does it suffice to show that $\delta$-approximation holds for sets of ordinals in $V[G]$? I attempt to show this by using the fact that every set is coded by a set of ordinals. So let $X \in V[G] \setminus V$ with $X\subset V$ be an arbitrary set coded by a set of ordinals $A \in V[G]\setminus V$. Then by the argument above, there must be some small set $B \in V$ such that $B \cap A \notin V$. But how do we know $B \cap A$ codes a small set of $X$?

A: For the first question, note that for any $r\in G$, there is $\alpha\in B$ that "comes from $r$". For any such $\alpha$, $G$ has "generically decided" whether to put $\alpha$ into $A$ or not and this makes sure that $B\cap A\notin V$. For suppose $C\in V$ is a set of ordinals. Then for any $r\in G$ there is $\alpha\in B$ and some $p\leq r$ so that
$$p\Vdash\check\alpha\in A\Leftrightarrow\alpha\notin C$$
This is a density argument that shows that there must be some $r', p'\in G$ and some $\alpha'\in B$ that "comes from $r'$" so that
$$p'\Vdash\alpha'\in A\Leftrightarrow \alpha'\notin C$$
and hence $B\cap A\neq C$.
For the second question, use the following trick: Since $X\subseteq V$, there is some $Y\in V$ with $X\subseteq Y$. Any $V_\alpha$ with $\alpha$ large enough works. Now in $V$ (!) code $Y$ as a set of ordinals, actually any bijection
$$\pi:Y\rightarrow \gamma$$
for an ordinal $\gamma$ is fine. Now replace $X$ by $X'=\pi[X]$.


text:
Q: WOFF font not supported in Android (Moto g4, nougat) In application I have placed some fonts into assets folder. I am applying font on runtime to textview. All fonts types are woff. App is throwing exception of font not found from assets.
Earlier i have tried with otf type font at that time app was running fine.
I am pretty sure something is wrong in Nougat.
Can anyone guide me how to apply WOFF font type in all android OS?
Even i have tested app with WOFF font in 5.0 and 6.0. Its running good.


text:
Q: How to sort the docs when use scroll api in elasticsearch? Recently I'm reading Elasticsearch: The Definitive Guide. When I read a section about scroll, I got some problem. The book says that :

The costly part of deep pagination is the global sorting of results, but if we disable sorting, then we can return all documents quite cheaply. To do this, we sort by _doc. This instructs Elasticsearch just return the next batch of results from every shard that still has results to return.

Then the question came. If I'd like to sort the results, then does it mean that I still will get bad performance? If so, how to solve the deep pagination problem? Is there anyone can help me with that? Thanks a lot.


text:
Q: Sequelize many-to-many self reference I'm trying to get one of the association examples from sequelize working properly and it doesn't seem to be setting up the join table correctly. In the example we have one model called Person and then a many-to-many self-reference for a Person's children. Code:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('postgres://root@localhost/database_bug');

var Person = sequelize.define('Person', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' });

Person.sequelize.sync({force:true}).then(function() {
  Person.build({ name: 'John Doe' }).save().then(function(father) {
    Person.build({ name: 'Jane Doe' }).save().then(function(daughter) {
      father.addChild(daughter);
    });
  });
});

But when I look at my tables in postgres I feel like a column is missing on the auto-generated join table.
            List of relations
 Schema |      Name      |   Type   | Owner
--------+----------------+----------+-------
 public | People         | table    | root
 public | People_id_seq  | sequence | root
 public | PersonChildren | table    | root

                                    Table "public.People"
  Column   |           Type           |                       Modifiers
-----------+--------------------------+-------------------------------------------------------
 id        | integer                  | not null default nextval('"People_id_seq"'::regclass)
 name      | character varying(255)   | not null
 createdAt | timestamp with time zone | not null
 updatedAt | timestamp with time zone | not null
Indexes:
    "People_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE ""PersonChildren"" CONSTRAINT "PersonChildren_PersonId_fkey" FOREIGN KEY ("PersonId") REFERENCES "People"(id)

          Table "public.PersonChildren"
  Column   |           Type           | Modifiers
-----------+--------------------------+-----------
 createdAt | timestamp with time zone | not null
 updatedAt | timestamp with time zone | not null
 PersonId  | integer                  | not null
Indexes:
    "PersonChildren_pkey" PRIMARY KEY, btree ("PersonId")
Foreign-key constraints:
    "PersonChildren_PersonId_fkey" FOREIGN KEY ("PersonId") REFERENCES "People"(id)

PersonChildren needs a column called ChildId or something along those lines to link a Person to its Child.
People table:
database_bug=# SELECT * FROM "People";
 id |   name   |         createdAt          |         updatedAt
----+----------+----------------------------+----------------------------
  1 | John Doe | 2015-02-06 09:36:44.975-08 | 2015-02-06 09:36:44.975-08
  2 | Jane Doe | 2015-02-06 09:36:44.985-08 | 2015-02-06 09:36:44.985-08

Weirder still, I select to make sure daughter was added as a child to father:
database_bug=# SELECT * from "PersonChildren";
         createdAt          |         updatedAt          | PersonId
----------------------------+----------------------------+----------
 2015-02-06 09:36:44.997-08 | 2015-02-06 09:36:44.997-08 |        2

But PersonId is 2, not 1. The father was supposed to add the daughter, not the other way around.
Any ideas how to get this association working?

A: Ok, looks like the example in the documentation is wrong. To be fair they did say must use hasMany but then showed an example using belongsToMany.
I changed belongsToMany to hasMany and it looks like we are good to go:
          Table "public.PersonChildren"
  Column   |           Type           | Modifiers
-----------+--------------------------+-----------
 createdAt | timestamp with time zone | not null
 updatedAt | timestamp with time zone | not null
 PersonId  | integer                  | not null
 ChildId   | integer                  | not null

database_bug=# select * from "PersonChildren";
         createdAt          |         updatedAt          | PersonId | ChildId
----------------------------+----------------------------+----------+---------
 2015-02-06 10:04:21.624-08 | 2015-02-06 10:04:21.624-08 |        1 |       2

Now I can do father.getChildren() and the promise will return a list of children.


text:
Q: Getting error "module has no attribute lite" when trying to convert TF model to TFLite file I am using the code below to convert my Tensorflow model to TFLite. When I run the code I get the
following error (export_tflite.py is the code below):

File "tools/export_tflite.py", line 45, in <module>
    converter = tf.contrib.lite.TFLiteConverter.from_session(sess, [model.input], [model.predictions])

File "C:\Users\sachu\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\util\lazy_loader.py", line 54, in __getattr__
    return getattr(module, item)

AttributeError: module 'tensorflow.contrib' has no attribute 'lite'

import os
import sys
import argparse

import tensorflow as tf

sys.path.append((os.path.normpath(
                 os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              '..'))))

from model import OpenNsfwModel, InputType

"""Exports a tflite version of tensorflow-open_nsfw

Note: The standard TFLite runtime does not support all required ops when using the base64_jpeg input type.
You will have to implement the missing ones by yourself.
"""
if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument("target", help="output filename, e.g. 'open_nsfw.tflite'")

    parser.add_argument("-i", "--input_type", required=True,
                        default=InputType.TENSOR.name.lower(),
                        help="Input type. Warning: base64_jpeg does not work with the standard TFLite runtime since a lot of operations are not supported",
                        choices=[InputType.TENSOR.name.lower(),
                                 InputType.BASE64_JPEG.name.lower()])

    parser.add_argument("-m", "--model_weights", required=True,
                        help="Path to trained model weights file")

    args = parser.parse_args()

    model = OpenNsfwModel()

    export_path = args.target
    input_type = InputType[args.input_type.upper()]

    with tf.Session() as sess:
        model.build(weights_path=args.model_weights,
                    input_type=input_type)

        sess.run(tf.global_variables_initializer())

        converter = tf.contrib.lite.TFLiteConverter.from_session(sess, [model.input], [model.predictions])
        tflite_model = converter.convert()

        with open(export_path, "wb") as f:
            f.write(tflite_model)


text:
Q: How do site analytics tools know the URL that visitors were referred from? I'm building a rudimentary tracking tool for one of my sites, and I'm realizing that Google Analytics and my Squarespace site are aware of the URL that referred my visitors to my site.
For example, Squarespace's analytics can detect the exact URL of the pinterest pin that 3 of my visitors came from, which blog post referred 15 visitors to me, etc. How can my server possibly know who referred them to my site?
I'm a full stack .Net/C#/Javascript engineer and have no ideas. Thanks!

A: There is an HTTP referrer header that is usually populated by default by your browser upon clicking links. It's possible to disable this as the browser is what chooses to include the header. You can make requests in a variety of other ways and leave that header blank, but clicking a simple link in a standard browser is pretty much always going to include the header.

(click for larger view)

A: basically, when you click a link on a site, that site will send location(the URL) information to the destination page, which your server logs.


text:
Q: Lambda Func delegate using interface I have a class implementing an interface, and I need to return a Queryable<> list of that interface, given a certain Where predicate :
public interface ISomeInterface
{
     int ID{get;}
     IQueryable<ISomeInterface> GetWhere(Func<ISomeInterface,bool> predicate);

}
public class SomeClass : ISomeInterface
{
   public static IQueryable<SomeClass> AVeryBigList;
   public int ID {get;set;}
   public IQueryable<ISomeInterface> GetWhere(Func<ISomeInterface,bool> predicate)
    {
      return (from m in AVeryBigList select m).Where(predicate);
    }

}

problem is , this won't even compile, as the predicate won't match.
I've attempted so far:
      return (from m in AVeryBigList select m as ISomeInterface)
             .Where(predicate);

This will compile, but will fail at runtime, saying that it can't instantiate an interface
Second attempt:
  return (from m in AVeryBigList select m)
         .Cast<ISomeInterface>
         .Where(predicate);

This will fail with a more enigmatic error: Unable to cast object of type 'System.Linq.Expressions.MethodCallExpression' to type 'SubSonic.Linq.Structure.ProjectionExpression'.
Edit:
The answer from wcoenen works as it should. Problem now appears when my AVeryBigList is provided by SubSonic 3.0. I get an exception thrown from within SubSonic when executing a query with Cast<>:
Unable to cast object of type 'System.Linq.Expressions.MethodCallExpression' to type 'SubSonic.Linq.Structure.ProjectionExpression'.

SubSonic.Linq.Structure.DbQueryProvider.Translate(Expression expression) at SubSonic.Core\Linq\Structure\DbQueryProvider.cs:line 203

Should I understand that SubSonic's Linq does not support Cast<> or is this a bug in SubSonic?

A: The Where extension methods for IEnumerable indeed take a System.Func, which is how you are trying to pass the predicate here.
But you're working with IQueryable, not IEnumerable. The Where extension methods for IQueryable take a System.Linq.Expressions.Expression, not a System.Func. Change the type of the predicate argument like this:
IQueryable<ISomeInterface> GetWhere(Expression<Func<SomeClass, bool>> predicate)
{
   return AVeryBigList.Where(predicate).Cast<ISomeInterface>();
}

Alternatively, you could keep the original function declaration and pass the predicate to the Where method as x => predicate(x), but that would sabotage the ability of the IQueryable implementation to analyze the expression and optimize the query. (That's exactly what Subsonic does by the way; it analyzes the expression tree to generate a SQL statement.)
Also, you'll be glad to hear that the .Cast<ISomeInterface>() is no longer necessary in .NET 4.0 because of the new support for covariance.


text:
Q: TypeORM doesn't return entire entity after calling .save() method I have a simple entity:
import { BaseEntity, Entity, Column, PrimaryGeneratedColumn, Timestamp } from 'typeorm';

@Entity('organizations')
export class OrganizationEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column('varchar', { length: 10 })
    uid: string;

    @Column('varchar', { length: 100 })
    name: string;

    @Column('varchar', { length: 100 })
    status: string;

    @Column('timestamp')
    createdAt: Timestamp;

    @Column('timestamp')
    updatedAt: Timestamp;

    @Column('timestamp')
    deletedAt: Timestamp;
}

Creating a new entity:
const organization = new OrganizationEntity();
organization.name = 'someName';
organization.status = 'someStatus';
await organization.save();

In Postgres SQL looks like this:
INSERT INTO "organizations"("uid", "name", "status", "createdAt", "updatedAt", "deletedAt") VALUES (DEFAULT, $1, $2, DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "status"

As can be seen it returns only filled fields in RETURNING statement.
I know there are some workarounds by using query builder but I am concern is there any semantical way how I can return an entire entity after calling method save so there will be RETURNING *
Thanks in advance.

A: You can use something like this until TypeORM fixes it:
const user = await this.userRepository.findOne(id);
// handle user not found
const updatedUser = await this.userRepository.save({ id, ...updateDto });
return Object.assign(user, updatedUser);

A: Thanks @noam-steiner. It looks like this issue is in development and probably will be fixed soon. There is even open PR: https://github.com/typeorm/typeorm/pull/5680.


text:
Q: how can i return a char value from function? in c unix To write programs in C which reads lines from a file
text, whose name will give the user at runtime.
The program should select a random line of the file and to print the screen, giving the user a time X to type the words seen on the screen.
The time of X depends on the length of each phrase and you can consider that each character will give the user 1 second.
If the message is printed correctly and on time, the user receives congratulations. If the error message printed (and on time), then the user is informed precisely about the mistakes he has done.
Finally, if time runs out before printing the message, then asks the user if he wants to continue and provided the user answers yes to the above sequence is repeated for a new random line of the file, otherwise the program terminates.
Can someone tell me what I have done wrong; I would have been easier if you write the code you need ...
thanks nik
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

void catch_alarm (int sig)
{
    char ans[2];

    printf ("Operation timed out. Exiting...\n");
    printf ("thes mia akoma eukairia?[y/n]\n");
    scanf ("%s", ans);

    exit (0);
}
void exodos (int sig)
{
    printf ("termatismos ergasias... \n");
    signal (SIGQUIT, SIG_DFL);

    exit (0);
}

int main (int argc, char **argv)
{
    int i, j, x, count, gram[80];
    i = j = count = 0;

    char arxeio[25], grammi[80], buf[80][80], protash[80],  ch, ans[2];
    FILE *fp;

    printf("dwse to onoma tou arxeiou pou thes na anoixeis: \n");
    scanf("%s", arxeio);

    do
    {
        fp = fopen( arxeio, "r");
        while ( (ch = getc(fp)) != EOF )
        {
            buf[i][j] = ch;
            if ( buf[i][j] == '\n' )
            {
                ++i;
                gram[i] = j;
                j = 0;
            }
                ++j;
        }

        fclose(fp);

        // edw vazoume tin rand kai to apotelesma tis sto 4 parakatw
        x = rand() % i;
        j = 0;

        while (j<=gram[x+1])
        {
            printf("%c", buf[x][j]);
            j++;
        }

        /* elenxos entos xronou an oxi TIME OUT... */
        signal(SIGALRM, catch_alarm);
        fflush(stdout);
        alarm(gram[x+1]);
        scanf("%s",protash);

        if (ans[0] == 'n')
            signal(SIGQUIT, exodos);

        /* elenxos or8hs eisagwghs dedomenwn*/
        j = 0;
        while ( j<=(gram[x+1]-2) )
        {
            if ( buf[x][j+1] != protash[j] )
                printf("anti gia %c egrapses %c\n", buf[x][j+1], protash[j]);
            else
                printf("swsto\n");

            ++j;
        }

        /* deuterh eukairia... */

    }
    while ( ans[0] == 'y' );

    return 0;
}

A: The example you pasted here is slightly hard to follow, but it looks like you're trying to make a signal handler return a char. This isn't possible because the signal handler is required to be void  (although it is in general possible for a function to return a char).
The simplest work around for this would be a global (static?) variable instead.
Also note that printf and scanf are not async-safe. The work around for that would be to set a "flag" somewhere and then notice that this has been set later on.
Edit I think this is a simplified example of what you're trying to achieve here:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>

static int timeout = 0;

static void catch_alarm(int sig) {
   if (SIGALRM != sig || 0 != timeout)
      abort();

   timeout = 1;
}

int main() {
   char buf[80];

   signal(SIGALRM, catch_alarm); //TODO: check return!

   printf("Type some stuf:\n");
   fflush(NULL);
   alarm(5);
   int read = -1;
   while (read  < 0 && !timeout) {
      read = scanf("%80s", buf);
   }

   if (timeout) {
     printf("Time out, do something else\n");
   }

   exit(0);
}


text:
Q: How to reverse engineer the data sent from a 433MHz temperature sensor? First off, I apologize if my question is too specialized or does not belong here. If you believe there is a better place to ask this question, please suggest.
My main goal is to transmit the measured temperature from my microcontroller to a wireless thermometer that I bought some time ago. The temperature sensor for the thermometer is wireless and uses a certain protocol to transmit the data to the thermometer. In order to do this, I need to understand the protocol that is being used. Once I understand this, I can program the microcontroller to send my own packets. This is mostly just an exercise to practice reverse engineering and embedded programming. Here is a link to the thermometer/sensor combo.
Using my SDR, I was able to monitor the wireless sensor, record a few samples of different temperatures and view them in Audacity. I was able figure out a few things about the protocol by comparing the recorded samples.

*

*The data is transmitted from the sensor every 40-50 seconds, in 33 bit packets. The packet is repeated 4 times per transmission. The data is OOK PWM modulated, with a 0 being a short pulse and a 1 being a long pulse.

*Each transmission is prefixed with a 'start sequence' and each packet is separated by a 'delimiter sequence'.

*The packet takes the form of xxxx xxxx xxxx x tttt tttt tttt cccc cccc, where t is the temperature bits, c is probably type of checksum and x is probably some type of id/address, battery indicator or header.

*The x bits do not change unless I power down the sensor, so I'm not particularly worried about them as I assume that I'll be able to leave them the same in my own transmissions. the 12 t bits hold the temperature in binary, with the temperature in Celsius calculated as follows:
temp_Celsius = temp/20 - 50

Example from above packet: b011000001110 = 1551
1551/20 - 50 = 27.5 C -> 81.5 F

This works for all of my recorded samples. My main problem is trying to figure out the last 8 c bits. Since the protocol seems relatively simple, I do not think it should be an overly complicated checksum/crc, but I haven't been able to figure it out. I have tried using CRC RevEng but could not find an appropriate model.
So pretty much all I am trying to figure out at this point is how the last 8 c bits are calculated, but I would also be interested to learn what info the first 13 x bits holds. Hopefully one of you sees a pattern that I am missing.
Sample Packets:
    binary:
    ? xxxxxxxxxxxx tttttttttttt cccccccc
    -----------------------------------------
    0 111000000010 011000001111 11000000            //27.5C, 81.5F
    0 111000000010 011000100111 11111000            //28.7C, 83.6F
    0 111000000010 011000100001 11110010            //28.4C, 83.1F
    0 111000000010 011000000011 11010100            //28.4C, 83.1F
    0 111000000010 010111101101 10111110            //25.8C, 78.4F
    0 111000000010 010110101011 01111111            //22.5C, 72.5F
    0 111000000010 010011101000 10111010            //12.8C, 55.0F
    0 111000000010 010010000100 01010110            // 7.8C, 46.0F
    0 111000000010 001111101111 10111110            // 0.3C, 32.5F

    hex:
    ? xxx ttt cc
    --------------
    0 E02 60F C0            //27.5C, 81.5F
    0 E02 627 F8            //28.7C, 83.6F
    0 E02 621 F2            //28.4C, 83.1F
    0 E02 603 D4            //28.4C, 83.1F
    0 E02 5ED BE            //25.8C, 78.4F
    0 E02 5AB 7F            //22.5C, 72.5F
    0 E02 4E8 BA            //12.8C, 55.0F
    0 E02 484 56            // 7.8C, 46.0F
    0 E02 3EF BE            // 0.3C, 32.5F

Things I have tried:

*

*Searching for a CRC model using RevEng

*Online CRC calculators

*Searching for my particular sensor or similar ones in RTL433. There are other LaCrosse devices in this program but none seem to have the same protocol as mine.

Any and all criticism/help is appreciated, thanks.


text:
Q: Finding the domain a domain controller belongs to How do I figure out the name of the domain a domain controller belongs to?
For example I have the domain controller \\nFS01.nfs01.local. It says the domain of this is NFS0101 but I don't remember setting a domain name like that, so is there a way to find this information out for another domain such as another controller with the name \\fs01.local?

A: Open PowerShell on a domain controller.
Run:
Import-Module ActiveDirectory
Get-ADDomain | select DNSRoot,NetBIOSName

This will output the FQDN of your domain and the NetBIOS name.
Or, just open the Active Directory Users and Computers snap-in. It's right at the top in the left-hand pane.

A: From a command prompt on the DC run "set" and look at the USERDNSDOMAIN and USERDOMAIN environment variables to get the DNS and NetBIOS names of the domain.


text:
Q: ¿Cómo puedo realizar la siguiente consulta? La duda es la siguiente, tengo dos tablas, una que contiene los datos de un alumno llamada datoaspirante con la siguiente información...
nombre
apPaterno
apMaterno
familiarid

... con el siguiente registro:
nombre  apPaterno  apMaterno  familiarid
-----------------------------------------
john      doe       perez         1

La siguiente tabla me muestra la información de los familiares de un alumno...
Nombre
aPaterno
aMaterno
Parentesco
datoaspirante

... con los  siguientes registros...
    nombre  apPaterno  apMaterno  parentesco  ocupacion  datoaspirante
    ---------------------------------------------------------------------
    maria   perez        ghg      Madre       diseñadora       1
    juan    doe          d        Padre       Programador      1
    marisol lucatero     gf       Madre       Contadora        1

... en el cual mediante la siguiente consulta junto la información de las dos tablas para que se puedan observar la información del alumno y de sus padres.
select da.nombre,da.apPaterno,da.apMaterno,
f.nombre as nombrePadre,f.aPaterno as apellidoPaternoPadre,f.aMaterno as
apellidoMaternoPadre,f.parentesco,
fa.nombre as nombreMadre,fa.aPaterno apellidoPaternoMadre,fa.aMaterno
apellidoMaternoMadre ,fa.parentesco
from datoaspirante as da
left join familiar as f on da.familiarid =  f.datoaspirante and f.parentesco
= 'Padre'
left join familiar as fa on da.familiarid =  fa.datoaspirante and
fa.parentesco = 'Madre';

... dándome el siguiente resultado en donde si el usuario cuenta con dos madres muestra dos veces el registro pero mostrando madres distintas.
nombre apPaterno  apMaterno nombrePadre apPaternoPadre  Ocupacion  nombreMadre  apellidoPaternoMadre  apellidoPaternoMadre  Ocupacion
---------------------------------------------------------------------------------------------------------------------------------------
john     doe        perez       juan         doe        programador   maria            perez                  ghg          Diseñadora
john     doe        perez       juan         doe        programador   marisol          lucatero               gf           Contadora

La pregunta es, ¿Cómo podría traerme la información del alumno y de los 3 padres en una sola columna?
Algo así:
nombre apPaterno  apMaterno nombrePadre apPaternoPadre  Ocupacion  nombreMadre  apellidoPaternoMadre  apellidoMaternoMadre  Ocupacion  nombreMadre2  apellidoPaternoMadre2  apellidoMaternoMadre2  Ocupacion
---------------------------------------------------------------------------------------------------------------------------------------
john     doe        perez       juan         doe        programador   maria            perez                  ghg          Diseñadora   marisol            lucatero       gf                      Contadora

A: Puedes hacer lo siguiente para mostrar los datos en una sola linea utilizando subquery:
CREATE TABLE datoaspirante (
    nombre varchar (60) NULL,
    apPaterno varchar (60) NULL,
    apMaterno varchar(60) NULL,
    FamiliarId int NULL
)

CREATE TABLE Familia (
    nombre varchar (60) NULL,
    apPaterno varchar(60) NULL,
    apMaterno varchar(60) NULL,
    Parentesco varchar(60) NULL,
    Datoaspirante int NULL,
    Ocupacion varchar(60) NULL
)

INSERT   datoaspirante  VALUES (N'jhoe', N'doe', N'perez', 1)

INSERT Familia VALUES (N'maria', N'perez', N'mora', N'madre', 1, N'Contadora')

INSERT Familia VALUES (N'jose', N'garcia', N'feliz', N'padre', 1, N'Programador')

SELECT
CONCAT(nombre," ",apPaterno," ",apMaterno) as Aspirante,
(select CONCAT(nombre,' ',apPaterno,' ',apMaterno)from Familia where Datoaspirante=FamiliarId AND Parentesco='madre' ) as Madre,
(select CONCAT(nombre,' ',apPaterno,' ',apMaterno)from Familia where Datoaspirante=FamiliarId AND Parentesco='padre' ) as Padre,
(select Ocupacion  from Familia where Datoaspirante=FamiliarId AND Parentesco='madre' ) as Ocupacion_Madre,
(select Ocupacion   from Familia where Datoaspirante=FamiliarId AND Parentesco='padre' ) as  Ocupacion_Padre
FROM Datoaspirante

Aquí concatene los apellidos para que se vean mejor al usuario, pero si lo vas a reutilizar lo puedes hacer independiente.
Espero que sea útil.


text:
Q: Make img thumbnail gallary to work in php When I insert some php code to make this dynamic. The problem becomes that when the website refreshes there i cant get to have a image preselected. How can I make that when I refresh the site a img is from UL is preselected.
Html:

Script:


text:
Q: *ngIf for all sub routes I want do figure out how I can show a container with *ngIf for all sub routes.
Like for:

So this container is shown when I am at "page" and also for all subpages of "page".
Thanks for your help

A:     public currentLink: string;

    constructor(private router: Router){

        this.currentLink = this.router.url;

   }
   if(this.currentLink.startsWith('/page/')) this.flag = true;
   else this.flag = false;

> you can get the URL using observable also


text:
Q: How Can I Use A Python Variable In A SQL Query So That Parameters Are Processed? This should be pretty basic; I am not sure what the error I am making is. I am attempting to query a database using a Python variable in the query and I am able to query successfully with this:
locationIDSelectQuery = ('SELECT locationId FROM stateTemplate WHERE id = 1')
cursor.execute(locationIDSelectQuery)
and unsuccessfully with this:
stateTableRowId = 1
cursor.execute("SELECT locationId FROM stateTemplate WHERE id=?", stateTableRowId)
When I try this in the latter it doesn't work either (statetableRowID).
Same error message in both instances:
Traceback (most recent call last):
line 29, in
    cursor.execute("SELECT locationId FROM stateTemplate WHERE id=?", (stateTableRowId))
ValueError: Could not process parameters
How can I use a Python variable in my SQL query?

A: try the following, replace ? with %s
stateTableRowId = 1
cursor.execute("SELECT locationId FROM stateTemplate WHERE id=%s", stateTableRowId)

A: I combined the recommendations of @zealous and @juanpa.arrivillaga to arrive at a working solution:stateTableRowId = 1
cursor.execute("SELECT locationId FROM stateTemplate WHERE id=%s", (stateTableRowId,))
My understanding is that it may be preferable for security reasons to use ? instead of %s. I have yet to get that to work with the database to which I'm connecting.


text:
Q: What is to be made of "e" ending so many Middle English words? I was recently reading about the life of Robert I (the Bruce) of Scotland.  On his deathbed, since he had been unable to go on crusade to the Holy Land as he had once pledged to do, he directed that his embalmed heart be carried on a crusade:

"I will that as soone as I am trespassed out of this worlde that ye take my harte owte of my body, and embawme it, and take of my treasoure as ye shall thynke sufficient for that enterprise, both for your selfe and suche company as ye wyll take with you, and present my hart to the holy Sepulchre where as our Lorde laye, seyng my body can nat come there."

Note that "out" and "hart" here are actually spelled both with and without a terminal "e".
What is going on here?  Was this just an unaccountable urge to plaster terminal and unpronounced extra "e"s everywhere, or were they actually expected to be pronounced?  Or was there some kind of spelling convention that called for "e"s?
I do see that some of this pointless terminal "e" thing is done to this day (such as in "treasoure" above).  Obviously that is just tradition. And of course a terminal silent "e" is used to indicate that a previous vowel is to be pronounced "long" instead of "short".   But what about the ME usage?

A: The simplest explanation is that it's a simple case of phonetic changes buggering up what used to be sensible orthography.
In Old English and earlier Middle English, some words ended in a consonant, while others had an extra, final, unstressed vowel: in Old English, just about any vowel could serve (though -y was rare), while later on, most of these unstressed vowels merged and were pronounced the same, probably as some kind of schwa [ə], most commonly associated with a weak form of the letter ⟨e⟩ in particular (perhaps because that's how the final schwa was written in Old French around the same time).
When that happened, it's only natural that the scribes of the time started faltering and getting unsure of which words had an ⟨e⟩ all along (and therefore didn't change), and which ones used to be written with ⟨a⟩, ⟨i⟩, ⟨o⟩, or ⟨u⟩. The system was gone, and suddenly you had an enormous chunk of words and case forms that all ended in [ə], but were written in half a dozen different ways.
Eventually, this synchronically random system was of course abandoned, and they started just writing ⟨e⟩ everywhere.
But what happens, then, when a few centuries later, that final [ə] has been whittled away at for so long that it, too, has completely disappeared? Back when the schwa was pronounced, it was obvious why you wrote an yong man [ən joŋ maːn] but the yonge man [ðe(ː) joŋə maːn]: they were different words, pronounced differently, so of course they were also spelt differently. But once they're both pronounced the same, [joŋ], but still spelt differently, you've got a nice, fertile ground in which to start sowing confusion.
This was around the same time that popular (by which I mean non-ecclesiastical, vernacular) literature and writing started spreading far beyond what it had previously been, so you had a whole new group of people writing the language that had never been thoroughly trained for years as scribes—they just wrote what they spoke.
After a while of this, you'd quite naturally end up with a kind of written diglossia: the untrained who wrote how they spoke would be more likely to just leave off all those pesky little -e's (that weren't pronounced anyway) and just write what they pronounced; while the more thoroughly trained scribes who had historical documents at hand and had been taught Old English (not to mention Latin and probably Old French) grammar would be much more likely to maintain a more conservative, archaising style, effectively creating a 'high-brow' literary style that would seem, among other things, to be characterised by an abundance of words ending in some mysterious -e that meant absolutely nothing and wasn't pronounced.
Just like nowadays, when people tend to use fancy words to sound clever (even if they don't understand them and end up misspelling and/or misusing them), it would of course be desirable for an untrained writer to appear more high-brow and literary than he perhaps really was—but since an untrained writer had no real way of knowing exactly where to stuff in all these pesky extra -e's, it's almost unavoidable that he would start adding them, well, more or less at random. When he felt like it.
Once the untrained writers started significantly outnumbering the trained ones, the not-so-systematical system of optionally adding silent -e's at the end of many words became the standard practice. At some point, even the trained scholars gave up and just went with it—that's around the time when writers like Ye Olde Robert and later on Shakespeare start to enter the stage.
(Actually, Robert himself was probably on the stage while the schwas started to be deleted, which seems to have been a process underway by Chaucer's time, about 30 or so years after Robert's reign. But whoever wrote down the text you were reading might well have done so later in the century, so it's roughly around the same time.)


text:
Q: JS prevent scrollTo from called from external js Is there a way to prevent window.scrollTo, we have a problem with an external library injecting an UI component and then it will scroll to the top of the page, which is terrible for user experience, because you will scroll into this component and page will jump to top of window.
appreciate any great suggestions.

A: Answering your question

Is there a way to prevent window.scrollTo

Yes, you can store it in a variable, and override it:
window._scrollTo = window.scrollTo;
window.scrollTo = function() { };

Then, if you need to use scrollTo yourself, you can simply use the moved function:
window._scrollTo(...);

However, it does not sound correct.
You need to find the reason of this problem, and fix it.


text:
Q: I'm getting error during sniff packet using scapy My code is here:
#!/usr/bin/env python3
import os
print(os.sys.path)
from scapy.all import*
def sniff(interface):
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)

def process_sniffed_packet(packet):
    print(packet)

sniff("eth0")

And got the error code like this:
python3 row.py
['/home/kali/Desktop', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.7/dist-packages']
Traceback (most recent call last):
  File "row.py", line 11, in <module>
    sniff("eth0")
  File "row.py", line 6, in sniff
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
AttributeError: module 'scapy' has no attribute 'sniff'

Could anyone help?

A: You just imported all available functions from scapy with from scapy.all import *
which means you have to use sniff instead of scapy.sniff
If you want to use scapy.sniff you have to change your import to import scapy.all as scapy
Note: There is a sniff function in scapy.all but you are defining a new sniff function (line 5). Rename it so that you don't get name conflicts.
#!/usr/bin/env python3
import os
print(os.sys.path)
from scapy.all import *
def mysniff(interface):
    sniff(iface=interface, store=False, prn=process_sniffed_packet)

def process_sniffed_packet(packet):
    print(packet)

mysniff("eth0")


text:
Q: PyQt5 and QAbstractListModel::columnCount QTreeView ignores columnCount() of class inherited from QAbstractListModel and shows only first column:
import sys
from PyQt5.QtCore import QAbstractListModel
from PyQt5.QtWidgets import QApplication, QTreeView

class Model(QAbstractListModel):
    def columnCount(self, parent):
        return 3

    def data(self, index, role):
        return None

    def rowCount(self, parent):
        return 0

app = QApplication(sys.argv)

model = Model()
list_view = QTreeView()
list_view.setModel(model)
list_view.show()

app.exec_()

Relevant C++ code works fine.
What am I doing wrong?

A: From the Qt docs:

The QAbstractListModel
  class provides an abstract model that can be subclassed to create
  one-dimensional list models. [emphasis added]

But you clearly want a two-dimensional model, so use QAbstractItemModel instead.


text:
Q: why mysql still use index to get data when use the 2nd col of multiple column index in mysql? Why mysql still use index to get data when use the 2nd col of multiple column index  in mysql?
We know mysql use leftmost match rule, but here I didn't use the 1st col and I use the 2nd col, the two select operation results bellow show that mysql sometimes use index and sometimes didn't use it. Why? In addtion, my mysql version is 5.6.17.
1.create table:
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `cid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_cid_INX` (`name`,`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8

2.run select:
EXPLAIN SELECT * FROM student WHERE   cid=1;

3. result:
Result with index
It shows that mysql use index to get data.
The following is another table.
1.create table:
CREATE TABLE `test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `note` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `NAME` (`name`),
  KEY `AGE` (`age`),
  KEY `LeftMostPreFix` (`name`,`address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2.run select:
explain SELECT * FROM test.test_table where  address = '东京'

3.result:
Result without index
On the contrary here it shows that mysql didn't use index to get data.
Comparing above two results, I feel puzzled why the 1st result use index which is against leftmost match rule.

A: From the mysql manual

it is possible that key will name an index that is not present in the possible_keys value. This can happen if none of the possible_keys indexes are suitable for looking up rows, but all the columns selected by the query are columns of some other index. That is, the named index covers the selected columns, so although it is not used to determine which rows to retrieve, an index scan is more efficient than a data row scan.

So while there is a key used here, it's not actually used in the normal sense. In some situations it is still more efficient to use that as a table scan (in your first example), in others it might not be (in your second)
Most of the times these things are decided by the optimizer based on several things (usage of the table, etc).
Best thing to remember is that here you can NOT "use the index", and that's why there is no index in possible keys. You can only use the index if the first column is in there.

A: Neither index in either Case starts with what is in the WHERE, so there will be a full scan of table or of index.
Case 1:  The index is "covering", so it is a tossup as to which (table scan vs index scan) is better.  The Optimizer happened to pick the secondary index.  EXPLAIN FORMAT=JSON SELECT ... may have enough details to explain 'why' in this case.
Case 2:  Because of * (in SELECT *), the secondary index is at a disadvantage -- it is not "covering", so the processing will bounce back and forth between the index and the data.  So it is clearly better to simply scan the table.
Instead of trying to understand EXPLAIN (in these cases), turn the question around: "What is the optimal index for this query against this table?" Then follow the guidelines here.


text:
Q: How to make Vigenere cipher with upper/lower case letters and numbers I need to do vigenere cipher which can encrypt words with lower/upper case letters and numbers. I'm new to c# so I don't really know how to do it. Tried to edit this code, but could'nt do much.
class VCipher
        {
            public string encrypt(string txt, string pw, int d)
            {
                int pwi = 0, tmp;
                string ns = "";
                txt = txt.ToUpper();
                pw = pw.ToUpper();
                foreach (char t in txt)
                {
                    if (t < 65) continue;
                    tmp = t - 65 + d * (pw[pwi] - 65);
                    if (tmp < 0) tmp += 26;
                    ns += Convert.ToChar(65 + (tmp % 26));
                    if (++pwi == pw.Length) pwi = 0;
                }

                return ns;
            }
        };


text:
Q: Add or set Multiple value to Dropdown using Jquery with selected <label class=" ORGAD1-labeltext2">Color</label>
<select class="select-color-multiple  [enter image description here][1] ORGAD16-color"  multiple="multiple" name="variantcolor_color[]" id="variantcolor-color">
            <option value="" >choose color</option>
            <option value="black"  >Black</option>
            <option value="white" >White</option>
            <option  value="green" >Green</option>
            </select>

in this Drop down want to set multiple value using Jquery like below image .eg:
the values comes from database like color= red,black. and how set value to drop down?

A: $(document).ready(function() {
    var selectedColors = ['black', 'green']; // These values are comming from db. You can use ajax call for this.

    $.map($('#variantcolor-color option'), function(option) {
        if ($(option).val() != '' && $.inArray($(option).val(), selectedColors)) {
            $(option).attr('selected', true);
        }
    });
});


text:
Q: Probably segmentation fault n>150 000 wtih vector int main()
{
    ios_base::sync_with_stdio(0);

    cin>>n;
    vector<vector<bool> > tab (n+1, vector<bool>(n+1));
    vector<unsigned short int >wifi (n+1);
    int  z=0;
    x=1;
    do{
        cin>>a>>b;
        tab[a][b]=1;
        tab[b][a]=1;
        x++;
    }while(x!=n);
}

Hi, I still have a problem, the program has stopped working results greater than 150 000 even though they changed it to vector. I present the code in a nutshell.

A: My hunch is you're running out of memory or not checking the input values enough!
Change [i]
 to .at(i) and make sure the indices are valid:
Live On Coliru
#include <iostream>
#include <vector>

int main() {
    std::ios_base::sync_with_stdio(0);

    size_t n;
    if (std::cin >> n)
    {
        std::cout << "n = " << n << "\n";

        std::vector<std::vector<bool> > tab(n + 1, std::vector<bool>(n + 1));
        std::vector<unsigned short int> wifi(n + 1);

        std::cout << "allocated, reading\n";

        size_t a, b;
        for (size_t m = n; m && std::cin >> a >> b; --m)
        {
            tab.at(a%n).at(b%n) = 1;
            tab.at(b%n).at(a%n) = 1;
            if (m%1000==1) std::cout << "." << std::flush;
        }
    }
}

My PC has no trouble even for 250,000 rows.
Now, consider using dynamic_bitset or boost::icl::interval_set instead. Consider using parallell BGL for distributed AdjacencyMatrix graphs.
Consider AdjacencyLists or EdgeList if the matrix is sparse.


text:
Q: When do I use Boxing and Unboxing? I know boxing convert value type to object and unboxing convert object to a value type.
Example:
int num = 1;
Object obj = num;      //boxing
int num2 = (int)obj    //unboxing

But when I use it in the real life (when I write some code)?
I never assign Int into Object (or that's what I think so, I didn't write it explicitly)

A: Boxing/unboxing is useful for situations where you may have, for instance, a collection of disparate things, some of which are primitives and others of which are object types, such as a List<object>. Indeed, that's the example they give in the Boxing and Unboxing documentation page that comes up if you search for "msdn boxing:"
// List example.
// Create a list of objects to hold a heterogeneous collection
// of elements.
List<object> mixedList = new List<object>();

// Add a string element to the list.
mixedList.Add("First Group:");

// Add some integers to the list.
for (int j = 1; j < 5; j++)
{
    // Rest the mouse pointer over j to verify that you are adding
    // an int to a list of objects. Each element j is boxed when
    // you add j to mixedList.
    mixedList.Add(j);
}

// Add another string and more integers.
mixedList.Add("Second Group:");
for (int j = 5; j < 10; j++)
{
    mixedList.Add(j);
}

// Display the elements in the list. Declare the loop variable by
// using var, so that the compiler assigns its type.
foreach (var item in mixedList)
{
    // Rest the mouse pointer over item to verify that the elements
    // of mixedList are objects.
    Console.WriteLine(item);
}

// The following loop sums the squares of the first group of boxed
// integers in mixedList. The list elements are objects, and cannot
// be multiplied or added to the sum until they are unboxed. The
// unboxing must be done explicitly.
var sum = 0;
for (var j = 1; j < 5; j++)
{
    // The following statement causes a compiler error: Operator
    // '*' cannot be applied to operands of type 'object' and
    // 'object'.
    //sum += mixedList[j] * mixedList[j]);

    // After the list elements are unboxed, the computation does
    // not cause a compiler error.
    sum += (int)mixedList[j] * (int)mixedList[j];
}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.
Console.WriteLine("Sum: " + sum);

// Output:
// Answer42True
// First Group:
// 1
// 2
// 3
// 4
// Second Group:
// 5
// 6
// 7
// 8
// 9
// Sum: 30


text:
Q: Definition of Hölder Spaces of maps between manifolds (also Sobolev Spaces of these maps) Let $M$ be a Riemannian manifold, $N$ a manifold, $k\in \mathbb{N}$, $\alpha\in(0,1)$

Question: How exactly is the Hölder space $C^{k,\alpha}(M,N)$ and the sobolev space $W^k_p(M,N)$ defined? Are there (good) references where these spaces are introduced and sobolev embedding theorems of these spaces can be found?

(I know how $C^{k,\alpha}(M,\mathbb{R})$, $W^k_p(M,\mathbb{R})$ and $C^{k,\alpha}(E)$, $W^k_P(E)$ for sections of a vector bundle $E\rightarrow M$ are defined if that helps.)
Also I would appreciate any good references on the topic of sobolev and hölder spaces of maps between manifolds and sections of vector bundles.
Thanks in advance!

A: The Hölder maps are very straightforward to define in the usual way if you have a metric on both the domain and range. If $N$ is just a differentiable manifold, I guess the local version of Hölder continuity is invariant under local diffeomorphisms. So that would still be meaningful, although not the global version.
Concerning the Sobolev spaces, these are distributions in general, if my memory serves me correctly. So this is part of the general question of how to define manifold-valued distributions, which is not so easy. I think it might be impossible because for distributions, you need integration by parts of integrals of test functions. Those integrals are not well defined in general because the range space is not a vector space. So you can't compute the average of a distribution of points on the range manifold. Something similar to this question was discussed in item 935310.


text:
Q: Shell script to move files between two dirs I have multiple folders which contain subfolders like JAN/ Jan/ FEB/ Feb/ MAR/ Mar/ and so on. I need to move all files from JAN/* to Jan/ , FEB/* to Feb/ and so on. How do I achieve this with a shell script?
Edit
Thanks to @Costas for pointing me in the right direction. His solution will work with Bash 4 and up. Since I had v3 I ended up using this.
for DIR in [A-Z][A-Z]*/
do
    NEWDIR=`echo "$(echo "$DIR" | sed 's/.*/\L&/; s/[a-z]*/\u&/g')"`
    mv $DIR/* $NEWDIR
done

sed script taken from here.

A: For modern bash (which supports case change):
for dir in [A-Z][a-z]*/
do
    mv -t "$dir" ${dir^^}/*
done

In unsupported versions you free to use tr|sed|… conversion instead.

A: Using the Perl-based rename utility that comes as standard on Debian, but is known as prename on some other systems, you can do it with one command
( LC_ALL=C; prename -v 's!^([A-Z])([A-Z]{2}/)!$1\L$2!' [A-Z][A-Z][A-Z]/* )

This forces the C locale, which ensures that filename matching is case sensitive, allowing the file pattern [A-Z][A-Z][A-Z] to pick up only months with entirely capital letters. The substitution swaps three capital letters for a capital letter followed by two lowercase letters.
If you prefer you can swap the filename pattern [A-Z][A-Z][A-Z]/* for an explicit list of all twelve months: {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC}/*


text:
Q: Graph API for accessing teams and team's groups to pull documents I am working on asset management system in which my application needs to pull specific documents of all the employees being stored by them on teams or any teams group.
Using graph API or any other medium, how can I achieve the same. Any suggestions or pointers will be helpful to start with.

A: Teams has a associated Group.
So you need to get the list of all the Teams first through (reference):
GET https://graph.microsoft.com/beta/groups?$filter=resourceProvisioningOptions/Any(x:x eq 'Team')

Then you can traverse this list to get the Group (Teams) id.
Get the channels in an Teams like this (reference):
GET https://graph.microsoft.com/v1.0/teams/{Group id}/channels

Record the channels' name.
Now use this call to get the files stored in a Teams channel (reference):
GET https://graph.microsoft.com/v1.0/groups/{Group id}/drive/root:/{channel name}:/children

You need to implement multiple loops to get all the files stored in Teams.
UPDATE:
Using the following request to list the items in the Teams:
GET https://graph.microsoft.com/v1.0/groups/{Group id}/drive/root/children

You can get the item id of General folder from the response.
Then you can get the files under General folder through:
GET https://graph.microsoft.com/v1.0/groups/{Group id}/drive/items/{item id}/children


text:
Q: Conditionally call a keyed parameter in a macro Is it possible to have keywords used\called conditionally? Essentially instead of:
(defun test (var)
  (if var
    (some-function :para var)
    (some-function)))

I'd want something like this:
(defmacro test (var)
  `(some-function (if ,var [add-keyword])))

where the function is(for quick easy example purposes):
(defun some-function (&key para)
  (cond ((equal para 'yes) "yes")
        ((null para) "no")
        (t "other")))

A: It's usually possible to write code in a way to not need to do this (just pass nil or the default). But if it really is unavoidable you can use apply:
(apply #'some-function args... (when var (list :para var)))

If you want to pass keyword arguments on, you should use a &rest argument with apply and &allow-other-keys. If you want to pass them on to the next method in CLOS, you should use call-next-method. In general it is best to have the set of keyword arguments known at compile time because then the compiler can make things much faster than the unknown case.

A: One can also detect if a function was called with a keyword parameter:
CL-USER 44 > (flet ((example (&key (para nil para-supplied-p))
                      (list para para-supplied-p)))
               (list (example)
                     (example :para nil)
                     (example :para t)))
; para  para-supplied-p
((NIL   NIL)
 (NIL     T)
 (  T     T))


text:
Q: Insert duplicate records in a weak entity Entity Framework So I'm doing some entity framework practices and as a project I wanted to create a database that stores a list of clients, some products and when and how many of a product where bought.
I created an entity "Receipt".
[Key]
public int ID { get; set; }

[Required]
public DateTime RecieptDate { get; set; }

[ForeignKey("FKClient")]
public Client Client { get; set; }

public List<Product> Products { get; set; }

And EF creates an implicit table in the Database to store the relationship between Receipt and Products, but the thing is that I want to store multiple records of the same product in the same receipt. I wonder is there a way to store duplicate records on the implicit ReceiptProducts table?
If not, is there a better way to approach this problem?
(Edit) -Added the product entity
class Product
    {
        [Key]
        public int ID { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        [Range(1,double.MaxValue)]
        public decimal price { get; set; }
        public List<Receipt> Receipts { get; set; }
    }


text:
Q: Python download file in link I want to open a link using python on  same tab. I use web browser module but all open in default browser ,but I want to open in same browser and same current tab.
webbrowser.open(URL)
webbrowser.open_new_tab(URL)

A: Once you open webPage you have no controll over the page. As webbrowser open command will retrun True or False depending on either webpage successfully open or not.


text:
Q: create properties with loop I would like to create object properties using a loop, and the setattr function.
The problem i run into  is that all the properties created with such a loop are equal to one another.
In the following example i create a class A with a single attribute z, a complex number. i then would like to loop over functions such as numpy's real and imag to create other properties, such as z_real and z_imag. The problem then, in the context of this example, is that z_real == z_imag is True.
import numpy as np

class A(object):
    def __init__(self, z):
        self.z = z

        for func in [np.real, np.imag]:
            fget = lambda x: func(x.z)
            print('self.z_%s = %i' % (func.__name__, fget(self)))
            setattr(self.__class__, 'z_%s' % (func.__name__),
                    property(fget))

a = A(1+2j)

print ('a.z_real=%i'% a.z_real)
print ('a.z_imag=%i'% a.z_imag)

running this yields
self.z_real = 1
self.z_imag = 2
a.z_real=2
a.z_imag=2

It is not clear to me why this is.

A: You're doing it wrong.

Don't create more then one instance of the same closure per normal function!

fget = lambda x, f=func: f(x.z)

A: Your fget is a closure. It closed over the variable func. After the loop is finished, func remains set to np.imag.
You should do the following afer self.z = z:
def make_getter(func):
    return lambda x: func(x.z)

for func in [np.real, np.imag]:
    fget = make_getter(func)

etc.


text:
Q: join в несколько уровней Пишу фильтр для сайта, необходимо использовать join в несколько уровней, в один уровень умею, а вот второй уровень не могу написать, ошибками закидывает.
В property_product находится связка товара и характеристики.
В property находятся сами характеристики.
Задача: получить product учитывая характеристики. Сначала берем из property_product товары с характеристиками, потом отсортировываем лишние, чтобы в property были совпадения. Желательно сделать в таком же виде, чтобы был один основной join, а всё остальное внутри него. То есть получаетс join в 2 уровня.
Вот, что я наворотил :D
$product = DB::table("product")
                ->join('property_product', function($join) use ($filter) {
                    if (!empty($filter) && !empty($filter['property'])) {
                        $join->on('property_product.id_product', '=', 'product.id');

                        foreach ($filter['property'] as $keyp => $valuep) {
                            $join->join('property', function($joinp) use ($valuep) {
                                $joinp->on('property.id', '=', 'property_product.id_property')
                                ->where('property.val', '=', $valuep['value'])
                                ->where('property.id_category', '=', $valuep['id']);
                            });
                        }
                    }
                });

Ошибка:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id_category' in where clause is ambiguous (SQL: select `product`.* from `product` inner join (`property_product` inner join `property` on `property`.`id` = `property_product`.`id_property` and `property`.`val` = 2 and `property`.`id_category` = 2) on `property_product`.`id_product` = `product`.`id` where (`id_category` = 1 and `id_city` = 1) and `id` = 1 limit 15 offset 0) in file /home/host/loc/shop/api/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671

A: Может быть легче использовать чистый sql?
SELECT column1, column2, column3 FROM table1, table2, table3
WHERE table1.id = table2.id and table2.id = table3.id


text:
Q: FOSUserBundle sending more email on user creation I'm developing a web site using Symfony2 and I'm using FosUserBundle to manage the users.
On user registration I'd like to send a mail to admins to inform of the event.
I followed the official FOS manual but I'm not able to override correctly the mail sending and anyway I don't know how to generate a new email for the admins.
The first problem comes from the config.yml files where I set the following params for the Mailer override
# ...
fos_user:
        registration:
            confirmation:
                enabled: true
            email:
                template: UserBundle:Registration:confirmation.email.twig
            form:
                type: user_registration

The email: and template: rows gave me the following errors:
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized option "email" under "fos_user.registration"

Any advice on how to solve the problem and any other on how to implement the second mail sending?

A: For a similar situation I've used an EventListener to send an e-mail.  The mailer is a service, which is also shown below.
listenter
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityManager;

/**
 * Description of RegistrationListener
 *
 * @author George
 */
class RegistrationListener implements EventSubscriberInterface
{

    private $em;
    private $mailer;
    private $tools;

    public function __construct(EntityManager $em, $mailer, $tools)
    {
        $this->em = $em;
        $this->mailer = $mailer;
        $this->tools = $tools;
    }

    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
        );
    }

    /**
     * Persist organization on staff registration success
     * @param \FOS\UserBundle\Event\FormEvent $event
     */
    public function onRegistrationSuccess(FormEvent $event)
    {
        /** @var $user \FOS\UserBundle\Model\UserInterface */
        $user = $event->getForm()->getData();
        $user->setAddDate(new \DateTime());
        $type = $this->tools->getUserType($user);
        if ('staff' === $type) {
            $organization = $user->getOrganization();
            $organization->setTemp(true);
            $user->setOrganization($organization);
            $this->em->persist($organization);
            $user->addRole('ROLE_STAFF');
            $this->mailer->sendNewOrganization($organization);
        }
        if ('admin' === $type) {
            $user->addRole('ROLE_ADMIN');
        }
        if ('volunteer' === $type) {
            $user->setReceiveEmail(true);
            $user->setEnabled(true);
        }
    }

}

mailer service
use \Symfony\Component\DependencyInjection\ContainerAware;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\MailerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\ORM\EntityManager;

/**
 * Description of AdminMailer
 *
 * @author George
 */
class AdminMailer extends ContainerAware implements MailerInterface
{

    protected $mailer;
    protected $router;
    protected $twig;
    protected $parameters;
    protected $em;

    public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig, array $parameters, EntityManager $em)
    {
        $this->mailer = $mailer;
        $this->router = $router;
        $this->twig = $twig;
        $this->parameters = $parameters;
        $this->em = $em;
    }

    ...other functions

    /**
     * Alert admins to new org being created
     * @param type $organization
     * @return type
     */
    public function sendNewOrganization($organization)
    {
        $message = \Swift_Message::newInstance()
                ->setSubject('New organization')
                ->setFrom($this->parameters['address'])
                ->setTo($this->adminRecipients())
                ->setContentType('text/html')
                ->setBody(
                $this->twig->render(
                        'new_org', array(
                    'organization' => $organization,
                        ), 'text/html'
                )
                )
        ;

        return $this->mailer->send($message);
    }

protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
    $context = $this->twig->mergeGlobals($context);
    $template = $this->twig->loadTemplate($templateName);
    $subject = $template->renderBlock('subject', $context);
    $textBody = $template->renderBlock('body_text', $context);
    $htmlBody = $template->renderBlock('body_html', $context);

    $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom($fromEmail)
            ->setTo($toEmail);

    if (!empty($htmlBody)) {
        $message->setBody($htmlBody, 'text/html')
                ->addPart($textBody, 'text/plain');
    }
    else {
        $message->setBody($textBody);
    }

    $this->mailer->send($message);
}

}

services.yml (excerpts)
truckee.registration_listener:
    class: Truckee\VolunteerBundle\EventListener\RegistrationListener
    arguments:
        em: @doctrine.orm.entity_manager
        mailer: @admin.mailer
        tools: @truckee.toolbox
    tags:
        - { name: kernel.event_subscriber }
//toolbox gets user type (amongst other functions)
truckee.toolbox:
    class: Truckee\VolunteerBundle\Tools\Toolbox
    arguments: [@doctrine.orm.entity_manager]
//admin mailer sends lots of different e-mail messages
admin.mailer:
    class: Truckee\VolunteerBundle\Tools\AdminMailer
    arguments:
        - '@mailer'
        - '@router'
        - '@twig'
        -
            sandbox: %sandbox%
            address: %admin_email%
            template:
                confirmation: '%fos_user.registration.confirmation.template%'
                resetting: '%fos_user.resetting.email.template%'
            from_email:
                confirmation: '%fos_user.registration.confirmation.from_email%'
                resetting: '%fos_user.resetting.email.from_email%'
        - '@doctrine.orm.entity_manager'

A: In the documentation here it shows how you can override the registration controller to log a user registration event. It shouldn't take much to change that to send an email to your admins instead of creating a log entry.
See also how to send an email.


text:
Q: How Can I Concatenate Many Sets of Columns Into Several New Columns? I have a spreadsheet. 60 rows, ~100 columns.
I wish to concatenate the data from each set of 3 columns, to produce ~30 columns of 'merged' data.
e.g. currently columns include "Fighter 1", "Fighter 2", Fighter 3", "Wizard 1", "Wizard 2", Wizard 3" etc.
i wish to put the data from each set into I column each, labelled "Fighter", "Wizard" etc. with the data from the three columns 'merged', with a delimiter (:). I  need Empty Cells included.
I know I can use CONCATENATE(B2, C2, D2) to combine the data from one set of cells.
I can Drag this formula down, to fill the column.
But if I drag the Formula sidewards (to the right), it increments each value by 1, rather than the 3 that I need.
e.g. I want the columns to become (B2, C2, D2), (E2, F2, G2), (H2, I2, J2) etc, but I get (B2, C2, D2), (C2, D2, E2), (D2, E2, F2) ...

A: You could make use of the OFFSET function
We'll start with the premise that your data spans Column A to Column CU (1-99) and your "merged" data spans column CW to Column EC (101-133).
Starting with Cell CW2 (assuming your headers are on row 1), write this formula (I've added line breaks to make it easier to read):
=CONCATENATE(
    OFFSET($A2, 0, 3 * (COLUMN() - 101)),
    OFFSET($B2, 0, 3 * (COLUMN() - 101)),
    OFFSET($C2, 0, 3 * (COLUMN() - 101))
)

This will concatenate together the three adjacent columns of the original dataset, and when you drag-fill the formula to each of the next 32 columns, each merged column will have been offset by exactly three cells each, lining them up to concatenate all your data.
The important parts that you might need to change in that function for your use:

*

*$A2 It's important to start with whichever column is the start of your entire dataset, not just the columns relative to each merged set. Other than that though, if your data starts at Column C or E or Z or wherever, this will still work so long as this references that first column.

*3 Is a reference to how many columns you're grouping by. If you had a series like "Fighter 1" "Fighter 2" "Fighter 3" "Fighter 4" "Wizard 1" "Wizard 2" "Wizard 3" "Wizard 4"...., then you'd use 4 instead of 3.

*101 is the 1-indexed column of the start of your "Merged" data. That way, COLUMN()-101 is 0 for the first column, 1 for the second, 2 for the third, and so on. This then gets multiplied by 3 above to yield 0, 3, 6, 9, ...


text:
Q: Two Dirichlet characters $\chi$, $\chi'$ are equal if $\chi(p) = \chi'(p)$ for almost all primes I want to prove the following: Let $\chi, \chi'$ be two primitive Dirichlet-characters of conductor $N$. Suppose that $\chi(p) = \chi'(p)$ for all but a finite number of primes $p$. Then $\chi = \chi'$.
My idea was to use the same trick as in Euclid's proof of the infinitude of primes. Let $p_1, ..., p_n$ be the (pairwise distinct) primes not dividing $N$ such that $\chi(p_i) \neq \chi'(p_i)$. Then $p_1 \cdots p_n + N$ is coprime to $N$ and no $p_i$ divides $p_1 \cdots p_n + N$. So $\chi(p_1 \cdots p_n + N) = \chi'(p_1 \cdots p_n + N)$. Now I thought we can use the fact that $p_1 \cdots p_n + N$ is a unit in $\mathbf{Z} / N\mathbf{Z}$, but I couldn't get my head around that.
Does anyone know how to do it?
Thanks!

A: You only need to check that $\chi(a)=\chi'(a)$ for every $a\in(\mathbb{Z}/N\mathbb{Z})^\times$. By Dirichlet's theorem, there exists a prime $p\equiv a\bmod N$ such that $\chi(p)=\chi'(p)$. Repeat this for every $a$ and you are done.