Q: How can i create a file for JSONmodel programmatically and automatically create its Codable struct How can i build a function that takes string as a parameter, that string will be my JSONObject and then this function will create a file in project that contains a struct which have keys of my model like this page does https://app.quicktype.io
I will pass this kind of string to function:
  [
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }]

It will create a file in project like:
import Foundation

// MARK: - UserInfoModelElement
struct UserInfoModelElement: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}

// MARK: - Address
struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}

// MARK: - Geo
struct Geo: Codable {
    let lat, lng: String
}

// MARK: - Company
struct Company: Codable {
    let name, catchPhrase, bs: String
}

typealias UserInfoModel = [UserInfoModelElement]

A: I'm building exactly this as an open source project on GitHub juliofruta/CodableCode. Feel free to submit a Pull request since this does not support all cases as specified in the comments. I'm copy and pasting my current solution here:
import Foundation

enum Error: Swift.Error {
    case invalidData
}

let identation = "    "

extension String {

    var asType: String {
        var string = self
        let firstChar = string.removeFirst()
        return firstChar.uppercased() + string
    }

    var asSymbol: String {
        var string = self
        let firstChar = string.removeFirst()
        return firstChar.lowercased() + string
    }

    mutating func lineBreak() {
        self = self + "\n"
    }

    func makeCodableTypeArray(anyArray: [Any], key: String, margin: String) throws -> String {
        var types = Set<String>()
        var existingTypes = Set<String>()
        var structCodeSet = Set<String>()

        try anyArray.forEach { jsonObject in

            var type: String?

            // check what type is each element of the array
            switch jsonObject {
            case _ as String:
                type = "String"
            case _ as Bool:
                type = "Bool"
            case _ as Decimal:
                type = "Decimal"
            case _ as Double:
                type = "Double"
            case _ as Int:
                type = "Int"
            case let dictionary as [String: Any]:
                let objectData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
                let objectString = String(data: objectData, encoding: .utf8)!
                let dummyTypeImplementation = try objectString.codableCode(name: "TYPE", margin: "")

                // if the existing type does not contain the dummy type implementation
                if !existingTypes.contains(dummyTypeImplementation) {
                    // insert it
                    existingTypes.insert(dummyTypeImplementation)
                    // keep a count
                    if existingTypes.count == 1 {
                        type = key.asType
                    } else {
                        type = key.asType + "\(existingTypes.count)"
                    }
                    // and get the actual implementation
                    let typeImplementation = try objectString.codableCode(name: type!, margin: margin + identation)
                    structCodeSet.insert(typeImplementation)
                }
            default:
                type = ""
                assertionFailure() // unhandled case
            }
            if let unwrappedType = type {
                types.insert(unwrappedType)
            }
        }

        // write type
        var swiftCode = ""

        if types.isEmpty {
            swiftCode += "[Any]"
        } else if types.count == 1 {
            swiftCode += "[\(types.first!)]"
        } else {

            swiftCode += "\(key.asType)Options"

            // TODO: Instead of enum refactor to use optionals where needed.
            // TODO: Build Swift Build package plugin
            // Use diffing algorithm to introduce optionals?
            // Introduce strategies:
            // create
            // 1. enum withassociated types
            // 2. optionals where needed
            // 3. optionals everywhere

            // add support to automatically fix when reserved keywords have reserved words for example:
            // let return: Return // this does not compile and is part of the bitso api
            // so add support for coding keys
//
//            struct Landmark: Codable {
//                var name: String
//                var foundingYear: Int
//                var location: Coordinate
//                var vantagePoints: [Coordinate]
//
//                enum CodingKeys: String, CodingKey {
//                    case name = "return"
//                    case foundingYear = "founding_date"
//
//                    case location
//                    case vantagePoints
//                }
//            }

            // create enum
            swiftCode.lineBreak()
            swiftCode.lineBreak()
            swiftCode += margin + identation + "enum \(key.asType)Options: Codable {"

            types.forEach { type in
                swiftCode.lineBreak()
                // enum associatedTypes
                swiftCode += margin + identation + identation + "case \(type.asSymbol)(\(type))"
            }

            swiftCode.lineBreak()
            swiftCode += margin + identation + "}"
        }

        // write implementations
        structCodeSet.forEach { implementation in
            swiftCode.lineBreak()
            swiftCode.lineBreak()
            swiftCode += implementation
            swiftCode.lineBreak()
        }

        return swiftCode
    }

    /// Compiles a valid JSON to a Codable Swift Type as in the following Grammar spec: https://www.json.org/json-en.html
    /// - Parameter json: A valid JSON string
    /// - Throws: Not sure if it should throw right now. We can check if the JSON is valid inside
    /// - Returns: The string of the type produced by the JSON
    public func codableCode(name: String, margin: String = "") throws -> String {
        var swiftCode = ""
        swiftCode += margin + "struct \(name.asType): Codable {"
        guard let data = data(using: .utf8) else {
            throw Error.invalidData
        }
        if let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            try dictionary
                .sorted(by: { $0.0 < $1.0 })
                .forEach { pair in
                let (key, value) = pair
                swiftCode.lineBreak()
                swiftCode += margin + identation + "let \(key.asSymbol): "
                switch value {
                case _ as Bool:
                    swiftCode += "Bool"
                case _ as String:
                    swiftCode += "String"
                case _ as Decimal:
                    swiftCode += "Decimal"
                case _ as Double:
                    swiftCode += "Double"
                case _ as Int:
                    swiftCode += "Int"
                case let jsonObject as [String: Any]:
                    let objectData = try JSONSerialization.data(withJSONObject: jsonObject, options: [])
                    let objectString = String(data: objectData, encoding: .utf8)!
                    swiftCode += "\(key.asType)"
                    swiftCode.lineBreak()
                    swiftCode.lineBreak()
                    swiftCode += try objectString.codableCode(name: key, margin: margin + identation)
                    swiftCode.lineBreak()
                case let anyArray as [Any]:
                    swiftCode += try makeCodableTypeArray(anyArray: anyArray, key: key, margin: margin)
                // TODO: Add more cases like dates
                default:
                    swiftCode += "Any"
                }
            }
        }
        swiftCode.lineBreak()
        swiftCode += margin + "}"
        return swiftCode
    }

    public var codableCode: String? {
        try? codableCode(name: "<#SomeType#>")
    }
}


Q: How to reset/clear AudioUnit/AudioSession settings/properties in iOS? I am writing a VoIP app that uses AudioUnit for it's audio related tasks. Here, a lot of properties of AudioUnit and AudioSession are being set from a lot of places using the following two method
AudioComponentInstance audioUnit;
AudioComponent inputComponent;
AudioComponentDescription audioComponentDescription;
AudioStreamBasicDescription audioStreamBasicDescription;

AudioUnitSetProperty(audioUnit,
                     kAudioUnitProperty_StreamFormat,
                     kAudioUnitScope_Input,
                     kOutputBus,
                     &audioStreamBasicDescription,
                     sizeof(audioStreamBasicDescription));

AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput,
                        sizeof(allowBluetoothInput),
                        &allowBluetoothInput);

But at some point i want to clear all of my AudioUnit and AudioSession properties. And want to bring back all default settings. But i couldn't figure out how to do that. I tried with the following codes but none of those could do what i wanted.
AudioComponentInstance audioUnit;
AudioOutputUnitStop(audioUnit);

[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];

AudioUnitUninitialize(audioUnit);

Can anyone help me in this purpose ? Any code example would be very much helpful and appreciated. Solutions need to be from iOS 7 to upper.


Q: Параметры открытия pdf. Как защитить файл PDF от копирования Имеется файл pdf, используется просмотрщик Adobe reader, файл открывается внутри "браузера" (1С 8.3), передаю при открытии параметры scrollbar=0, toolbar=0, statusbar=0, navpanes=0 (параметры брал в документе от Adobe https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf).
Все панельки управления скрыты. Правая кнопка мыши дает возможность распечатать PDF. Нигде не могу найти параметра для запрета печати или отключения контекстного меню.
Кто сталкивался с таким: полная защита документа от печати (варианты подписи и шифрования через саму Adobe Reader не подходят)


Q: Rearranging posts based on categories Hey everyone on Stackexchange!
I'm trying to find a way to prioritize posts based on a category in a loop, which is sorted by dates. All posts are grouped under their respective dates. The date labels appear once on top of posts of the same date like this:
Date

*

*Post1

*Post2

*Post3

Date before that

*

*Post 4

*Post 5

etc
I'm trying to achieve a result, where if a post belongs to a certain predetermined category (I would only be using 1 category), it would be moved above others under a date as such:
Date

*

*Post3 (special category)

*Post1

*Post2

Date before that

*

*etc

I've done research for a while on this topic and I can't figure out whether this would even be possible or not. Some query functions seem to serve a similar purpose, but I'm not certain and the date sorting makes it harder to figure out. Would I need multiple loops or something of that nature?
My loop: http://pastebin.com/Pp0rA5j7
The loop and the sorting mechanism look like this in general (pastebin for a full code):
<?php $w_h = $w_d = $last = 0; ?>

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

    <?php
    if ( date('Yz') == get_the_time('Yz') ) {
        if (!$w_d++) echo '
Today
';
    } elseif ( date('Yz')-1 == get_the_time('Yz') ) {
        if (!$w_h++) echo '
Yesterday
';
    } else {
        echo the_date('', '
', '
');
    }; ?>

// post content

    <?php endwhile; ?>
    <?php endif; ?>
                     <?php else : ?>

Sample site: http://goldenred.web44.net (I would like to move the post test 6 with the category "test" above others under February 3, 2013)
I would be extremely thankful if anyone more experienced could help or at least point me towards a general direction. All comments are welcome.

A: May be it's a bad idea, but it's the only.
Don't print posts immediately, but collect them in different variables: one for category "test", one for the rest.
<?php
$w_h = $w_d = $last = 0;
// init variables to concatenate content later
$primary_posts = $secondary_posts = '';
// empty array to fill later
$category_names = array();
if (have_posts()) :
    while (have_posts()) :
        the_post();
        if ( date('Yz') == get_the_time('Yz') ) {
            if (!$w_d++) echo '
Today
';
        } elseif ( date('Yz')-1 == get_the_time('Yz') ) {
            if (!$w_h++) echo '
Yesterday
';
        } else {
            echo the_date('', '
', '
');
        };
        // get post categories
        $category_objects = get_the_category();
        foreach($category_objects as $category_object) {
            $category_names[] = $category_object->name;
        }
        // if posts belongs to category 'test'
        if( in_array('test', $category_names) ) {
            $primary_posts .= '
Post of category "test"';
            // title, categories and excerpt goes here
            $primary_posts .= '
';
        }
        else {
            $secondary_posts .= '
Post of category other than "test"';
             // title, categories and excerpt goes here
            $secondary_posts .= '
';
       }

    endwhile;
    // output all posts of category "test"
    echo $primary_posts;
    // output all posts of category other than "test"
    echo $secondary_posts;
endif;

A: Alright I looked up WP_Query options and I started figuring if it would be easier to abolish the current date sorting system for a more efficient one that would be more flexible in terms of customization? Personally, I'm all for out of the box solutions and I'm not attached to the code I have in my index. The main goal would be to only achieve the described functionality - posts grouped by dates, and prioritizing (2 levels) within groups. Everything else could change by me. This feature isn't for a client or anything, it's for my personal website. I really need that functionality. Anyway, enough rambling, here's the code I found:
$args = array('posts_per_page' => -1, 'orderby' => 'date' );

$myQuery = new WP_Query($args);

$date = '';

if ( $myQuery->have_posts() ) : while ( $myQuery->have_posts() ) : $myQuery->the_post();

if ( $date != get_the_date() ) {
    echo $date;
    echo '
';
    $date = get_the_date();
}

the_title(); // or whatever you want here.
echo '
';

endwhile; endif;
wp_reset_postdata();

Would something like this be a better base for what I described?


Q: How to fetch only the documents that have 3 different values in mongodb? I have the following data in mongodb:
    {
        "_id" : ObjectId("111"),
        "id" : "111",
        "classification" : [
            {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

   {
        "_id" : ObjectId("222"),
        "id" : "222",
        "classification" : [
                   {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "blue"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

  {
        "_id" : ObjectId("333"),
        "kind" : "youtube#video",
        "etag" : "tagvalue",
        "id" : "333"
    }

Please note that the classification label does not exists in all my records, as shown in record with id: "333".
I need to get all the records from my database that have different category values.
So, I need a query that when I run it, I will only get the record that has the classification label, and has exactly 3 different category values, in this case, I want a query that will only return this to me:
{
        "_id" : ObjectId("222"),
        "id" : "222",
        "classification" : [
            {
                "annotator" : "annotatorName1",
                "category" : "white"
            },
            {
                "annotator" : "annotatorName2",
                "category" : "blue"
            },
            {
                "annotator" : "annotatorName3",
                "category" : "black"
            }
        ]
    }

What command should I enter in my terminal in order to get all the records that have 3 unique category values under classification, IFF classification exists?
Thank you for your help.

A: The below aggregate can be used to find out the "id"s which have exactly 3 unique categories:
db.collectionName.aggregate([
  {$match : {classification : {$exists : true}}},
  {$unwind: "$classification"},
  {$group: { _id: "$id", uniqueCategories: {$addToSet: "$classification.category"}}},
  {$project: {_id : 1, numberOfCategories: {$size: "$uniqueCategories"}} },
  {$match: {numberOfCategories: 3} }
])

Explanation: We start with matching documents which have the classification element. Then we $unwind it so as to deconstruct the embedded array into separate documents. Then it is grouped by id, and using $addToSet the categories are collected into an array - this takes care of eliminating any dupes. Then we project its $size and match on 'equal to 3'.
This aggregate will yield documents with the _id set to the id field of the documents in your collection that have 3 unique categories, which you can use to get to the documents. If your collection size is quite large, you should consider adding another $match stage in the beginning to restrict the dataset. As it stands now, it will be doing a collection scan.


Q: Why does Keras convert the input shape from (3,3) to (?,3,3)? I am currently trying to get custom keras layers to work, you can see a simplified version here:
class MyLayer(Layer):

    def __init__(self, **kwargs):
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        print("input_shape: "+str(input_shape))
        self.kernel = self.add_weight(name='kernel',
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)

    def call(self, x):
        print("input tensor: "+str(x))
        return K.dot(x, self.kernel)

inputs = Input(shape=(3,3), dtype='float', name='inputs')
results = MyLayer(input_shape=(3,3))(inputs)

The resulting console output is this:
input_shape: (None, 3, 3)
input tensor: Tensor("inputs:0", shape=(?, 3, 3), dtype=float32)

As you can see, the input_shape that the layer gets is not (3,3) as I specified but actually (None,3,3). Why is that?
The shape of the input tensor is also shaped ( ?, 3,3) which I thought to be a consequence of the weird input_shape ( None, 3,3). But the input tensor also has this shape with a third dimension if you replace super(MyLayer, self).build(input_shape) with super(MyLayer, self).build((3,3)). What is this mysterious third dimension keras automatically adds and why does it do that?

A: It is nothing mysterious, it is the batch dimension, since keras (and most DL frameworks), make computations on batches of data at a time, since this increases parallelism, and it maps directly to batches in Stochastic Gradient Descent.
Your layer needs to support computation on batches, so the batch dimension is always present in input and output data, and it is automatically added by keras to the input_shape.

A: This newly added dimension refers to the batch dimension, i.e., in your case, you will be passing batches of 3x3 dimensional tensors. This additional None dimension refers to the batch dimension, which is unknown during the creation of the graph.
If you have a look at the Input layer explanation in Core Layers webpage for Keras,
https://keras.io/layers/core/, you will see that the shape argument you are passing when creating the Input layer is defined as the following:

shape: A shape tuple (integer), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors.

A: If you want to specify the batch size, you can do this instead:
inputs = Input(batch_shape=(batch_size,height,width,channel))


Q: CSS rotate3d property behaving unexpectedly I was reading about the CSS rotate3d() property to rotate an element. I thought that the first three parameters in the function are multipliers and the fourth one is the degree magnitude.
The value of multipliers has to be between 0 and 1. This means that rotate3d(1, 0, 0, 90deg) will only result in rotateX(90deg). To get more range of rotations I changed it to rotate3d(0.25, 0, 0, 360deg) but it produces entirely different result.
I also noticed that transform: rotateX(45deg) rotateY(45deg); is not the same as transform: rotate3d(1,1,0, 45deg);. etc. If we cannot simply change the multiplier of required dimensions to get desired rotations, how should I calculate the value of three multipliers?
Thanks.

A: When using rotate3d(x, y, z, a) the first 3 numbers are coordinate that will define the vector of the rotation and a is the angle of rotation. They are not multiplier of the rotation.
rotate3d(1, 0, 0, 90deg) is the same as rotate3d(0.25, 0, 0, 90deg) and also the same as rotate3d(X, 0, 0, 90deg) because we will have the same vector in all the cases. Which is also the same as rotateX(90deg)

.box {
  margin:30px;
  padding:20px;
  background:red;
  display:inline-block;
}

From this we can also conclude that rotate3d(0, Y, 0, a) is the same as rotateY(a) and rotate3d(0, 0, Y, a) the same as rotate(a). Note the use of 0 in two of the coordinates which will make our vector always in the same axis (X or Y or Z)

rotate3d(1,1,0, 45deg) is not the same as rotateX(45deg) rotateY(45deg). The first one will perform one rotation around the vector defined by (1,1,0) and the second one will perform two consecutive rotation around the X and Y axis.
In other words, rotate3d() is not a combination of the other rotation but a rotation on its own. The other rotation are particular cases of rotate3d() considering predefined axis.

The multiplier trick apply to the coordinate if you keep the same angle. rotate3d(x, y, z, a) is equivalent to rotate3d(p*x, p*y, p*z, a) because if you multiply all the coordinates with the same value, you keep the same vector direction and you change only the vector dimension which is irrelevant when defining the rotation. Only the direction is relevant.
More details here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
You can clearly notice that using values in the range of [-1,1] for x,y,z is enough to define all the combination. In the other hand, any combination of x,y,z can be reduced to values inside the range [-1,1]
Examples:

.box {
  margin:30px;
  padding:20px;
  background:red;
  display:inline-block;
}

We simply divide by the biggest number.


Q: how to count word frequency of words in dictionary? I have a dictionary like below:
[{'mississippi': 1, 'worth': 1, 'reading': 1}, {'commonplace': 1, 'river': 1, 'contrary': 1, 'ways': 1, 'remarkable': 1}, {'considering': 1, 'missouri': 1, 'main': 1, 'branch': 1, 'longest': 1, 'river': 1, 'world--four': 1}, {'seems': 1, 'safe': 1, 'crookedest': 1, 'river': 1, 'part': 1, 'journey': 1, 'uses': 1, 'cover': 1, 'ground': 1, 'crow': 1, 'fly': 1, 'six': 1, 'seventy-five': 1}, {'discharges': 1, 'water': 1, 'st': 1}, {'lawrence': 1, 'twenty-five': 1, 'rhine': 1, 'thirty-eight': 1, 'thames': 1}, {'river': 1, 'vast': 1, 'drainage-basin:': 1, 'draws': 1, 'water': 1, 'supply': 1, 'twenty-eight': 1, 'states': 1, 'territories': 1, 'delaware': 1, 'atlantic': 1, 'seaboard': 1, 'country': 1, 'idaho': 1, 'pacific': 1, 'slope--a': 1, 'spread': 1, 'forty-five': 1, 'degrees': 1, 'longitude': 1}, {'mississippi': 1, 'receives': 1, 'carries': 1, 'gulf': 1, 'water': 1, 'fifty-four': 1, 'subordinate': 1, 'rivers': 1, 'navigable': 1, 'steamboats': 1, 'hundreds': 1, 'flats': 1, 'keels': 1}, {'area': 1, 'drainage-basin': 1, 'combined': 1, 'areas': 1, 'england': 1, 'wales': 1, 'scotland': 1, 'ireland': 1, 'france': 1, 'spain': 1, 'portugal': 1, 'germany': 1, 'austria': 1, 'italy': 1, 'turkey': 1, 'almost': 1, 'wide': 1, 'region': 1, 'fertile': 1, 'mississippi': 1, 'valley': 1, 'proper': 1, 'exceptionally': 1}]

And I want to change it to my desired output like below to calculate score of similarity between two target words:
river 4
    ground: 1
    journey: 1
    longitude: 1
    main: 1
    world--four: 1
    contrary: 1
    cover: 1
    delaware: 1
    remarkable: 1
    vast: 1
    forty-five: 1
    crookedest: 1
    territories: 1
    spread: 1
    country: 1
    longest: 1
    fly: 1
    atlantic: 1
    crow: 1
    supply: 1
    seems: 1
    idaho: 1
    seaboard: 1
    states: 1
    ways: 1
    degrees: 1
    part: 1
    twenty-eight: 1
    pacific: 1
    branch: 1
    water: 1
    considering: 1
    six: 1
    safe: 1
    commonplace: 1
    draws: 1
    drainage-basin: 1
    uses: 1
    seventy-five: 1
    slope--a: 1
    missouri: 1
mississippi 3
    area: 1
    steamboats: 1
    germany: 1
    reading: 1
    france: 1
    proper: 1
    fifty-four: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    carries: 1
    combined: 1
    flats: 1
    receives: 1
    england: 1
    italy: 1
    scotland: 1
    wales: 1
    almost: 1
    navigable: 1
    austria: 1
    region: 1
    wide: 1
    spain: 1
    subordinate: 1
    drainage-basin: 1
    hundreds: 1
    keels: 1
    portugal: 1
    water: 1
    gulf: 1
    ireland: 1
    rivers: 1
    valley: 1
    fertile: 1
    worth: 1
water 3
    steamboats: 1
    spread: 1
    country: 1
    states: 1
    longitude: 1
    fifty-four: 1
    pacific: 1
    vast: 1
    subordinate: 1
    carries: 1
    keels: 1
    flats: 1
    supply: 1
    receives: 1
    atlantic: 1
    forty-five: 1
    river: 1
    rivers: 1
    idaho: 1
    mississippi: 1
    seaboard: 1
    navigable: 1
    discharges: 1
    degrees: 1
    twenty-eight: 1
    drainage-basin: 1
    hundreds: 1
    st: 1
    gulf: 1
    draws: 1
    delaware: 1
    territories: 1
    slope--a: 1
drainage-basin 2
    area: 1
    spread: 1
    country: 1
    states: 1
    mississippi: 1
    longitude: 1
    france: 1
    proper: 1
    vast: 1
    turkey: 1
    forty-five: 1
    areas: 1
    combined: 1
    germany: 1
    exceptionally: 1
    valley: 1
    supply: 1
    fertile: 1
    atlantic: 1
    italy: 1
    river: 1
    idaho: 1
    wales: 1
    almost: 1
    seaboard: 1
    spain: 1
    austria: 1
    region: 1
    degrees: 1
    twenty-eight: 1
    wide: 1
    england: 1
    portugal: 1
    water: 1
    ireland: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    scotland: 1
    slope--a: 1
area 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
journey 1
    ground: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
seems 1
    ground: 1
    journey: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
states 1
    spread: 1
    country: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
slope--a 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
remarkable 1
    contrary: 1
    river: 1
    commonplace: 1
    ways: 1
vast 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    pacific: 1
    forty-five: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
forty-five 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    pacific: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
crookedest 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
carries 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
germany 1
    area: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
longest 1
    main: 1
    river: 1
    world--four: 1
    branch: 1
    missouri: 1
    considering: 1
flats 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    rivers: 1
    receives: 1
supply 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    twenty-eight: 1
    river: 1
    idaho: 1
receives 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
crow 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
scotland 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    spain: 1
    italy: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
country 1
    spread: 1
    idaho: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
thames 1
    thirty-eight: 1
    rhine: 1
    lawrence: 1
    twenty-five: 1
england 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    region: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
navigable 1
    mississippi: 1
    steamboats: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
austria 1
    area: 1
    germany: 1
    mississippi: 1
    france: 1
    proper: 1
    region: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    exceptionally: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
rhine 1
    thirty-eight: 1
    thames: 1
    lawrence: 1
    twenty-five: 1
part 1
    ground: 1
    journey: 1
    seems: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
twenty-eight 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
branch 1
    main: 1
    longest: 1
    river: 1
    world--four: 1
    missouri: 1
    considering: 1
hundreds 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
st 1
    water: 1
    discharges: 1
considering 1
    main: 1
    longest: 1
    river: 1
    world--four: 1
    branch: 1
    missouri: 1
six 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    fly: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
gulf 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    flats: 1
    rivers: 1
    receives: 1
ireland 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    valley: 1
safe 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
commonplace 1
    contrary: 1
    river: 1
    remarkable: 1
    ways: 1
draws 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    supply: 1
    delaware: 1
    territories: 1
    atlantic: 1
    twenty-eight: 1
    river: 1
    idaho: 1
delaware 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
thirty-eight 1
    thames: 1
    rhine: 1
    lawrence: 1
    twenty-five: 1
longitude 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
world--four 1
    main: 1
    longest: 1
    river: 1
    branch: 1
    missouri: 1
    considering: 1
lawrence 1
    thirty-eight: 1
    thames: 1
    rhine: 1
    twenty-five: 1
ground 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
steamboats 1
    mississippi: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
spread 1
    seaboard: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
idaho 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
reading 1
    mississippi: 1
    worth: 1
almost 1
    area: 1
    germany: 1
    austria: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    mississippi: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
contrary 1
    river: 1
    remarkable: 1
    commonplace: 1
    ways: 1
cover 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
    fly: 1
france 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
spain 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
pacific 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    twenty-eight: 1
    river: 1
    idaho: 1
turkey 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
fifty-four 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    hundreds: 1
    keels: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
subordinate 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    water: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
territories 1
    spread: 1
    idaho: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    supply: 1
    atlantic: 1
    slope--a: 1
    river: 1
    country: 1
combined 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
exceptionally 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    region: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
region 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
twenty-five 1
    thirty-eight: 1
    thames: 1
    lawrence: 1
    rhine: 1
rivers 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    carries: 1
    fifty-four: 1
    keels: 1
    hundreds: 1
    subordinate: 1
    water: 1
    gulf: 1
    flats: 1
    receives: 1
fly 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    seventy-five: 1
    river: 1
atlantic 1
    spread: 1
    longitude: 1
    country: 1
    states: 1
    degrees: 1
    slope--a: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    river: 1
    supply: 1
    twenty-eight: 1
    idaho: 1
italy 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
main 1
    world--four: 1
    longest: 1
    river: 1
    branch: 1
    missouri: 1
    considering: 1
areas 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    england: 1
    turkey: 1
    exceptionally: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
seaboard 1
    spread: 1
    country: 1
    states: 1
    degrees: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
fertile 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
ways 1
    contrary: 1
    river: 1
    remarkable: 1
    commonplace: 1
discharges 1
    water: 1
    st: 1
degrees 1
    spread: 1
    country: 1
    states: 1
    longitude: 1
    twenty-eight: 1
    drainage-basin: 1
    vast: 1
    forty-five: 1
    water: 1
    seaboard: 1
    pacific: 1
    draws: 1
    delaware: 1
    territories: 1
    atlantic: 1
    supply: 1
    slope--a: 1
    river: 1
    idaho: 1
wide 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
proper 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    england: 1
    turkey: 1
    exceptionally: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1
keels 1
    mississippi: 1
    steamboats: 1
    navigable: 1
    water: 1
    fifty-four: 1
    hundreds: 1
    subordinate: 1
    carries: 1
    gulf: 1
    flats: 1
    rivers: 1
    receives: 1
portugal 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    ireland: 1
    valley: 1
worth 1
    mississippi: 1
    reading: 1
uses 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    fly: 1
    seventy-five: 1
    river: 1
seventy-five 1
    ground: 1
    journey: 1
    seems: 1
    part: 1
    cover: 1
    crow: 1
    crookedest: 1
    six: 1
    safe: 1
    uses: 1
    river: 1
    fly: 1
valley 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    wales: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
missouri 1
    main: 1
    longest: 1
    river: 1
    branch: 1
    world--four: 1
    considering: 1
wales 1
    area: 1
    germany: 1
    austria: 1
    mississippi: 1
    france: 1
    proper: 1
    exceptionally: 1
    turkey: 1
    england: 1
    areas: 1
    combined: 1
    scotland: 1
    italy: 1
    spain: 1
    almost: 1
    fertile: 1
    region: 1
    wide: 1
    drainage-basin: 1
    portugal: 1
    ireland: 1
    valley: 1

the first line is the target word and its frequency in the whole dictionary. Underneath is the associated words and their frequency in same sentence with target word. Like the first dictionary, the profile associated with "mississippi" will contain references to "worth" and "reading" and their word frequency in sentence is 1, but the word frequency of mississippi is 3 in entire dictionary. And I want to sort the word frequency of target word in descending order. Anyone can help?

A: It's not exactly clear neither from your desired output nor from your code what exactly are you trying to achieve but if it's just counting words in individual sentences then the strategy should be:

*

*Read your common.txt into a set for a fast lookup.

*Read your sample.txt and split on . to get individual sentences.

*Clear up all non-word characters (you'll have to define them or to use regex \b to capture word boundaries) and replace them with whitespace.

*Split on whitespace and count the words not present in the set from Step 1.

So:
import collections

with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\""  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    # read the whole file to include linebreaks and split on `.` to get individual sentences
    sentences = [s for s in f.read().split(".") if s.strip()]  # ignore empty sentences
    for sentence in sentences:  # iterate over each sentence
        sentence = sentence.translate(trans_table)  # replace the interpunction with spaces
        word_counter = collections.defaultdict(int)  # a string:int default dict for counting
        for word in sentence.split():  # split the sentence and iterate over the words
            if word.lower() not in common_words:  # count only words not in the common.txt
                word_counter[word.lower()] += 1
        sentences_counter.append(word_counter)  # add the current sentence word count

NOTE: On Python 2.x use string.maketrans() instead of str.maketrans().
This will produce sentences_counter containing a dictionary count for each of the sentences in sample.txt, where the key is an actual word and its associate value is the word count. You can print the result as:
for i, v in enumerate(sentences_counter):
    print("Sentence #{}:".format(i+1))
    print("\n".join("\t{}: {}".format(w, c) for w, c in v.items()))

Which will produce (for your sample data):
Sentence #1:
    area: 1
    drainage-basin: 1
    great: 1
    combined: 1
    areas: 1
    england: 1
    wales: 1
    wide: 1
    region: 1
    fertile: 1
Sentence #2:
    mississippi: 1
    valley: 1
    proper: 1
    exceptionally: 1
Keep in mind that (English) language is more complex than this - for example, "A cat wiggles its tail when it's angry so stay away from it." will vastly differ in dependence on how you treat an apostrophe. Also, a dot doesn't necessarily denote the end of a sentence. You should look into NLP if you want to do serious linguistic analysis.
UPDATE: While i don't see the usefulness of reiterating over each word repeating the data (the count won't ever change within a sentence) if you want to print each word and nest all the other counts underneath you can just add an inner loop while printing:
for i, v in enumerate(sentences_counter):
    print("Sentence #{}:".format(i+1))
    for word, count in v.items():
        print("\t{} {}".format(word, count))
        print("\n".join("\t\t{}: {}".format(w, c) for w, c in v.items() if w != word))

Which will give you:
Sentence #1:
    area 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    drainage-basin 1
        area: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    great 1
        area: 1
        drainage-basin: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    combined 1
        area: 1
        drainage-basin: 1
        great: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    areas 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    england 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        wales: 1
        wide: 1
        region: 1
        fertile: 1
    wales 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wide: 1
        region: 1
        fertile: 1
    wide 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        region: 1
        fertile: 1
    region 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        fertile: 1
    fertile 1
        area: 1
        drainage-basin: 1
        great: 1
        combined: 1
        areas: 1
        england: 1
        wales: 1
        wide: 1
        region: 1
Sentence #2:
    mississippi 1
        valley: 1
        proper: 1
        exceptionally: 1
    valley 1
        mississippi: 1
        proper: 1
        exceptionally: 1
    proper 1
        mississippi: 1
        valley: 1
        exceptionally: 1
    exceptionally 1
        mississippi: 1
        valley: 1
        proper: 1
Feel free to remove the sentence number printing and reduce one of the tab indentations to get something more of a desired output from your question. You can also build a tree-like dictionary instead of printing everything to the STDOUT if that's more what you fancy.
UPDATE 2: If you want, you don't have to use a set for the common_words. In this case it's pretty much interchangeable with a list so you can use list comprehension instead of set comprehension (i.e. replace curly with square brackets) but looking through a list is an O(n) operation whereas set lookup is an O(1) operation and therefore a set is preferred here. Not to mention the collateral benefit of automatic de-duplication in case the common.txt has duplicate words.
As for the collections.defaultdict() it's there just to save us some coding/checking by automatically initializing the dictionary to a key whenever it's requested - without it you'd have to do it manually:
with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\""  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    # read the whole file to include linebreaks and split on `.` to get individual sentences
    sentences = [s for s in f.read().split(".") if s.strip()]  # ignore empty sentences
    for sentence in sentences:  # iterate over each sentence
        sentence = sentence.translate(trans_table)  # replace the interpunction with spaces
        word_counter = {}  # initialize a word counting dictionary
        for word in sentence.split():  # split the sentence and iterate over the words
            word = word.lower()  # turn the word to lowercase
            if word not in common_words:  # count only words not in the common.txt
                word_counter[word] = word_counter.get(word, 0) + 1  # increase the last count
        sentences_counter.append(word_counter)  # add the current sentence word count

UPDATE 3: If you just want a raw word list across all sentences as it seems from your last update to the question, you don't even need to consider the sentences themselves - just add a dot to the interpunction list, read the file line by line, split on whitespace and count the words as before:
import collections

with open("common.txt", "r") as f:  # open the `common.txt` for reading
    common_words = {l.strip().lower() for l in f}  # read each line and and add it to a set

interpunction = ";,'\"."  # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))

sentences_counter = []  # a list to hold a word count for each sentence

word_counter = collections.defaultdict(int)  # a string:int default dict for counting
with open("sample.txt", "r") as f:  # open the `sample.txt` for reading
    for line in f:  # read the file line by line
        for word in line.translate(trans_table).split():  # remove interpunction and split
            if word.lower() not in common_words:  # count only words not in the common.txt
                word_counter[word.lower()] += 1  # increase the count

print("\n".join("{}: {}".format(w, c) for w, c in word_counter.items()))  # print the counts


Q: Why $a^4 + b^4$ ($a, b$ are positive integers) is not a perfect square? I've realized that there are maybe no positive integers $(a, b)$ that $a^4 + b^4$ is a perfect square, because I tested for $a, b \le 10000$ and cannot find any solution.

I think that's weird, and how to prove it?


Q: ngTable with ng-if is not working I'm using ng-table with angularJs as shown below.My problem is when I use ngTable it's rendered same column twice (MyColumn).In other words it doesn't consider the ng-if.How can I get rid of that issue ?
Note : But for the normal table it's working fine.Why is that not working with the ngTable ?
ngTable

      {{item.Value}}
       {{item.Value}}

A: I did it as shown below.It works fine. Hurray :D

      {{item.Value}}
      {{item.Value}}


Q: How to get the searched text in a string? I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?

A: Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid

Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid

A: Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
    result = text.substring(index + after.length());
}
System.out.print(result);

A: Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
  if(stringyouwanttoTrim.contains("I am")
  {
    return stringyouwanttoTrim.split("I am")[1].trim();
  }
  else
  {
    return stringyouwanttoTrim;
  }
}

A: If you prefer to split your sentence by blank space you could do like this :
 String [] myStringElements = "I am Vahid".split(" ");
 System.out.println("your name is " + myStringElements[myStringElements.length - 1]);


Q: sending mail in php with user informations hii evryone plz i need help i want to know why my code send only the attachment but not the others informations of my contact form here is my code php
here is my code the attachement is sent correctly but the other
informations not  i dont using any framework it is just php
i use a contact form with attachement
error_reporting(E_ALL);
ini_set("display_errors", 1); //Affichage des erreurs

//Eviter les insertions de scripts dans le cas d'un e-mail HTML
$nom = htmlentities($_POST['firstname']);
$email = htmlentities($_POST['email']);
$nom=$_POST['firstname'];
//$prenom = htmlentities($_POST['prenom']);

//Verifie si le fournisseur prend en charge les r
if(preg_match("#@(hotmail|live|msn).[a-z]{2,4}$#", $email)){
$passage_ligne = "\n";
}else{
$passage_ligne = "\r\n";
 }

  $email_to = "mon adresse email"; //Destinataire
  $email_subject = "Recrutement "; //Sujet du mail
  $boundary = md5(rand()); // clé aléatoire de limite

  $headers = "MIME-Version: 1.0\r\n";

  $headers.= "From: EA\r\n";
  $headers.= "Reply-To: EITA" . "\r\n";
  $headers.= "MIME-Version: 1.0" . $passage_ligne;
  $headers.= 'Content-Type: multipart/mixed; boundary='.$boundary .' '.
  $passage_ligne;

   //Pièce jointe
   if(isset($_FILES["fichier"]) && $_FILES['fichier']['name'] != ""){
   //Vérifie sur formulaire envoyé et que le fichier existe
    $nom_fichier = $_FILES['fichier']['name'];

   $source = $_FILES['fichier']['tmp_name'];
   $type_fichier = $_FILES['fichier']['type'];
   $taille_fichier = $_FILES['fichier']['size'];

 if($nom_fichier != ".htaccess"){ //Vérifie que ce n'est pas un .htaccess
 if($type_fichier == "image/jpeg"
 || $type_fichier == "image/pjpeg"
 || $type_fichier == "application/pdf"){ //Soit un jpeg soit un pdf

   if ($taille_fichier <= 2097152) { //Taille supérieure à Mo (en octets)
  $tabRemplacement = array("é"=>"e", "è"=>"e", "à"=>"a"); //Remplacement des
  caractères spéciaux

   $handle = fopen($source, 'r'); //Ouverture du fichier
   $content = fread($handle, $taille_fichier); //Lecture du fichier
    $encoded_content = chunk_split(base64_encode($content)); //Encodage
    $f = fclose($handle); //Fermeture du fichier
   //$message.='--'.$passage_ligne."\r\n";
   $email_message.="Content-Type: pdf; name=".$nom_fichier."\r\n";
    $email_message.="Content-Transfer-Encoding: BASE64"."\r\n";
    $email_message.="Content-Disposition: attachment;
   filename=".$nom_fichier."\r\n\r\n";
   $email_message.=
   chunk_split(base64_encode(file_get_contents($nom_fichier)))."\r\n";

   $email_message.='--'.$passage_ligne.'--'."\r\n";
   $email_message .= $encoded_content."n"; //Pièce jointe
   //$email_message .="Hello";

 }else{
 //Message d'erreur
  $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
 une pièce jointe mais celle ci était superieure à 2Mo.". $passage_ligne;
 }
 }else{
 //Message d'erreur
 $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
  une pièce jointe mais elle n'était pas au bon format.". $passage_ligne;
 }
 }else{
 //Message d'erreur
  $email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
  une pièce jointe .htaccess.". $passage_ligne;
   }
   }
  $email_message .= $passage_ligne . "--" . $boundary . "--" .
 $passage_ligne; //Séparateur de fermeture
 $msg.=$email_message.$nom."bonjour";
  if(mail($email_to,$email_subject, $msg, $headers)==true){ //Envoi du mail
  header('Location: index.php'); //Redirection
  }

  ?>


Q: select nodes in a graph such that any node is close enough to a selected node
Question.
Given an undirected graph, select minimum number of nodes, such that any node in the graph can be connected to a selected node with number of edges $\leq k$.

Any faster solution in the special case of $k=1$ and the graph is a tree (i.e. acyclic).
Example: $k=1$, graph is a single line of 6 nodes. Solution: O-X-O-O-X-O where X means selected.


Q: Expose Serializable Enum attributes in WCF I am trying to to expose an Enum from my WCF class (basically as a mechanism for passing a constant). When I look at the service reference code or the WSDL there is no sign of the Enum and I cannot use it. Why not?
[Serializable]
[DataContract]
public class MyRequest
{
    [DataContract]
    public enum Constants
    {
        [EnumMember]
        MaxMaxArticles = 1000
    }
}

A: I suspect you haven't used the enum anywhere in the contract. Unless you have, there is no reason that it would be included in the graph that it builds by walking members from the root contract type. It will not be included just because it is nested: it needs to be actually used somewhere.


Q: Array becomes undefined after page reload I am working on Angular WebApi. I have a database response on localhost in JSON format.
When I run my application, I can see the array oData. But when I reload the page then oData becomes undefined.
How can I solve this?
Here is my code from the .ts file:
  ngOnInit(): void {

    this.mydataser.getDbData().subscribe(data => {
      this.oData = data;
    });
  }

 public importData() {
    console.log(this.oData)
 }

Here is my service:
  getDbData(): Observable<DataFactory[]> {
    return this.http.get<DataFactory[]>("https://localhost:44216/api/dbdata");
  }

P.S. I tried to use localstorage but it does not work.

A: Declare data as an empty array; if you don't do it will be undefined until the API response is completed. If you want to know when the response is actually coming just use tap. So If you want to call importData() after API response is received then call this.importData() method inside subscribe like
// declare as empty array
oData = [];
buttonEnabled = false;

ngOnInit(): void {
    this.mydataser.getDbData().pipe(
        tap(d => this.buttonEnabled = true)
    ).subscribe(data => {
        this.oData = data;
    });
}

importData(): void{
 console.log(this.o.Data);
}

In template:
<button [disabled]="!buttonEnabled">Import</button>


Q: WCF Service Interface - XElement vs. XmlElement vs. xml string I am doing some work which requires a WCF Service interface (in C#). The data exchanged (sent and recieved) will be in the xml format --- I cannot use strong datatypes because the interface needs to support multiple clients which have different requirements.
My question is which one of these is preferable:
XElement MyServiceMethod(XElement inputParam 1)
{

    XElement retValue;

    //
    // Operation occurs here
    //

    return (retValue);

}

vs
XmlElement MyServiceMethod(XmlElement inputParam 1)
{
XmlElement retValue;

//
// Operation occurs here
//

return (retValue);

}
vs
//
//inputParam is an xml formatted string
//
string MyServiceMethod(string inputParam 1)
{

    string retValue;

    //
    // Operation occurs here
    //

        //retValue is an xml formatted string
    return (retValue);

}

The code will be consumed via SOAP interface primarily, though it may ultimately be consumed via REST as well.
Is there a "best" approach"? Likewise, is there one that is completely not desirous.


Q: Unable to change color of first text box in every row of table using jquery I am trying to change the background color of first text box in every row in a table and using below code for same purpose.
Somehow it does not seem to be working. Please help.

text1
<input type="text">
<input type="text">

text2
<input type="text">
<input type="text">

text3
<input type="text">
<input type="text">

A: Use :first selector with .find() to get input descendants.
$('tr').find(':text:first').css('background-color','#C0C0C0');

Demo
$("tr:text:first") in your code, finds tr with :text(type="text") which is invalid.

 does not have :text

A: Have you tried $("tr input:first-child").css('background-color','#C0C0C0'); ?

A: Also, if you can't get jQuery to work, it would be simple enough to add a class to the first table cell in each table row and style it that way, forgoing the time it would take to load jQuery(if that is an issue, as I have sometimes found it to be).


Q: Does Heroku support foreign key and unique constraints? I'm considering moving a Rails app to Heroku.
In general I add FK constraints with ON DELETE behavior to all FKs. Up to now I've done this by writing raw SQL to add the constraints, as Rails Migrations don't provide a way to do that.
I also add UNIQUE keys where needed.
Will I still be able to add constraints in this way if I move to Heroku?
Another way to put this question would be, do I get direct access to my DB with Heroku, or am I limited to what I can do in migrations?

A: You can execute any SQL you want in a migration using connection.execute, for example:
def up
    connection.execute(%q{
        alter table t add constraint c check (x in ('a', 'b', 'c'))
    })
end
def down
    connection.execute('alter table t drop constraint c')
end

You can also use foreigner to add proper FK support to your migrations and schema.rb if you don't want to manage your FKs through raw SQL.
You can use the :unique => true option to add_index to get unique constraints/indexes.
I've done all of this and even added functions (both SQL and Pl/pgSQL) and triggers to a dedicated PostgreSQL database at Heroku. I'm not sure how much is supported on the shared databases but unique indexes certainly will be and I'm pretty sure FKs and CHECKs will be available as well.


Q: How to declare two data types containing same variable in haskell? In a module, I want to add two classes like this.
data Person = Person { name :: String -- and some other details
                     }

data PetAnimal = PetAnimal { name :: String
                           }

I assumed this would work but ghc complains about multiple declrations of name. How do I accomplish this?

A: The problem here, I believe, is that Haskell defines access functions for all the fields in a record, so you get one function
name :: Person -> String

and then one
name :: PetAnimal -> String

which is what the compiler does not like.
You could change one or both of the names, or put them in different modules.

A: Type Classes are another way to achieve a common interface that you may consider.
data Person = Person { personname :: String -- and some other details
                     }

data PetAnimal = PetAnimal { petanimalname :: String
                           }

class HasName a where
  name :: a -> String

instance HasName PetAnimal where
   name = petanimalname

instance HasName Person where
   name = personname


Q: Get current latitude and longitude plus 500 meters Hi friends, I am having one event latitude and longitude, To checkin to this event i must be within 500 meters of that event.
I am getting current location using:
Geolocation.getLocation().then(function(position){
        $scope.position = position.coords;
        // console.log( $scope.position)
        $scope.locationError = null;
    });

Have to validate this current location with event latitude longitude coming from Api, if this current location is equal to or less than 500 meters then only user is able to checkin, Any help would be great

A: Hypothetically you need the distance between 2 geo locations. From the event geolocation to the the one calculated.
An identical thread from stackoverflow : Calculate distance between 2 GPS coordinates


Q: Dynamically load jade templates I'm working on a small documentation website and the content is stored in files. For instance I have two files chapter1.jade and chapter2.jade in a module1/ directory.
I'd like to read the module1/ directory and dynamically include all the chapterX.jade files in it.
I tried to have do directory = fs.readDirSync('module1/') and then in my view:
each item in directory
  include item

But jade include doesn't support dynamic values (even `include #{item}) doesn't work. Do you have any idea how I could implement this ?
EDIT: I'd like to generate some code under the each loop (anchor for easy linking) so the solution would preferabily be in the view. I could obviously manually add the anchor in the included files but it is not ideal.
Thanks

A: Here is the short version of what I've done to make it work. It uses the jade Public API.
var directory = __dirname+'/views/bla/'
  , files
  , renderedHTML = '';

if( !fs.existsSync(directory) ) {
  // directory doesn't exist, in my case I want a 404
  return res.status(404).send('404 Not found');
}

// get files in the directory
files = fs.readdirSync(directory);

files.forEach(function(file) {
  var template = jade.compile(fs.readFileSync(directory+file, 'utf8'));

  // some templating
  renderedHTML += '
 '+template()+'
';
});

// render the actual view and pass it the pre rendered views
res.render('view', {
  title: 'View',
  files: files,
  html: renderedHTML
})

And the view just renders the html variable unescaped:
div(class="component-doc-wrap")
  !{html}

A: As @user1737909 say, that's not possible using just jade.
The best way to do this (tho) is building a little Express Dynamic (view) Helpers
DEPECATED IN EXPRESS 3.XX
Check these:  Jade - way to add dynamic includes

A: in addition to kalemas answer you can also write your includes to a file which is included in jade.
in this example I write my includes to include_all.jade. This file is included in a jade file.
If it does not work, check the path ;-)
e.g.
in your app.js
var includes = "path/to/include1\n";
includes += "path/to/include2";
...
incPath = "path/to/include_all.jade";

fs.open(incPath,'w',function(err,fd){
if(err){
    throw 'error open file: ' + incPath +" "+ err;
}

var buffer = new Buffer(includes);
 fs.write(fd,buffer,0,buffer.length,null,function(err){
    if (err)
        throw 'error writing file: ' +err;
    fs.close(fd,function(){
        console.log('file written ' + incPath);
    });
 });
});

in your jade file
include path/to/include_all.jade


Q: WordPress : Form data is not displaying via echo I have created a form to which I am passing the data. When I try to echo the data it shows couple of errors saying that index is undefined.
<?php /* Template Name: Dummy Practice Page*/?>

    <form method='post' enctype='multipart/form-data'>
                <input id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

                <input id="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

                <input id="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

                <input id="pic" type="file" style="height:30px; width: 350px; ">

                <input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;    " name='Submit' value='Add Member' />

            </form>

<?php
if(isset($_POST['insert']))
{
    echo $namevar = isset($_POST['name']);
    echo $descriptionvar = isset($_POST['description']);
    echo $designationvar = isset($_POST['designation']);
}
?>

Following are the errors:

Notice: Undefined index: name in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
  Notice: Undefined index: description in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
  Notice: Undefined index: designation in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php

A: The issue is with the names of input fields.
In PHP or any other programming language, You should use the input name="something" to get the input values.
You should give the name for each input fields.
For example,
<input name = "name" id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

A:     <form method='post' enctype='multipart/form-data'>
                <input name="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

                <input name="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

                <input name="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

                <input id="pic" type="file" style="height:30px; width: 350px; ">

                <input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;" value='Add Member' />

    </form>
<?php
if(isset($_POST['insert']))
{
    echo $namevar = $_POST['name'];
    echo $descriptionvar = $_POST['description'];
    echo $designationvar = $_POST['designation'];
}
?>

A: You cannot pass POST data to another page vie using ID.
You should give name to <input>
<input name="name">
<input name="description">
<input name="designation">

Edit
You are defining variables and echoing them same time
Change your code to:
<?php
if(isset($_POST["insert"])){
  echo $_POST["name"];
  echo $_POST["description"];
  echo $_POST["designation"];
}?>


Q: PyMySQL different updates in one query? So I have a python script that goes through roughly 350,000 data objects, and depending on some tests, it needs to update a row which represents each one of those objects in a MySQl db. I'm also using pymysql as I've had the least trouble with it especially when sending over large select queries (select statements with where column IN (....) clause that can contain 100,000+ values).
Since each update for each row can be different, each update statement is different. For example, for one row we might want to update first_name but for another row we want to leave first_name untouched and we want to update last_name.
This is why I don't want to use the cursor.executemany() method which takes in one generic update statement and you then feed it the values however as I mentioned, each update is different so having one generic update statement doesn't really work for my case. I also don't want to send over 350,000 update statements individually over the wire. Is there anyway I can package all of my update statements together and send them at once?
I tried having them all in one query and using the cursor.execute() method but it doesn't seem to update all the rows.

A: Your best performance will be if you can encode your "tests" into the SQL logic itself, so you can boil everything down to a handful of UPDATE statements.  Or at least get as many as possible done that way, so that fewer rows need to be updated individually.
For example:
UPDATE tablename set firstname = [some logic]
WHERE [logic that identifies which rows need the firstname updated];

You don't describe much about your tests, so it's hard to be sure.  But you can typically get quite a lot of logic into your WHERE clause with a little bit of work.
Another option would be to put your logic into a stored procedure.  You'll still be doing 350,000 updates, but at least they aren't all "going over the wire".  I would use this only as a last resort, though; business logic should be kept in the application layer whenever possible, and stored procedures make your application less portable.

A: SQL #1: CREATE TABLE t with whatever columns you might need to change.  Make all of them NULL (as opposed to NOT NULL).
SQL #2:  Do a bulk INSERT (or LOAD DATA) of all the changes needed.  Eg, if changing only first_name, fill in id and first_name, but have the other columns NULL.
SQL #3-14:
UPDATE real_table
  JOIN t  ON t.id = real_table.id
  SET real_table.first_name = t.first_name
  WHERE t.first_name IS NOT NULL;
# ditto for each other column.

All SQLs except #1 will be time-consuming.  And, since UPDATE needs to build a undo log, it could timeout or otherwise be problematical.  See a discussion of chunking if necessary.
If necessary, use functions such as COALESCE(), GREATEST(), IFNULL(), etc.
Mass UPDATEs usually imply poor schema design.
(If Ryan jumps in with an 'Answer' instead of just a 'Comment', he should probably get the 'bounty'.)


Q: Is it possible to apply dbt seed configurations to all projects that use a given package? I built a dbt package for internal use. I'd like to specify the seed configurations in the dbt_project.yml of that package, and have those configurations apply to all projects that use the package. So far, I'm not sure if there's an issue with my syntax or if this just isn't possible.
The package dbt_project.yml includes the following:
seeds:
  seed_name:
    +quote_columns: false
    +column_types:
          column_name: varchar(127)

In a project that uses this package, there is a file data/seed_name.csv. When I run dbt seed for that project, I want the configuration defined in the package to apply to this seed. Instead, it seems to be ignored. To be clear, the .csv is included in the project that uses the package, not in the package itself.
It works if I move the above code out of the package and into the project-specific dbt_project.yml. However, this would mean that anyone using my package needs to copy that code into their file, which I'd prefer to avoid.


Q: My app runs perfectly while running it on eclipse but maps disapear and it crashes on some actvitys after export Hw can this happen and be solved?
My app runs perfectly while on eclipse, I tried everything before exporting the app.
When I exported the app, the maps showed a grey area and the app crashed while loading one activity.
Running on eclipse none of this happens.
Is this because of the prograd configuration?
How can I debug an exported app?

A: To resolve the Maps grey area issue do the following:

*

*Open Google Developers Console

*Select the project you are working on (or create it if it doesn't exist)

*Select APIs & Auth

*Then Credentials

*Find the section with the title "Key for Android applications"

*Click Edit allowed Android applications

*Execute the keytool command to generate the SHA1 fingerprint for your release keystore file

*Then add the SHA1 and package name to the list of allowed Android applications

And for the crashes, try using crash reporting tool (Crashlytics for example)


Q: Can some one explain me Planck/Reileigh Jean Law? I wonder why every proof of these laws consider the number of of oscillator in the end but disregard it while deriving the mean energy. Let me explain. Considering an oscillator in a heat bath, there are six variables in phase space, $x$, $y$, $z$, $p_x$, $p_y$ and $p_z$. Integrating the probability density over a 6-D ellipse we have that the probability of finding the oscillator with energy $$E<\frac{p_x^2}{2 m}+\frac{p_y^2}{2 m}+\frac{p_z^2}{2 m}+\frac{k x^2}{2}+\frac{k y^2}{2}+\frac{k x^2}{2}.$$
The partition function is $$z=\int \exp\left[-\beta \left(\frac{p_i^2}{2m}+\frac{k x_i^2}{2}\right)\right]dx_i^3 dp_i^3 = \left(\sqrt{\frac{2m \pi}{\beta}}\sqrt{\frac{2 \pi}{\beta k}}\right)^3 .$$
The probability is $$P(E<E_0) = \frac{1}{z} \int_{E<E_0}   e^{-\beta E_0} dx_i^3 dp_i^3.$$
Setting $r_1 = \sqrt{\frac{k}{2}}x$, $r_2=\sqrt{\frac{k}{2}}y$, $r_3=\sqrt{\frac{k}{2}}z$, $r_4 =\frac{p_x}{\sqrt{2 m}}$,$r_5 =\frac{p_y}{\sqrt{2 m}}$ ,$r_6 =\frac{p_z}{\sqrt{2 m}}$, and $ r = \sqrt{r_1^2+r_2^2+r_3^2+r_4^2+r_5^2+r_6^2}$ we have
\begin{align}
P(E<E_0) & = \frac{1}{z} \int_{r^2<E_0}   e^{-\beta r^2} (\sqrt{2 m}\sqrt{\frac{2 }{ k}})^3dr_i^6 \\
&= \frac{\beta^3}{\pi^3} \int_{r^2<E_0} e^{-\beta r^2} dr_i^6\\
&= \beta^3 \int_0^{\sqrt E_0} e^{-\beta \rho^2} \rho^5 d\rho
\end{align}
Making the substitution $E = \rho^2 $:
$$P(E<E_0)= \beta^3 \int_0^{E_0} \frac{1}{2} E^2 e^{-\beta E } dE$$
In all proofs I've read the factor $E^2$ simply disappears, but it precisely counts the number of oscillators with a given energy. If calculate the expected value, we have $$\beta^3 \int_0^{\infty} \frac{1}{2} E^3 e^{-\beta E } dE = \frac{3}{\beta}.$$
That's there times the temperature, for $\beta = \frac{1}{k_B T}$, because of the three dimensions. If someone could explain me why my reasoning is wrong I'll be very grateful.


Q: Using data (not METAdata) from a SSMS DB to drive biml in SSIS dtsx creation I need to be able to generate tasks in a data flow of a SSIS dtsx based on data stored in a SSMS DB table.
Basically, I have N (unknown, variable) sources and M (unknown, variable) destinations and I have a table T0 with MxN rows. Each row, using a bit B, specifies if I really need to send data from that specific source to that specific destination.
T0 is stored in a basic Database DB0 that is used for configuration.
Ideally, using BIML I want to script a dtsx that has a simple data flow (OLEDB Source -> OLEDB destination) FOR EACH row of T0 with B = 1.
This dtsx generation must be driven by the data i find in T0.
Online I can find how to read METADATA from a DB but I can't find anyone talking about the much basic "reading data from a DB" and using these data in the BIML.
Do I need to handle the DB connection in the C# code in BIMLScript? How do I use/address the connection to DB0 in the c# code? (usually I would have this connection in a config file... in this case I need to refer to the connMgr from the C# script).


Q: Unable to create table in Oracle I want to create a table in Oracle using the below syntax using %type
Create table emp_avg
(
emp_id HR.employees.emp_id%type,
dept_id HR.employees.dep_id%type
):

When I tried executing it is throwing an error.

A: The given code is not valid. Try the below code.
Create table emp_avg as
Select e.employee_id, e.department_id from HR.employees e where 1=0;

A: That's not valid syntax.  The point of an anchored type declaration (the %type syntax) in PL/SQL is that when the underlying data type changes, the PL/SQL code uses the new type automatically.  But that doesn't work when you're defining a table where Oracle has to know the actual data type when it writes a data block to disk and can't just dynamically recompile the table when the parent data type changes.  When you create a table, you have to specify actual data types.


Q: SQLSRV to Excel using php - Missing zero's in data cells I am using SQLSRV to download the data from server to excel based on requirement
When i display the data its fine, but when i try to download using
header("Content-type: application/vnd-ms-excel") the leading zero in the integer are missing.
For example '0012346' gets converted into '12346'.
In my results file i need leading zeros also like  - '0012346'.
How can i achieve it?


Q: Partial Fractions with a Repeated and a Irreducible Quadratic factor I am trying to make this into a partial fractions form but i can't seem to find a way to do it.
The question is here:
Change into a partial fractions form.
\begin{align}
 \frac{2s}{(s+1)^2(s^2 + 1)} \\\\
\end{align}
i change to
\begin{align}
\frac{A}{(s+1)}+\frac{B}{(s+1)^2}+\frac{Cs+D}{(s^2+1)}
\end{align}
I expand it and group like terms tgt but i am stump at this point
\begin{align}
2s = (A+C)s^3 + (B+A+2C+D)s^2 + (A+C+2D)s + (B+A+D)
\end{align}
Anyone can help?

A: Such partial fraction decomposition is very easy using the Heaviside cover up method. As I show in that answer, the method  generalizes to quadratic denominators. Let's apply it to your problem.
$$\dfrac{a}{x+1} + \dfrac{\color{#c00}b}{(x+1)^2} + \dfrac{cx+d}{x^2+1}\, =\, \dfrac{2x}{(x+1)^2(x^2+1)}\tag{E}$$
Scaling $\rm\,(E)\,$  by $\,(x+1)^2,\,$  then evaluating at its root $\,x = -1\,$ yields
$$\  \ \ \ \color{#c00}b\, =\, \dfrac{2x}{x^2+1}\:\!\Bigg|_{\:\!\large  x\,=\,-1} =\, \color{#c00}{ -1}$$
Subtracting out this known summand leaves a fraction in partial form, so we are done:
$$\require{cancel}\!\!\!  \dfrac{\color{#0a0}{2x}}{(x+1)^2(x^2+1)}\, -\, \dfrac{\!\!\!\!\!\color{#c00}{-1}}{(x+1)^2}\: =\: \dfrac{\cancel{\color{#0a0}{2x}+x^2+1}}{\cancel{(x+1)^2}(x^2+1)}\, =\, \dfrac{1}{x^2+1}\quad  {\bf\small  QED}$$

Remark $ $ It's unneeded - but instructive - to use this quadratic Heaviside method for all terms:
Scaling $\rm\,(E)\,$  by $\,x^2+1\,$ then evaluating at its root $\,x = i\,$ yields
$$ \color{#0a0}c\, i + \color{#c00}d\, =\,  \dfrac{2i}{(i\!+\!1)^2} \, =\, \dfrac{2i}{2i} \,=\, \color{#c00}1\ \Rightarrow\ \color{#0a0}{c = 0},\ \color{#c00}{d = 1} $$
Scaling  $\rm\,(E)\,$  by $\,(x\!+\!1)^2\,$ then evaluating at its root $\,x = w,\,$  so $\,\color{#c0d}{w^2\!+\!1 = -2w}$
$$a(w+1)+ b\,  =\, \dfrac{2w}{\color{#c0d}{w^2\!+\!1}}\,=\,\dfrac{\ \ \,2w}{\color{#c0d}{-2w}} \,=\, -1\,\Rightarrow\ a=0,\ b=-1 $$

Below are some further examples asked about in comments.
$$ \dfrac{f}{(x+1)^2} + \dfrac{cx+d}{x^2+1}\, =\, \dfrac{2x+1}{(x+1)^2(x^2+1)}\tag{$\rm \dot E$}$$
Scaling $\rm\,(\dot E)\,$  by $\,(x\!+\!1)^2\,$ then evaluating at its root $\,x = w,\,$
$$f\,  =\, \dfrac{\color{#0a0}{2w+1}}{\color{#c0d}{w^2\!+\!1}}\,=\,\dfrac{\color{#0a0}{-w^2}}{\color{#c0d}{-2w}} \,=\,  \dfrac{w}2 $$
by $\,w^2\!+2w\!+\!1=0\ \Rightarrow\ \color{#0a0}{2w\!+\!1=-w^2},\,\ \color{#c0d}{w^2\!+\!1 = -2w}$

$$ \dfrac{f}{(x-2)^2} + \dfrac{c}{x-1}\, =\, \dfrac{x}{(x-2)^2(x-1)}\tag{$\rm \ddot E$}$$
Scaling $\rm\,(\ddot E)\,$  by $\,(x\!-\!2)^2\,$ then evaluating at its root $\,x = w,\,$
$$f\,  =\, \dfrac{w}{\color{c0d}{w\!-\!1}}\,=\,1+\color{#c00}{\dfrac{1}{w\!-\!1}} = 4\!-\!w $$
$\!\underbrace{{\rm since\ we've }\,\ 0=(w\!-\!2)^2\! = (w\!-\!3)(w\!-\!1) + 1}_{\textstyle \text{polynomial}\ \color{darkorange}{\rm divide}\,\ (w\!-\!2)^2 \:\! \ {\rm by}\ \ (w\!-\!1)\qquad\ \ \ }\,\Rightarrow\, \color{#c00}{\dfrac{1}{w\!-\!1}= 3\!-\!w}$
OR $\bmod w\!-\!1\!:\ (w\!-\!2)^2 \equiv 1^2\,$ so $\,w\!-\!1\mid (w\!-\!2)^2\!\color{#c00}{-\!1^2} = \color{#c00}{(w\!-\!3)(w\!-\!1)}$

Generally given coprime polynomials $\,p,q\,$ over a field $K$ (e.g. $\Bbb Q, \Bbb R, \Bbb C),\,$  we can use the Euclidean algorithm to compute partial fraction decompositions as follows
$$\begin{align} \dfrac{f}p + \dfrac{g}q \,&=\, \dfrac{h}{pq}\\[.4em]
\iff\ q\:\!f + p\:\!g\, &=\, h\end{align}\qquad$$
We can solve the latter equation for $\,f,g\,$ using the same methods that we do for integers - by the extended) Euclidean algorithm and closely related methods, e.g. evaluating it mod $p\,$ we deduce $\,qf\equiv h\iff f\equiv h/q\,\pmod{\!p},\,$ which is exactly the same as the Heaviside method above.  When $\,q\,$ is linear we can compute $\,1/q\bmod p\,$ simply by (long hand) polynomial $\color{darkorange}{\text{dividing}}$ $\,p\,$ by $\,q\,$ (as we did in the final example above), which amounts to optimizing the case when the extended Euclidean algorithm terminates in a single step.
Similar ideas were employed by Hermite in general partial fraction decomposition algorithms used for integrating rational functions, e.g. see here.

A: Since you arrived to $$\begin{align}
2s = (A+C)s^3 + (B+A+2C+D)s^2 + (A+C+2D)s + (B+A+D)
\end{align}$$ identification of the coefficients of the different powers of $s$ gives $$A+C=0$$ $$B+A+2C+D=0$$ $$A+C+2D=2$$ $$B+A+D=0$$  for which the solutions are easily obtained either using matrix or elimination and the final result is : $A=0$,$B=-1$,$C=0$ and $D=1$

A: Hint: It is probably easiest to observe that
$$
2s=(s+1)^2-(s^2+1).
$$
Use that in the numerator and see what you can cancel from the two terms you get.

A: HINT:
Using Partial Fraction Decomposition formula,
$$\frac{2s}{(s+1)^2(s^2+1)}=\frac A{s+1}+\frac B{(s+1)^2}+\frac{Cs+D}{s^2+1}$$