text:
Q: Box2d Libgdx how to make a realistic Car turn I am having a rectangle which should represent a car. It should rotate when you tuch the display. How to make this with box2d. I already setted all up: Press W to accelerate and touch display for right turn and dont touch it for left turn. Problem is that the car is drifting when you rotate it and not immediately goes only to the direction its facing to. So far this is my code, how to remove this drifting, its like it drives on ice. :/
EDIT: (copied from C++ code: http://www.iforce2d.net/b2dtut/top-down-car I tried to copy everything until the Torque so now It should drive. But when I do accelerate. It does not move. The currentSpeed Variable is 0 and the currentForwardNormal is 0.0 ,0.0. What did I wrong?)
//Main upate
public void update(float delta) {
    updateFriction();
}

//Movements and Subclasses of them
public void accelerate() {
    //find current speed in forward direction
    Vector2 currentForwardNormal = ship.getWorldVector(new Vector2(0,1));
    float currentSpeed = getForwardVelocity().dot(currentForwardNormal);

    //apply necessary force
    float force = 0;
    if(maxSpeed > currentSpeed) {
        force = maxDriveForce;
    } else {
        force = -maxDriveForce;
    }
    System.out.println("Current Speed: "+currentSpeed);
    System.out.println("Current Forward Normal: "+currentForwardNormal);
    ship.applyForceToCenter(currentForwardNormal.scl(force),true);
}

public void rotate(boolean direction) { //true for Up and false for Down
    if(direction) {
        //torques
    }
}

private void updateFriction() {
    Vector2 impulse = getLateralVelocity().scl(-ship.getMass());
    ship.applyLinearImpulse(impulse, ship.getWorldCenter(), true);
    ship.applyAngularImpulse(0.1f * ship.getInertia() * -ship.getAngularVelocity(),true);
}

private Vector2 getLateralVelocity() {
    Vector2 currentRightNormal = ship.getWorldVector(new Vector2(1,0));
    return currentRightNormal.scl(currentRightNormal.dot(ship.getLinearVelocity()));
}

private Vector2 getForwardVelocity() {
    Vector2 currentRightNormal = ship.getWorldVector(new Vector2(0,1));
    return currentRightNormal.scl(currentRightNormal.dot(ship.getLinearVelocity()));
}


text:
Q: Playing background video I am trying to play a background video but i am having a problem with one line of code. I get an error that says "Cannot invoke initializer for type 'URL' with no arrangements" At this line "open var contentURL: URL = URL()"
open class VideoSplashViewController: UIViewController {

  fileprivate let moviePlayer = AVPlayerViewController()
  fileprivate var moviePlayerSoundLevel: Float = 1.0
  open var contentURL: URL = URL() {
    didSet {
      setMoviePlayer(contentURL)
    }
  }

  open var videoFrame: CGRect = CGRect()
  open var startTime: CGFloat = 0.0
  open var duration: CGFloat = 0.0
  open var backgroundColor: UIColor = UIColor.black {
    didSet {
     view.backgroundColor = backgroundColor
   }
 }

I don't know how to fix this, please help

A: The error message is self-explanatory, URL class doesn't have an initializer with no arguments :)
If you take a look at URL class -Hold down CMD key and click on URL-, you will notice that there is no initializer like this:
init() {}

Therefore you can't just write URL() because that requires the above initializer. However, there is a variety of other initializers in URL class such as:
init?(string: String) {}
init(fileURLWithPath path: String)
...

You can use any of them to initialize the contentURL instance.
open var contentURL: URL = URL(string: "") {/**/}
open var contentURL: URL = URL(fileURLWithPath: "") {/**/}

What is Initializer?

A: You should replace the following code
open var contentURL: URL = URL() {
didSet {
  setMoviePlayer(contentURL)
}}

with this:
 public var contentURL: NSURL = NSURL() {
didSet {
  setMoviePlayer(contentURL)
}}

This will fix your problems.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Have Multiple Selected Elements in a Cell Dropdown I would like to select items from a pre-created list of possibilities. This is why I use a data-validation dropdown. But I would like to select more than one dropdown element.
How can I implement in google sheets, or excel, a drop-down similar to the one below from an angular demo site?


text:
Q: Analogy of a Fano manifold with anticanonical divisor Some people say that a Fano manifold with anticanonical divisor is an analogue of a manifold with boundary. Where does this intuition come from?

A: I'd say it's closer to an oriented manifold with corners (corners happening where the divisor is singular), or even that times a coefficient. In these papers Khesin, Rosly, and later Thomas build a homology theory based on this analogy.


text:
Q: Passing PChar / *char between C++ and Delphi DLL I have a C++ program, that calls Delphi DLL to initialize a buffer that contains chars.
I am testing out the interface to make sure the data are passed correctly:
In C++ program:
char * pMsg = (char*)malloc(3); //allocate buffer

Init(pMsg * char); //Delphi DLL function

In Delphi DLL:
procedure Init(pMsg:PChar);
var
  pHardcodedMsg:PChar;
begin
  pHardcodedMsg:= '123';
  CopyMemory(pMsg, pHardcodedMsg, Length(pHardcodedMsg));
end;

But, when I try to printf( (const char*)pMsg ) in C++,
It shows me "123" followed by some rubbish characters.
Why is this so?
How can I successfully place an array of char into the buffer and have the string printed out correctly?

A: Delphi does not use NULL-terminated strings so you need to slap a 0 at the end, as C/C++ uses that to determine where the string data ends (Pascal uses the size of the string at the beginning IIRC).
The usual character is '\0' - escape value 0.
Don't forget to return 4 characters, not 3.

A: Your Init function doesn't work because
1) pHardcodedMsg is a pointer for which you didn't allocate memory
2) CopyMemory doesn't add a 0 to the end of pMsg
3) the procedure header of Init misses a semi colon at the end of the line
When you are using a unicode version of Delphi you will also have to consider string length and character set conversion


text:
Q: Вопрос по настройке SDK Android Вопрос заключается в следующем. На данный момент максимально-доступная версия платформы 6.0. У меня не телефоне 4.4.2. Это значит,что мне нужно устанавливать sdk для 4 версии, или я могу поставить и разработать приложение на 6-й и оно запустится на моем телефоне? Если первый вариант, тогда sdk какой версии будет универсальнее?

A: Есть minSdkVersion и targetSdkVersion. targetSdkVersion желательно должна быть последней из доступных, а вот minSdkVersion Вы задаете начиная с какой версии Ваша программа будет работать (ну и использовать необходимо, соответственно, методы и пр. доступные начиная с этой версии).
Если будет minSdkVersion 14, то будет работать на всех устройствах, начиная с Android 4.0. Если minSdkVersion 19, то с Android 5.0 и т.п.
Благодаря наличию Support библиотек, Вы можете значительно понижать minSdkVersion, практически ничего не теряя, но если Вы хотите разрабатывать только под новые устройства, используя последние API, тогда на старых версиях, само собой, программа не будет работать.

A: Если хотите тестировать на своем телефоне, то minSdkVersion должна быть <= 19. Иначе не получится запустить программу на телефоне. targetSdkVersion может быть вплоть до самой последней, но >= minSdkVersion. Обычно и выбирают последнюю версию SDK. Если будете публиковать ваше приложение, то желательно тестировать его на телефонах, планшетах разных версий SDK и разрешений экранов. Без эмулятора не обойтись.
Чем меньшее значение в качестве minSdkVersion выберете, тем большую долю существующих в мире устройств охватите (см. Dashboards). Но тем сложнее будет и разработка (больше ограничений, необходимость учесть разные варианты) и тестирование. Нужен компромисс.
Оба параметра (minSdkVersion, targetSdkVersion) выставляются в файле build.gradle(Module:app). Можно найти этот файл быстро, если смотреть проект в режиме Android в AndroidStudio (В разделе Gradle Scripts). После его исправления нужно выполнить синхронизацию проекта с Gradle файлами (Sync project with Gradle Files) -  на панели иконка- зеленый кружок и голубая стрелочка вниз.

A: В среде разработки (например Android Studio) имеет смысл устанавливать последнюю стабильную версию SDK (на сегодняшний день - API 23 Android 6.0) - это позволит разрабатывать приложение с максимальным количеством поддерживаемых устройств и использовать возможности новых API для поддерживающих их устройств. То же самое относится и к пакетам SDK Tools, SDK Build Tools, SDK Platform Tools. Также должны быть установлены SDK, для которых будут созданы виртуальные устройства для тестирования. Прочие версии SDK, в том числе и реальных тестирующих устройств, устанавливать нет никакой необходимости - реальное устройство имеет все необходимое SDK в себе самом.
SDK устанавливается с помощью утилиты SDK Manager (Tools -> Android -> SDK Manager в Android Studio).
Разрабатываемое приложение при этом может быть запущено на любом устройстве, API которого выше, чем установленное в настройках проекта minSdkVersion, верхнее ограничение, как правило, не указывается. Указав данный параметр, вы будете иногда получать предупреждения от IDE о том, что пытаетесь использовать классы или методы, которые не совместимы с указанным минимальным API. Это значит, что данный класс (метод) был добавлен в SDK позднее, чем указанное вами ограничение и на некоторых устройствах из указанных в число поддерживаемых приложение работать не будет. Библиотеки поддержки Google существенно расширяют возможности по использованию новых классов на устройствах, где имеющийся у них API не позволяет их использовать. При этом вместо классов SDK используются классы из support-библиотек.
Для того, чтобы указать, с каким минимальным API может работать ваше приложение (на какой минимальной версии Android оно может быть запущено), нужно указать это в конфигах вашего проекта одним из способов:

*

*Соответствующий параметр в файле AndroidManifest.xml.

Пример указания в манифесте:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.application" />
    <uses-sdk
      android:minSdkVersion="15"
      android:compileSdkVersion="23" />
<!-- остальное содержимое-->
</manifest>

*В секции defaultConfig конфигурационного файла build.gradle модуля проекта.

Пример в файле build.gradle :
android {
    compileSdkVersion 23
    buildToolsVersion '23.0.3'
defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 23
    }

C переходом на систему сборки Gradle рекомендуется использовать второй вариант. Данные настройки в проекте означают, что приложение может быть запущенно на любом устройстве с Android 4.0 (API15) или новее.
Настроить эти параметры можно как непосредственным редактированием конфигурационных файлов, так и в окне Project Structure через графический интерфейс:

PS: compileSdkVersion (указывает с помощью какого SDK собирать проект) должна быть последней версии API, иначе новые библиотеки поддержки не будут работать (мажорный номер библиотеки поддержки и compileSdkVersion должны соответствовать).
targetSdkVersion указывает основное целевое устройство (предпочтительный для приложения SDK). Второстепенный параметр, но традиционно указывается равным compileSdkVersion


text:
Q: How to defined component /binding when using React ref in Reasonml? I am having issues integrating react-system-notification module in my app, having read the documentation about Reason React Ref I am not sure why the reference is not passed down the stack; a hint would be much appreciated.
I keep getting the error below, I have used this component in the past in React but it seems that there is some issue when used in ReasonML/React. I suspect a null reference is passed down which breaks the component.

Element type is invalid: expected a string (for built-in components)
  or a class/function (for composite components) but got: undefined. You
  likely forgot to export your component from the file it's defined in,
  or you might have mixed up default and named imports.
Check the render method of Notifications.

Binding:
module NotificationSystem = {
    [@bs.module "react-notification-system"] external reactClass : ReasonReact.reactClass = "default";

    let make = ( children ) =>
    ReasonReact.wrapJsForReason(
        ~reactClass,
        ~props=Js.Obj.empty(),
        children
    )
};

Component
type action =
  | AddNotification(string);

type state = {
    _notificationSystem: ref(option(ReasonReact.reactRef)),
};

let setNotificationSystemRef = (notificationRef, {ReasonReact.state: state}) =>
  state._notificationSystem := Js.toOption(notificationRef) ;

let component = ReasonReact.reducerComponent("Notifications");

let addNotification = (message, state) => {
    switch state._notificationSystem^ {
    | None => ()
    | Some(r) => ReasonReact.refToJsObj(r)##addNotification({"message": message, "level": "success"});
    }
};

let make = (_children) => {
    ...component,
    initialState: () => {_notificationSystem: ref(None) },
    reducer: (action, state) =>
        switch action {
            | AddNotification(message) =>  ReasonReact.SideEffects(((_) => addNotification(message, state)))
        },
    render: ({handle, reduce}) => (
        <div>
            <NotificationSystem ref=(handle(setNotificationSystemRef)) />
            <button onClick=(reduce( (_) => AddNotification("Test Notification Test"))) > (ReasonReact.stringToElement("Click")) </button>
        </div>
    )
};

A: My guess would be that react-notification-system is not distributed as an es6 component, and therefore does not export default. Try removing default from the external:
[@bs.module "react-notification-system"] external reactClass : ReasonReact.reactClass = "";

You should always start by trying out the simplest implementation first, then build incrementally from there, to minimize possible causes of errors. Especially when dealing with something as error-prone as the js boundary. In this case that would be without the complex ref handling. You'll likely find that it still does not work, because of the above, and that you've been looking in the wrong place because you bit off more than you can chew.

A: After some further investigation, thanks to glensl hint and some messages exchanged on Discord I am posting the complete answer.
The issue was related to way bsb generated the "require" statement in the javascript output:
[@bs.module "react-notification-system"] external reactClass : ReasonReact.reactClass = "default";

Was being emitted as:
var ReactNotificationSystem = require("react-notification-system");

instead of
var NotificationSystem = require("react-notification-system");

Mightseem a little hacky however I got bsb to emit the correct javascript was using the following statement:
[@bs.module ] external reactClass : ReasonReact.reactClass = "react-notification-system/dist/NotificationSystem";

Then with some minor tweaking to the wrapper component, I was able to get it working with the following code:
module ReactNotificationSystem = {
    [@bs.module ] external reactClass : ReasonReact.reactClass = "react-notification-system/dist/NotificationSystem";
let make = ( children ) =>
ReasonReact.wrapJsForReason(
    ~reactClass,
    ~props=Js.Obj.empty(),
    children
)
};

type action =
  | AddNotification(string);

type state = {
    _notificationSystem: ref(option(ReasonReact.reactRef)),
};

let setNotificationSystemRef = (notificationRef, {ReasonReact.state}) =>
  state._notificationSystem := Js.Nullable.to_opt(notificationRef) ;

let component = ReasonReact.reducerComponent("Notifications");

let addNotification = (message, state) => {
    switch state._notificationSystem^ {
    | None => ()
    | Some(r) => ReasonReact.refToJsObj(r)##addNotification({"message": message, "level": "success"});
    }
};

let make = (_children) => {
    ...component,
    initialState: () => {_notificationSystem: ref(None) },
    reducer: (action, state) =>
        switch action {
            | AddNotification(message) =>  ReasonReact.SideEffects(((_) => addNotification(message, state)))
        },
    render: ({handle, reduce}) => (
    <div>
        <ReactNotificationSystem ref=(handle(setNotificationSystemRef)) />
        <button onClick=(reduce( (_) => AddNotification("Hello"))) > (ReasonReact.stringToElement("Click")) </button>
    </div>
  )
};

A full sample working project can be found on Github here:


text:
Q: Cache Manifest messes up my app when online Gurus of SO
I am trying to play with CACHE MANIFEST/HTML5. My app is JS heavy and built on jquery/jquerymobile.
This is an excerpt of what my Manifest looks like
CACHE MANIFEST
FALLBACK:
/
NETWORK:
*
CACHE:
/css/style.css
/js/jquery.js

But somehow, the app doesn't load the files the first time itself and the entire app breaks down.

*

*Is my format wrong?

*Should I never load JS into the Cache?

*How should I treat this differently to always check the network first if anything isn't available and only load stuff available from the Cache?

Thank you.

A: I tried a simple page with your cache manifest and it worked fine for me, so I'm not really sure what the problem is. But,

*

*Yes, there is something wrong with the format. The entries in the FALLBACK section need to have two parts: a pattern, and a URL. This says "if any page matching the pattern is not available offline, display the URL instead (which will be cached)." The main example of this (as shown here) is "/ /offline.html", which means "for all pages, if we are offline and they are not cached, display /offline.html instead." However, I don't think this is the source of your problem since I tested it with your exact manifest and it still worked.

*There is nothing special about JS files. It should be fine to load them into the cache.

*I don't understand the third question. There are possibly two goals here: a) how do you check to see if there is a newer version of the file available online first, before going back to the cache, and b) how do you check the network to see if there is a file that is not cached, and if we are offline, fall back to an error page. The answer to (a) is that once you have turned on the cache manifest, things work very differently. It will never check for new versions of the files unless there is a new version of the manifest also. So you must always update the manifest whenever you change any files. The answer to (b) is the FALLBACK section.

See Dive Into HTML5's excellent chapter on this, particularly the section "The fine art of debugging, a.k.a. "Kill me! Kill me now!"" which explains how the manifest updates.
Also I don't think we've gotten to the meat of your question, because it's unclear what you mean by "the app doesn't load the files the first time itself". Which files don't load? Do they load properly after a refresh? Etc.

A: The only way I got this to work to refresh a cache was to rename the manifest file with a commit number or timestamp, and change the cache declaration to
<html manifest='mymanifest382330.manifest'>
I made this part of my build.


text:
Q: Elasticsearch java API bulk delete not working I'm attempting perform a bulk delete of documents whose id's are derived from a previous search.  The query to determine the documents that are candidates for deletion is producing desired results (thousands of records) however the bulk delete only deletes 10 records at a time, even though I'm feeding it all of the results of the original query;
Client client = node.client();
BulkRequestBuilder bulkRequest = client.prepareBulk();

SearchResponse deletes = client.prepareSearch("my_index")
        .setTypes("my_doc_type")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(boolQuery().mustNot(termQuery("tId", transactionId)))
        .execute()
        .actionGet();

long deleteHits = deletes.getHits().getTotalHits();

if (deleteHits > 0) {

    logger.info("Preparing to delete (" + deleteHits + ") " +
            "documents from index");

    Arrays.asList(deletes.getHits().getHits()).stream().forEach(h ->
            bulkRequest.add(client.prepareDelete()
                .setIndex("my_index")
                .setType("my_doc_type")
                .setId(h.getId())));
    }

    BulkResponse bulkResponse = bulkRequest.execute().actionGet();

    if (bulkResponse.hasFailures()) {
        throw new RuntimeException(bulkResponse.buildFailureMessage());
    }

}

A: By default, the search response returns only top 10 results. So, while deletes .getHits().getTotalHits() can be in thousands or even in millions, the size of deletes.getHits().getHits() will never be more than you specified in the size parameter of your request, which 10 by default.
A naive approach would be to try paginating throw the results using normal search by changing the from parameter. However, this can lead to missing to delete some records since each command will execute a new search and the result of the next search can get shifted comparing to the previous search as a result of deleting records on the previous search.
A proper approach is to use specialized scan and scroll search to paginate throw the records. This type of search will keep the results consistent between calls. An example, of this approach can be found in the delete by query plugin that will be available in v2.0.
I also need to note that while the delete by query functionality exists in the previous versions of elasticsearch and it might seem to be the easiest solution for your problem, I would still recommend to use scan/scroll because of poor performance and fragility of existing delete by query API implementation in pre-v2.0.

A: deletes.getHits().getTotalHits give you the total number of hits for the search but  SearchResponse deletes do not contains all the results.
You'll need to paginate over it.
you'll need to use something like this to define the paging
client.prepareSearch("my_index").setFrom(int from).setSize(int pageSize);


text:
Q: Implement "add to favorites" I am creating an app where a user can favorite a room. I started with a has_and_belongs_to_many association. But then I just noticed that it is very tricky to implement a remove button with drestroy. So I decided to do it this time with a has_many through association. I have a users who should add rooms to favorite or wishlist. Unfortunately when I click on the favorite button I am getting this error:

What I am missing how can I make this work?
If you need further information just let me know. I have used this as a direction.
Implement "Add to favorites" in Rails 3 & 4
favorite_room.rb
class FavoriteRoom < ApplicationRecord
    belongs_to :room
    belongs_to :user
end

room.rb
belongs_to :user
has_many :favorite_rooms
has_many :favorited_by, through: :favorite_rooms, source: :user

user.rb
 has_many :rooms
 has_many :favorite_rooms
 has_many :favorites, through: :favorite_rooms, source: :room

routes.rb
 resources :rooms do
    put :favorite, on: :member
 end

rooms_controller.rb
before_action :set_room, only: [:show, :favorite]
...
...
def favorite
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @room
      redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@room)
      redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}'

    else
      # Type missing, nothing happens
      redirect_to wishlist_path, notice: 'Nothing happened.'
    end
end

private
def set_room
  @room = Room.find(params[:id])
end

show.html.erb
<% if current_user %>
  <%= link_to "favorite",   favorite_room_path(@room, type: "favorite"), method: :put %>
  <%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>
<% end %>

create_favorite_rooms.rb (migration file)
class CreateFavoriteRooms < ActiveRecord::Migration[5.0]
  def change
    create_table :favorite_rooms do |t|
      t.integer :room_id
      t.integer :user_id

      t.timestamps
    end
  end
end


text:
Q: Como fazer um Seed.rb buscando dados aleatoriamente SQLite no Rails? Como eu já tenho um cadastro de Cidades e estados, que podem ver abaixo, minha dúvida é a seguinte, como posso colocar dentro da função 10.times nas linhas da address_city e address_state um parâmetro para buscar cidades e estados aleatórios? dentro do que foi cadastrado no SQLite pela função BRpopulate.
Ruby 2.2.1
Rails 4.2.1
Este é o meu seed.rb:
require 'faker'

#create natural_person
10.times do
  natural_person = NaturalPerson.new(
     name: Faker::Name.name,
     short_name: Faker::Name.first_name,
     treatment: Faker::Name.prefix,
     profession: Faker::Name.title,
     email: Faker::Internet.email,
     address: Faker::Address.street_name,
     address_number: Faker::Address.building_number,
     address_district: Faker::Address.state,
     address_zipcode: Faker::Address.zip_code,
     birthday: Faker::Date.between(100.years.ago, 18.years.ago),
     phone: Faker::Number.number(10),
     mobile: Faker::Number.number(10),
     commercial_phone: Faker::Number.number(10),
     #city_id: ?
     #state_id: ?
     address_coutry: 'Brasil'
  )
  natural_person.save!
end

    # Polpulation State and City for DB
require 'net/http'
require 'json'

  module BRPopulate
   def self.states
     http = Net::HTTP.new('raw.githubusercontent.com', 443); http.use_ssl = true
     JSON.parse http.get('/celsodantas/br_populate/master/states.json').body
  end

  def self.capital?(city, state)
    city["name"] == state["capital"]
  end

  def self.populate
     states.each do |state|
      state_obj = State.new(:acronym => state["acronym"], :name => state["name"])
      state_obj.save

  state["cities"].each do |city|
    c = City.new
    c.name = city
    c.state = state_obj
    c.capital = capital?(city, state)
    c.save
  end
end
end
end

BRPopulate.populate

Models:
NaturalPerson
State
City

A: No meu caso Resolvi aqui assim:
city_id: City.order("RANDOM()").first.id,
state_id: State.order("RANDOM()").first.id,


text:
Q: Linear Algebra Proof: Invertible matrices, construction of the field on complex numbers Let $x$, $y$ $\in \mathbb{R}$ and let
$Z =
\begin{bmatrix}
    x       & -y \\
    y       &  x
\end{bmatrix}$.
Prove that $Z$ is invertible if and only if $x \neq 0$ and $y \neq 0$.

I believe that this is constructing a field over the field of complex numbers, but I am struggling to do so. Does anyone have any recommendations or way forward?

A: A $2\times2$ matrix is invertible if and only if it's determinant is not 0. This matrix has the determinant $x^2 + y^2$, which is $0$ if and only if both $x$ and $y$ are zero. Therefore it is invertible if and only if $x \neq 0$ or $y \neq 0$.

A: If $x=y=0$, then $Z$ is the null matrix, which is not invertible.
Otherwise, the matrix$\begin{bmatrix}\frac x{x^2+y^2}&\frac y{x^2+y^2}\\\frac {-y}{x^2+y^2}&\frac x{x^2+y^2}\end{bmatrix}$ is the inverse of $Z$.

A: Another perspective:
$$
\mathbf{A}^{-1} =
 \left[ \begin{array}{cr}
 x & -y \\ y & x
 \end{array} \right]^{-1} = \frac{\text{adj}\mathbf{A}}{\det \mathbf{A}}=
\frac{1}{x^{2}+y^{2}}
 \left[ \begin{array}{rr}
 -x & y \\ -y & -x
 \end{array} \right]
$$
When does the inverse not exist? When $x^{2}+y^{2} = 0$.


text:
Q: Unable to access media file belonging to nobody:nobody When I deploy my django project to centos, I am unable to access it through the URL.
The media files uploaded from django admin belong to the user and group nobody:nobody.
When I change the ownership to my user, then it is accessible. How to allow these files to be accessed without specifying chmod explicitly?

A: You can use ACL rights Access Control List.
With this method, you may define the default owners and permissions for the content that will be created in a folder.
On CentOS, you may install it with the following command:
yum install acl

Once installed, the command getfacl will return the acl setup for a specific file:
getfacl /path/to/your/folder
The command setfacl will set up the access.
To setup default permissions:
setfacl -Rm d:u:username:rwx,g:groupname:rwx /path/to/your/folder

The content created in this folder will inherit the default ACL.

A: Run ls -la that will show you owner of file. Run this command in order to reach from outside.
chown admin


text:
Q: Memory leak and errors after fixing memory leak Can you tell me why I have bunch of errors after editing memory leaks?? I wanted to fix memory leaks which i did. All memory is free....But suddenly i got bunch of errors.. Why its happened??? Any explanations?!

A: free() does not do what you appear to think it does. You use free on memory that you malloced after you have used it, when you're done with it.
With free you return the memory to the OS. It means you are no longer going to use it. Calling free immediately after malloc is like turning on your PC and then immediately shutting it down again.
The lines
List *node = malloc(sizeof(List));
free(node);
node->value = v; // can't use node after free()ing it

are problematic here because you allocate the memory. Then de-allocate (free) it and then use it anyway. Remove the call to free and call free in remove_node instead.


text:
Q: How to exclude NULL value in codeigniter and print in excel using get_where I have developeded my web app using Codeigniter. I have some problems where to print the value from the database that excluded the null value. I'm trying to use 'where(value IS NOT NULL)' then the whole row in the database was excluded. but it not process the where.

MODAL

public function get_distinct_fl_outgoing_feeder($obj_class, $bil, $source_file_id){

        switch ($bil) {

            case 'NEW':
                $this->db->from('sap_main, sap_outgoing_feeder');
                $this->db->join('sap_outgoing_feeder', 'sap_outgoing_feeder.sap_id = sap_main.id', 'right');
                $this->db->select('sap_main.id, sap_main.source_file_id, sap_main.category, sap_main.obj_label, sap_main.bil, sap_main.functional_location, sap_main.functional_location_desc, sap_main.fl_object_type, sap_main.cost_center, sap_main.business_area, sap_main.planner_group, sap_main.main_workcenter');
                $this->db->like('sap_main.bil', $bil);
                 $this->db->where('sap_outgoing_feeder.f10_fl IS NOT NULL OR sap_outgoing_feeder.f10_fl !=0');
                $result = $this->db->get_where('sap_main', array('sap_main.obj_class' => $obj_class, 'sap_main.source_file_id' => $source_file_id, 'sap_main.fl_status_flag' => 'O', 'sap_main.eq_status_flag' => 'O', 'sap_main.changed_fl_flag' => 'O'));
                   return $result->result_array();
                break;

            case 'EXISTING':
                $this->db->from('sap_main, sap_outgoing_feeder');
                $this->db->join('sap_outgoing_feeder', 'sap_outgoing_feeder.sap_id = sap_main.id', 'right');
                $this->db->select('sap_main.id, sap_main.source_file_id,sap_main.category, sap_main.obj_label, sap_main.bil, sap_main.functional_location, sap_main.functional_location_desc, sap_main.fl_object_type, sap_main.cost_center, sap_main.business_area, sap_main.planner_group, sap_main.main_workcenter');
                $this->db->not_like('bil', 'NEW');
                $this->db->where('sap_outgoing_feeder.f10_fl IS NOT NULL');
                $result = $this->db->get_where('sap_main', array('sap_main.obj_class' => $obj_class, 'sap_main.source_file_id' => $source_file_id, 'sap_main.fl_status_flag' => 'O', 'sap_main.eq_status_flag' => 'O', 'sap_main.changed_fl_flag' => 'O'));
                   return $result->result_array();
                break;

            default:
                $this->db->group_by('functional_location');
                $this->db->order_by('sap_main.id', 'ASC');
                // $this->db->where('f10_fl IS NOT NULL');
                $result = $this->db->get_where('sap_main, sap_outgoing_feeder', array('obj_class' => $obj_class, 'source_file_id' => $source_file_id, 'fl_status_flag' => 'O', 'eq_status_flag' => 'O', 'changed_fl_flag' => 'O'));
                return $result->result_array();
                break;

        }

    }

CONTROLLER

function write_dlvdb01($data){

    $ci = get_instance();

    $source_file_id = $data['source_file_id'];

    $obj_label = $data['obj_label'];

    $header = $data['file_header'];

    $objects = $ci->sap_model->get_distinct_fl_outgoing_feeder('D_LVDB','ALL',$source_file_id);

    if($objects){

        $rowCount = 1;

        $counter = 0;

        $spreadsheet = new Spreadsheet();

        if($header){

            $label = ['Functional Location','Structure Indicator','Category','Functional Location Description','Object Type','Maintenance Plant','Company Code','Business Area','Cost Center','Maintenance Planning Plant','Planner Group','Main Workcenter','Eqp Allow'];

            $spreadsheet->getActiveSheet()->fromArray(
                    $label,         // The data to set
                    NULL            // Array values with this value will not be set
                                        // Top left coordinate of the worksheet range where
                                        //    we want to set these values (default is A1)
                );

            $rowCount++;

        }

        foreach($objects as $object){

            $spreadsheet->getActiveSheet()->setCellValue('A'.$rowCount, $object['functional_location']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['functional_location_desc']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f1_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f1_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f2_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f2_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f3_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f3_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f4_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f4_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f5_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f5_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f6_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f6_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f7_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f7_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f8_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f8_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f9_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f9_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f10_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f10_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f11_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f11_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f12_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f12_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f13_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f13_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f14_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f14_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f15_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f15_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f16_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f16_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f17_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f17_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f18_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f18_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f19_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f19_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $spreadsheet->getActiveSheet()->setCellValue('A'.++$rowCount, $object['f20_fl']);
            $spreadsheet->getActiveSheet()->setCellValue('B'.$rowCount, 'TNBD');
            $spreadsheet->getActiveSheet()->setCellValue('C'.$rowCount, $object['category']);
            $spreadsheet->getActiveSheet()->setCellValue('D'.$rowCount, $object['f20_description']);
            $spreadsheet->getActiveSheet()->setCellValue('E'.$rowCount, $object['fl_object_type']);
            $spreadsheet->getActiveSheet()->setCellValue('F'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('G'.$rowCount, '6001');
            $spreadsheet->getActiveSheet()->setCellValue('H'.$rowCount, $object['business_area']);
            $spreadsheet->getActiveSheet()->setCellValue('I'.$rowCount, $object['cost_center']);
            $spreadsheet->getActiveSheet()->setCellValue('J'.$rowCount, '6000');
            $spreadsheet->getActiveSheet()->setCellValue('K'.$rowCount, $object['planner_group']);
            $spreadsheet->getActiveSheet()->setCellValue('L'.$rowCount, $object['main_workcenter']);
            $spreadsheet->getActiveSheet()->setCellValue('M'.$rowCount, '1');

            $rowCount++;

            $counter = $counter+ 4;

        }

        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);

        $file_directory = 'assets\\files\\downloads\\'.$ci->session->userdata('user_id').'\\sapFormat\\'.strtoupper($obj_label);

        if(!file_exists($file_directory)){

            mkdir($file_directory, 0777, true);

        }

        $filename = "01-D_LVDB-IL01-".$counter.".xls";

        $writer = new Xls($spreadsheet);

        $writer->save($file_directory.'\\'.$filename);

        $spreadsheet->disconnectWorksheets();

        unset($spreadsheet);

    }

}

OUTPUT

I want to remove that white space.
Thanks for helping.
I found the solution where i put the condition on the controller. Thanks all for helping.

A: $this->db->where() requires the second parameter to be passed even if you're passing fieldname is not null as the first parameter.
Since there's actually no second parameter to be passed, you need to use:
$this->db->where('f10_fl IS NOT NULL', NULL);
in query builder to exclude all rows where f10_fl has a null value in the table (or those which get nulled by an empty join)

A: Active record code should be
$this->db->where("f10_fl IS NOT NULL", NULL, FALSE);


text:
Q: Generate random dates with random times between two dates for selected period and frequency I have to create a scheduling component that will plan e-mails that need to be sent out. Users can select a start time, end time, and frequency. Code should produce a random moment for every frequency, between start and end time. Outside of office hours.
Paramaters:
User can select a period between 01/01/2020 (the start) and 01/01/2021 (the end). In this case user selects a timespan of one exactly year.
User can select a frequency. In this case user selects '2 months'.
Function:
Code produces a list of datetimes. The total time (one year) is divided by frequency (2 months). We expect a list of 6 datetimes.
Every datetime is a random moment in said frequency (2 months). Within office hours.
Result:
An example result for these paramaters might as follows, with the calculated frequency bounds for clarity:

*

*[jan/feb] 21-02-2020 11.36

*[mrt/apr] 04-03-2020 16.11

*[mei/jun] 13-05-2020 09.49

*[jul-aug] 14-07-2020 15.25

*[sep-okt] 02-09-2020 14.09

*[nov-dec] 25-12-2020 13.55

--
I've been thinking about how to implement this best, but I can't figure out an elegant solution.
How could one do this using PHP?
Any insights, references, or code spikes would be greatly appreciated. I'm really stuck on this one.

A: I think you're just asking for suggestions on how to generate a list of repeating (2 weekly) dates with a random time between say 9am and 5pm? Is that right?
If so - something like this (untested, pseudo code) might be a starting point:
$start    = new Datetime('1st January 2021');
$end      = new Datetime('1st July 2021');
$day_start = 9;
$day_end = 17;

$date = $start;
$dates = [$date]; // Start date into array
while($date < $end) {

    $new_date = clone($date->modify("+ 2 weeks"));
    $new_date->setTime(mt_rand($day_start, $day_end), mt_rand(0, 59));

    $dates[] = $new_date;
}

var_dump($dates);

A: Steve's anwser seems good, but you should consider 2 additional things

*

*holiday check, in the while after first $new_date line, like:

$holiday = array('2021-01-01',    '2021-01-06', '2021-12-25');
if (!in_array($new_date,$holiday))

*also a check if date is a office day or a weekend in a similar way as above with working days as an array.

A: It's kind of crappy code but I think it will work as you wish.
function getDiffInSeconds(\DateTime $start, \DateTime $end) : int
{
    $startTimestamp = $start->getTimestamp();
    $endTimestamp = $end->getTimestamp();

    return $endTimestamp - $startTimestamp;
}

function getShiftData(\DateTime $start, \DateTime $end) : array
{
    $shiftStartHour = \DateTime::createFromFormat('H:i:s', $start->format('H:i:s'));
    $shiftEndHour = \DateTime::createFromFormat('H:i:s', $end->format('H:i:s'));

    $shiftInSeconds = intval($shiftEndHour->getTimestamp() - $shiftStartHour->getTimestamp());

    return [
        $shiftStartHour,
        $shiftEndHour,
        $shiftInSeconds,
    ];
}

function dayIsWeekendOrHoliday(\DateTime $date, array $holidays = []) : bool
{
    $weekendDayIndexes = [
        0 => 'Sunday',
        6 => 'Saturday',
    ];

    $dayOfWeek = $date->format('w');
    if (empty($holidays)) {
        $dayIsWeekendOrHoliday = isset($weekendDayIndexes[$dayOfWeek]);
    } else {
        $dayMonthDate = $date->format('d/m');
        $dayMonthYearDate = $date->format('d/m/Y');
        $dayIsWeekendOrHoliday = (isset($weekendDayIndexes[$dayOfWeek]) || isset($holidays[$dayMonthDate]) || isset($holidays[$dayMonthYearDate]));
    }

    return $dayIsWeekendOrHoliday;
}

function getScheduleDates(\DateTime $start, \DateTime $end, int $frequencyInSeconds) : array
{
    if ($frequencyInSeconds < (24 * 60 * 60)) {
        throw new \InvalidArgumentException('Frequency must be bigger than one day');
    }

    $diffInSeconds = getDiffInSeconds($start, $end);

    // If difference between $start and $end is bigger than two days
    if ($diffInSeconds > (2 * 24 * 60 * 60)) {
        // If difference is bigger than 2 days we add 1 day to start and subtract 1 day from end
        $start->modify('+1 day');
        $end->modify('-1 day');

        // Getting new $diffInSeconds after $start and $end changes
        $diffInSeconds = getDiffInSeconds($start, $end);
    }

    if ($frequencyInSeconds > $diffInSeconds) {
        throw new \InvalidArgumentException('Frequency is bigger than difference between dates');
    }

    $holidays = [
        '01/01'         => 'New Year',
        '18/04/2020'    => 'Easter 1st official holiday because 19/04/2020',
        '20/04/2020'    => 'Easter',
        '21/04/2020'    => 'Easter 2nd day',
        '27/04'         => 'Konings',
        '04/05'         =>  '4mei',
        '05/05'         =>  '4mei',
        '24/12'         => 'Christmas 1st day',
        '25/12'         => 'Christmas 2nd day',
        '26/12'         => 'Christmas 3nd day',
        '27/12'         => 'Christmas 3rd day',
        '31/12'         => 'Old Year'
    ];

    [$shiftStartHour, $shiftEndHour, $shiftInSeconds] = getShiftData($start, $end);
    $amountOfNotifications = floor($diffInSeconds / $frequencyInSeconds);
    $periodInSeconds = intval($diffInSeconds / $amountOfNotifications);
    $maxDaysBetweenNotifications = intval($periodInSeconds / (24 * 60 * 60));
    // If $maxDaysBetweenNotifications is equals to 1 then we have to change $periodInSeconds to amount of seconds for one day
    if ($maxDaysBetweenNotifications === 1) {
        $periodInSeconds = (24 * 60 * 60);
    }

    $dates = [];
    for ($i = 0; $i < $amountOfNotifications; $i++) {
        $periodStart = clone $start;
        $periodStart->setTimestamp($start->getTimestamp() + ($i * $periodInSeconds));
        $seconds = mt_rand(0, $shiftInSeconds);

        // If $maxDaysBetweenNotifications is equals to 1 then we have to check only one day without loop through the dates
        if ($maxDaysBetweenNotifications === 1) {
            $interval = new \DateInterval('P' . $maxDaysBetweenNotifications . 'DT' . $seconds . 'S');
            $date = clone $periodStart;
            $date->add($interval);

            $dayIsWeekendOrHoliday = dayIsWeekendOrHoliday($date, $holidays);
        } else {
            // When $maxDaysBetweenNotifications we have to loop through the dates to pick them
            $loopsCount = 0;
            $maxLoops = 3; // Max loops before breaking and skipping the period
            do {
                $day = mt_rand(0, $maxDaysBetweenNotifications);
                $periodStart->modify($shiftStartHour);
                $interval = new \DateInterval('P' . $day . 'DT' . $seconds . 'S');
                $date = clone $periodStart;
                $date->add($interval);

                $dayIsWeekendOrHoliday = dayIsWeekendOrHoliday($date, $holidays);

                // If the day is weekend or holiday then we have to increment $loopsCount by 1 for each loop
                if ($dayIsWeekendOrHoliday === true) {
                    $loopsCount++;

                    // If $loopsCount is equals to $maxLoops then we have to break the loop
                    if ($loopsCount === $maxLoops) {
                        break;
                    }
                }
            } while ($dayIsWeekendOrHoliday);
        }

        // Adds the date to $dates only if the day is not a weekend day and holiday
        if ($dayIsWeekendOrHoliday === false) {
            $dates[] = $date;
        }
    }

    return $dates;
}

$start = new \DateTime('2020-12-30 08:00:00', new \DateTimeZone('Europe/Sofia'));
$end = new \DateTime('2021-01-18 17:00:00', new \DateTimeZone('Europe/Sofia'));
$frequencyInSeconds = 86400; // 1 day

$dates = getScheduleDates($start, $end, $frequencyInSeconds);
var_dump($dates);

You have to pass $start, $end and $frequencyInSeconds as I showed in example and then you will get your random dates. Notice that I $start and $end must have hours in them because they are used as start and end hours for shifts. Because the rule is to return a date within a shift time only in working days. Also you have to provide frequency in seconds - you can calculate them outside the function or you can change it to calculate them inside. I did it this way because I don't know what are your predefined periods.
This function returns an array of \DateTime() instances so you can do whatever you want with them.
UPDATE 08/01/2020:
Holidays now are part of calculation and they will be excluded from returned dates if they are passed when you are calling the function. You can pass them in d/m and d/m/Y formats because of holidays like Easter and in case when the holiday is on weekend but people will get additional dayoff during the working week.
UPDATE 13/01/2020:
I've made updated code version to fix the issue with infinite loops when $frequencyInSeconds is shorter like 1 day. The new code used few functions getDiffInSeconds, getShiftData and dayIsWeekendOrHoliday as helper methods to reduce code duplication and cleaner and more readable code


text:
Q: Is this 'preposition? I saw somebody say that 'because' used in subordinate clauses as in "I left because I was tired" is preposition.
I have considered 'because' as not a 'preposition' but a 'conjunction'.
What do you think of this? 'preposition' or 'conjunction' in this sentence like "I left  because I was tired."?

A: In modern grammar there is no difference between a subordinating conjunction and a preposition. We call both of these types of word prepositions in modern grammar. So the word before is the same word in the following three sentences:

*

*I've never seen her before.

*I saw her before the concert.

*I saw her before the concert started.

The word because is therefore a preposition in the OP's sentence.


text:
Q: django-admin.py makemessages not working I am trying to translate a string.
{% load i18n %}
{% trans "Well, Hello there, how are you?" %}

to...
Hola amigo, ¿que tal?

My settings.py file has this:
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'translations'),
)

And I am getting this:
(env)glitch:translations nathann$ django-admin.py compilemessages
CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed.

I also don't understand this error message.
(env)glitch:ipals nathann$ django-admin.py makemessages -l es
CommandError:
This script should be run from the Django Git tree or your project or
app tree. If you did indeed run it from the Git checkout or your project
or application, maybe you are just missing the conf / locale(in the
django tree) or locale(for project and application) directory? It is not
created automatically, you have to create it by hand if you want to
enable i18n for your project or application.

The docs: https://docs.djangoproject.com/en/1.6/ref/django-admin/#django-admin-makemessages
And for bonus upvotes, a related question:
gettext wasn't linked when I installed it... Any help with this one? Should I force it?
glitch:translations nathann$ brew link gettext
Warning: gettext is keg-only and must be linked with --force
Note that doing so can interfere with building software.

Thanks!

UPDATES:
I have since changed the name of translations to locale and updated my settings.py accordingly. then I ran this again and it's still complaining about gettext:
(env)glitch:ipals nathann$ mv translations/ locale
(env)glitch:ipals nathann$ django-admin.py makemessages -l es
CommandError: Can't find xgettext. Make sure you have GNU gettext tools 0.15 or newer installed.

I also found this:
Understand homebrew and keg-only dependencies
after reading this:
(env)glitch:ipals nathann$ brew install gettext
Warning: gettext-0.18.3.2 already installed
(env)glitch:ipals nathann$ brew link gettext
Warning: gettext is keg-only and must be linked with --force
Note that doing so can interfere with building software.

A: After making sure I had this in settings:
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
print(LOCALE_PATHS)

I double checked I had the locale directory in the right place with its name spelled correctly.
I ended up linking gettext (after asking about that on superuser):
brew link gettext --force

manage.py compilemessages

django-admin.py makemessages -l es

And BAM. I've got my po file.
But the doctor says:
Warning: Some keg-only formula are linked into the Cellar.
Linking a keg-only formula, such as gettext, into the cellar with
`brew link <formula>` will cause other formulae to detect them during
the `./configure` step. This may cause problems when compiling those
other formulae.

Binaries provided by keg-only formulae may override system binaries
with other strange results.

You may wish to `brew unlink` these brews:

    gettext

A: Please try this in Ubuntu
sudo apt-get install gettext
And use brew install gettext in OSX
Also make sure to set the local path in settings.py file.

A: For Mac users brew link gettext --force can be risk, as Brew advises. A better work around is to set a new PATH variable for your virtual environment. So, in the postactivate file, which is located in the bin folder of your virtual environment folder, type:
export TEMP_PATH=$PATH
export PATH=$PATH:/usr/local/Cellar/gettext/0.19.7/bin

Note that you have to replace 0.19.7 by the version that is installed in your machine.
And in your predeactivate file, which is located in the same folder of postactivate file, type:
export PATH=$TEMP_PATH
unset TEMP_PATH

Now you can use the python manage.py makemessages -l <desired_language> without worries. :)
Cheers.

A: For macOS :
brew install gettext
export PATH="/usr/local/opt/gettext/bin:$PATH"

A: Have you added {% load i18n %} to the top of your template?
Bonus: You don't need to link gettext, what is the output from brew doctor?

A: Please install gettext in your ubuntu OS
using sudo apt-get command
Or in Mac
using brew command

A: Here is the solution for those having problems with translations or are creating a multi-language site for the very first time in Django. Here is the way I do it, and I have been doing since Django 1.4, below is tested in 1.7.1:
In settings.py …
Add to MIDDLEWEAR_CLASSES, locale, it enables language selection based on request:
'django.middleware.locale.LocaleMiddleware',

Add LOCALE_PATHS, this is where your translation files will be stored, also enable i18N:
USE_I18N = True

LOCALE_PATHS = (
    os.path.join(PROJECT_PATH, 'locale/'),
)

Set LANGUAGES that you will be translating the site to:
ugettext = lambda s: s
LANGUAGES = (
    ('en', ugettext('English')),
    ('fr', ugettext('French')),
    ('pl', ugettext('Polish')),
)

Add i18n template context processor, requests will now include LANGUAGES and LANGUAGE_CODE:
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n', # this one
    'django.core.context_processors.request',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
)

Nest, in urls.py :
In url_patterns, add the below, it will enable the set language redirect view:
url(r'^i18n/', include('django.conf.urls.i18n')),

See Miscellaneous in Translations for more on this.
Add the following imports, and encapsulate the urls you want translated with i18n_patterns. Here is what mine looks like:
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^i18n/', include('django.conf.urls.i18n')),
)

urlpatterns += i18n_patterns('',
    (_(r'^dual-lang/'), include('duallang.urls')),
    (r'^', include('home.urls')),
)

Note: You can also drop your admin urls into the i18n_patterns.
Now anywhere you use text and want to convert it, import lazytext and wrap every string with it like so _('text'), you can even go to your other urls.py files and do url translation like so:
url(_(r'^dual_language/$'), landing, name='duallang_landing'),

You can wrap text that you want translated in your other files, such as models.py, views.py etc.. Here is an example model field with translations for label and help_text:
name = models.CharField(_('name'), max_length=255, unique=True, help_text=_("Name of the FAQ Topic"))

Django translation docs are great for this!
In your html templates...
Now you can go into your templates and load the i18n templatetag and use trans and transblock on the static stuff you want to translate. Here is an example:
{% load i18n %}

{% trans "This is a translation" %}

{% blocktrans with book_t='book title'|title author_t='an author'|title %}
This is {{ book_t }} by {{ author_t }}. Block trans is powerful!
{% endblocktrans %}

Now run a makemessages for each of your locales:
./manage.py makemessages -l pl

And now all is left is to go into your /locales folder, and edit each of the .po files. Fill in the data for each msgstr. Here is one such example of that:
msgid "English"
msgstr "Angielski"

And finally compile the messages:
./manage.py compilemessages

There is a lot more to learn with translations and internationalization is closely related to this topic, so check out the docs for it too. I also recommend checking out some of the internationalization packages available for Django like django-rosetta, and django-linguo. They help translate model content, django-rosetta does not create new entries for this in your database, while django-linguo does.
If you followed this you should be off to a good start. I believe this is the most standardized way to get your site running in multiple languages. Cheers!

A: If you don't want to link gettext (which you shouldn't because messing about with OS X internals is bad) then you can set the PATH for the makemessages command. The following should work (but you need to adjust your gettext version number):
PATH=/usr/local/Cellar/gettext/<installed version>/bin/:$PATH && \
django-admin makemessages -l <language>

If you do it that way your installed gettext remains keg-only and django-admin will be happy and find all the programms it needs.

A: One of the possibilities is that after you have successfully done all the above and done
pip install python-gettext

you may have improperly configured your IDE or venv. In order to bypass this, go to the command prompt, navigate to your root folder and run py manage.py makemessages from there. It will work.

A: For me, on Windows 10, the problem was that I used gettext installed with pip install (I got version 0.19-something). I made it work by:

*

*Uninstalling gettext with pip.

*downloading gettext (as a zip) from here istead: https://mlocati.github.io/articles/gettext-iconv-windows.html

*Extracting the files in a foler on "C:/program files"

*Added the path to the "bin" folder (inside the extracted folder) to PATH in my environment variables in windows.

After that it worked! (after 5 h frustrated debugging...)


text:
Q: SharePoint Performance Point Custom Filter Renderer Class Error I have two servers (Server A and Server B) in one SharePoint 2010 farm.  I am getting following error on SharePoint Dashboard page while using the custom PPS filter webpart on Dashboard.
I have used Microsoft PerformancePoint Services SDK sample as base and created a custom Rendered class to define in FilterEditor Class as
filter.RendererClassName = typeof(CustomFilter).AssemblyQualifiedName;

Critial Error:

0x0500   PerformancePoint Service        PerformancePoint Services       4   Critical    An unexpected error occurred.  Error 20798.  Exception details: System.ServiceModel.FaultException: An unknown error has occurred. If the problem persists contact an administrator. There may be additional information in the server application event log.    Server stack trace:      at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)    Exception rethrown at [0]:... c9c0a044-c18d-4374-ad6f-e99d2a2959cd

Critial Error:

PerformancePoint Services        4   Critical    ...      at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)     at Microsoft.PerformancePoint.Scorecards.IBIMonitoringServiceApplication.GetFilterDependencies(RepositoryLocation filterLocation)     at Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplicationProxy.<>c_DisplayClassbb.b_ba(IBIMonitoringServiceApplication channel)     at Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplicationProxy.ExecuteOnChannel(CodeBlock codeBlock)    c9c0a044-c18d-4374-ad6f-e99d2a2959cd

And finally:

PerformancePoint Services        ef8z    Critical    An exception occurred while rendering a Web control. The following diagnostic information might help to determine the cause of this problem:  Microsoft.PerformancePoint.Scorecards.BpmException: There was a problem preparing the WebPart for display.  PerformancePoint Services error code 20700.   c9c0a044-c18d-4374-ad6f-e99d2a2959cd

Please advice what I should do to overcome this problem.

A: In the web.config file, how did you specifiy the assembly for the renderer? It should be in this format:
Namespace.Class name, DLL name, DLL version number, DLL culture, DLL public key token
And it should look something like the RendererClass in this example:
<CustomFCO type="Filter" subType="SampleFilter">
    <Resources FCOName="Custom Filter" FCODescription="This is my custom filter." />
    <RendererClass name="Microsoft.PerformancePoint.Scorecards.ServerRendering.MultiSelectTreeViewControl,
Microsoft.PerformancePoint.Scorecards.ServerRendering, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    <EditorURI uri="/_layouts/SampleFilterEditor.aspx" />
</CustomFCO>

(http://msdn.microsoft.com/en-us/library/ee556434.aspx)


text:
Q: Flat vector bundles and constant transition functions Let $E\to M$  be a vector bundle endowed with a flat connection. Then, does $E$ admit a bundle atlas with constant transition functions?
For a vector bundle with constant transition functions, are the possible structure groups in correspondence with representations of the fundamental group of the base?
Thanks.

A: Here is a brief answer to your first question:
Let $(M, \mathscr{O}_M)$ be a real or complex manifold, where $\mathscr{O}_M$ is the structure sheaf. Let $\mathbb{K}$ denoted either $\mathbb{R}$ or $\mathbb{C}$, as appropriate, and $\mathbb{K}_M$ the corresponding constant sheaf on $M$. Let $\nabla: \mathscr{E} \to \Omega^1 \otimes_{\mathscr{O}_M} \mathscr{E}$ be the linear connection, which is a $\mathbb{K}_M$-linear map.
If the connection is flat, then $\mathscr{L} := \ker(\nabla)$ is a local system of $\mathbb{K}_M$-modules (i.e. a locally free sheaf). Pick a trivializing open cover, and then you can see that the corresponding transition functions must be locally constant for $\mathscr{L}$.
Since the vector bundle can be recovered from the local system by tensoring $\mathscr{O}_M\otimes_{\mathbb{K}_M} \mathcal{L} \cong \mathcal{E},$ then the vector bundle admits locally constant transition functions as well.


text:
Q: How private is my code in WebAssembly? I have some c++ binary running on my web server that does some calculations and I was thinking about moving it to the user side using Webassembly. My question is how private will my c++ code be? Is it possible to transform a compiled Webassembly file back to c++?

A: How private is it? Not private at all. Your WebAssembly code is delivered over HTTP to the client's machine where it is executed. It is obfuscated a little, but hardly private.
The code is delivered in a binary format, however using readily available tools, e.g. wasm2wat, this can easily be converted into a human readable text format. The text is a relatively low level language, but still quite readable. It will not protect your algorithms, it will simply take people a little longer to understand them.
WebAssembly is not readily transformable back to higher level languages (e.g. C++), but this does not make your algorithm private.


text:
Q: How to store files generated from app in "Downloads" folder of Android? I am generating an excelsheet in my app which when generated should be automatically saved in the "Downloads" folder of any android device where all the downloads are typically saved.
I have the following which saves the file under "My Files" folder  -
File file = new File(context.getExternalFilesDir(null), fileName);

resulting in -
W/FileUtils﹕ Writing file/storage/emulated/0/Android/data/com.mobileapp/files/temp.xls

I rather want to save the generated file automatically in the "Downloads" folder when the excel sheet is generated.
Update # 1: Please see the snapshot here. What I want is the one circled in red and what you suggested gets stored in the one circled blue (/storage/emulated/0/download) if that makes sense. Please advise on how I can save a file in the one circled red i.e., "Downloads" folder which is different from /storage/emulated/0/Download under "MyFiles"

A: I used the following code to get this to work in my Xamarin Droid project with C#:
// Suppose this is your local file
var file = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
var fileName = "myFile.pdf";

// Determine where to save your file
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, fileName);

// Create and save your file to the Android device
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, file);

// Notify the user about the completed "download"
var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
downloadManager.AddCompletedDownload(fileName, "myDescription", true, "application/pdf", filePath, File.ReadAllBytes(filePath).Length, true);

Now your local file is "downloaded" to your Android device, the user gets a notification, and a reference to the file is being added to the downloads folder. Make sure, though, to ask the user for permission before you write to the file system, otherwise an 'access denied' exception will be thrown.

A: For API 29 and above
According to documentation, it is required to use Storage Access Framework for Other types of shareable content, including downloaded files.
System file picker should be used to save file to External storage directory.
Copy file to external storage example:
// use system file picker Intent to select destination directory
private fun selectExternalStorageFolder(fileName: String) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
        putExtra(Intent.EXTRA_TITLE, name)
    }
    startActivityForResult(intent, FILE_PICKER_REQUEST)
}

// receive Uri for selected directory
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        FILE_PICKER_REQUEST -> data?.data?.let { destinationUri ->
            copyFileToExternalStorage(destinationUri)
        }
    }
}

// use ContentResolver to write file by Uri
private fun copyFileToExternalStorage(destination: Uri) {
    val yourFile: File = ...

    try {
        val outputStream = contentResolver.openOutputStream(destination) ?: return
        outputStream.write(yourFile.readBytes())
        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

A: Use this to get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

And don't forget to set this permission in your manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A: As Oluwatumbi have answered this question correctly but First you need to check for permission is granted for WRITE_EXTERNAL_STORAGE by following code:
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted
        // Request for permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

    }else{
        Uri uri = Uri.parse(yourUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
        request.allowScanningByMediaScanner();// if you want to be available from media players
        DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }

A: Now from your question edit I think understand better what you want.
Files shown on the Downloads menu from the one circled in red are ones that are actually downloaded via the DownloadManager, though the previos steps I gave you will save files in your downloads folder but they will not show in this menu because they weren't downloaded. However to make this work, you have to initiate a download of your file so it can show here.
Here is an example of how you can start a download:
 DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
request.allowScanningByMediaScanner();// if you want to be available from media players
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);

This method is used to download from a Uri and i have not used it with a local file.
If your file is not from the internet you could try saving a temporary copy and get the Uri of the file for this value.

A: Just use the DownloadManager to download your generated file like this:
File dir = new File("//sdcard//Download//");

File file = new File(dir, fileName);

DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);

downloadManager.addCompletedDownload(file.getName(), file.getName(), true, "text/plain",file.getAbsolutePath(),file.length(),true);

The "text/plain" is the mime type you pass so it will know which applications can run the downloadedfile. That did it for me.

A: This is running code download files using DownloadManager for Xamarin android api version 29
public bool DownloadFileByDownloadManager(string imageURL)
        {
            try
            {
                string file_ext = Path.GetExtension(imageURL);
                string file_name = "MyschoolAttachment_" + DateTime.Now.ToString("yyyy MM dd hh mm ss").Replace(" ", "") + file_ext;
                var path = global::Android.OS.Environment.DirectoryDownloads;

                Android.Net.Uri uri = Android.Net.Uri.Parse(imageURL);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.SetDestinationInExternalPublicDir(path, file_name);
                request.SetTitle(file_name);
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted); // to notify when download is complete

                // Notify the user about the completed "download"
                var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);

                var d_id = downloadManager.Enqueue(request);
                return true;
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.Alert("Error in download attachment.", "Error", "OK");
                System.Diagnostics.Debug.WriteLine("Error !" + ex.ToString());
                return false;
            }
        }

A: WORKING ON API 29 AND 30
To get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Set this permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Add requestLegacyExternalStorage to your application tag in AndroidManifest.xml (for API 29):
<application
    ...
    android:requestLegacyExternalStorage="true">


text:
Q: how to separate certain parts of a string in python Lets say i have myVariable = 'Hello world'
How can I get just "World"? Ive tried a bunch of ways.
I am trying to make a chat bot at the moment, and I am making a settings command where you type :BotSettings in a input.

A: You can split on space and select element nr 1.
myVariable.split(' ')[1]

A:
If I have myVariable = "Hello World", how do I
make it "World"?

myVariable = "World"

If I have myVariable = "Hello World", how do I find the second word?

myVariable = myVariable.split()[1] # "World"

If I have myVariable = "apple Hello World banana", how do I find everything written after "Hello"?

_, _, myVariable = myVariable.partition("Hello ")


text:
Q: How to use named constants in Symfony2? I'm trying to use named constants in a Symfony2 project which are required by my in-house third-party code. Is there a way of managing such configuration parameters using Symfony2 ymls?

A: I found this, which is part of the official Symfony 2 documentation which looked interesting:
How to Set External Parameters in the Service Container.
The final section in the document is interesting as it describes how you can use the PHP include statement to run any PHP script file as part of the application configuration.
The document:
Miscellaneous Configuration
The imports directive can be used to pull in parameters stored elsewhere. Importing a PHP file gives you the flexibility to add whatever is needed in the container. The following imports a file named parameters.php.
YAML

# app/config/config.yml
imports:
    - { resource: parameters.php }

XML

<!-- app/config/config.xml -->
<imports>
    <import resource="parameters.php" />
</imports>

PHP

// app/config/config.php
// $loader->import('parameters.php');

// our third party config
$loader->import('ThirdPartyDefines.php');

Now, all that is required is create a script called something like:
ThirdPartyDefines.php
In that file have the required defines : i.e.
define('THIRD_PARTY_V1', 'ACME_value1');
define('THIRD_PARTY_V2', 'ACME_value12');

etc.

A: You can use parameters for this :
$container->hasParameter('namedConstant');
$container->getParameter('namedConstant');
$container->setParameter('namedConstant', 'a new value');

A: You could create a bundle that integrates your in-house code into Symfony. You could use parameters or the bundle's configuration to provide the values that the bundle will then define as constants.
Imagine you generate a bundle, GreatInHouseProjectBundle. You will also get an extension, GreatInHouseProjectBundle\DependencyInjection\GreatInHouseProjectExtension. You could then define your constants there.
Using a parameter:
class GreatInHouseProjectExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        # ...

        if( ! defined('THIRD_PARTY_V1') ) {
            define(
                'THIRD_PARTY_V1',
                $container->getParameter('third_party.version')
            );
        }
    }
}

Using the bundle configuration:
class GreatInHouseProjectExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        if( ! defined('THIRD_PARTY_V1') ) {
            define(
                'THIRD_PARTY_V1',
                $config['third_party_version']
            );
        }
    }
}


text:
Q: Copy rows with certain value vba excel Hi all I have a sheet with more then 60 000 rows and I want to copy all rows to a new sheet if column of row contains certain value for example Energizer like in the following code
 Sub Macro3()
    Dim rngA As Range
    Dim cell As Range
    Set col = Cells(Rows.Count, "A").End(xlUp)

    Set rngA = Range("A2", col)
    For Each cell In rngA
        If cell.Value = "Energizer" Then
            cell.EntireRow.Copy

        End If
    Next cell

End Sub

Code doesn't work at all what could be done?

A: The following copies all rows containing "Energizer" in column A into the clipboard.
    Sub Macro3()
    Dim rngA As Range
    Dim cell As Range
    Dim col As Range
    Dim copiedRange As Range
    Dim r As Integer

    Set col = Cells(Rows.Count, "A").End(xlUp)
    r = 0
    Set rngA = Range("A2", col)

    For Each cell In rngA
        If cell.Value = "Energizer" Then
            If r = 0 Then
                Set copiedRange = cell.EntireRow
                r = 1
            Else
                Set copiedRange = Union(copiedRange, cell.EntireRow)
            End If
        End If
    Next cell

    If r = 1 Then
        copiedRange.Copy
    End If

End Sub

As mentioned in the code, if you want to copy the rows directly to a new sheet, add the destination after the copy command.

A: If this is really all of your code, you forgot to paste your copied row to the new sheet.


text:
Q: Python Turtle constant text input box Using turtle, i need to get constant text inputs. The ideal thing would be:
1. an input box fixed inside the main turtle.Screen()
2. the possibility of getting text inputs separated by an input event(ex. enter)
for the same needs and to the degree of my knowledge i found the turtle.textinput('title','prompt') not really satisfying. What kind of solution would you suggest?
Thanks in advance!

A: The simplest way to combine fixed input widgets with turtle graphics is to embed a turtle canvas in tkinter instead of running turtle standalone atop tkinter.
You can find an example in Trying to take user input and make a turtle dot - searching for RawTurtle will get you many examples.