text:
Q: Two functions utilizing registration_errors filter I wrote two plugins that utilize the registration_errors filter:
add_filter( 'registration_errors', 'process_payment', 10, 3 );

add_filter( 'registration_errors', 'add_user_to_SF', 10, 3 );

When add_user_to_SF returns errors, the process_payment function runs successfully (I know this because it processes a payment).
How can I set this up so that when one of them returns an error the other doesn't run and user registration doesn't happen?

A: Identifying errors via error code
Run add_user_to_SF with an earlier priority, to make it execute first
add_filter( 'registration_errors', 'add_user_to_SF', 9, 3 );`

Let's assume you have two possible errors in your add_user_to_SF:
function add_user_to_SF( $errors, $sanitized_user_login, $user_email )
{
    $has_errors = false;

    if ( /* some condition that should throw an error */ ) {
        $errors->add( 'some_error', 'some message' );
        $has_errors = true;
    }
    if ( /* another condition that should throw an error */ ) {
        $errors->add( 'another_error', 'another message' );
        $has_errors = true;
    }

    if ( ! $has_errors ) {
        /* write to your external DB */
    }

    return $errors;
}

Then check for those errors in the latter function by using the $errors object's get_error_codes method:
function process_payment( $errors, $sanitized_user_login, $user_email )
{
    $error_codes = $errors->get_error_codes();

    if (
        is_array( $error_codes ) &&
        ! empty( $error_codes ) &&
        ! empty( array_intersect( array( 'some_error', 'another_error' ), $error_codes ) )
    ) {
        return $errors;
    } else {
        /* run your payment processing */
    }

    return $errors;
}

Via a flag
The following is a mock-up of how you'd do it with a flag as a class property:
if ( ! class_exists( 'WPSE_96362_Registration_Errors' ) ) {
    class WPSE_96362_Registration_Errors
    {
        /* error flag */
        private $has_errors = false;

        /* constructor with filters */
        public function __construct()
        {
            /* earlier priority for "add_user_to_SF" method */
            add_filter( 'registration_errors', array( $this, 'add_user_to_SF' ), 9, 3 );
            add_filter( 'registration_errors', array( $this, 'process_payment' ), 10, 3 );
        }

        public function add_user_to_SF( $errors, $sanitized_user_login, $user_email )
        {
            if ( /* some condition that should throw an error */ ) {
                 $errors->add( 'some_error', 'some message' );
                 $this->has_errors = true;
            }
            if ( /* another condition that should throw an error */ ) {
                 $errors->add( 'another_error', 'another message' );
                 $this->has_errors = true;
            }

            if ( ! $this->has_errors ) {
                /* write to your external DB */
            }

            return $errors;
        }

        public function process_payment( $errors, $sanitized_user_login, $user_email )
        {
            if ( $this->has_errors ) {
                return $errors;
            } else {
                /* run your payment processing */
            }

            return $errors;
        }
    }
}

$wpse_96362_registration_errors = new WPSE_96362_Registration_Errors();


text:
Q: Android, should I center content? I'm pretty new to android and wanted to ask about the centering practices, what I mean is that for example:
Before I say something, I don't know what are the good practices are so...
I can have a LinearLayout with height as match_parent and android:layout_marginTop="?attr/actionBarSize"(btw, according to google's material 56dp).
So that is one option, but, I saw apps where the content is centered nicely if the device is really long(such as Galaxy Note devices), so what I did is:
Same LinearLayout but with height as wrap_content and android:layout_gravity="center", but the problem here is with for example a form with 1 field(almost no content height), the problem is that almost no content will leave you with a lot of space between the toolbar and the content and below that content as well.
My question: altought may be obscure I'm asking for the best practices, what is the best approach that will make content(bigger or smaller) appear nicly on multiple devices, maybe it would require multiple layouts/dimens, I'm ok with that, just looking for the right path.

A: There is another view group named RelativeLayout.
You can use it like this:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        // here you can use attributes such as `android:layout_below`, `android:layout_above`,`layout_toRightOf`
        //to modify and control your items
    />

</RelativeLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Timezone updater doesn't work This 26th of October new timezone was set(-1 hour). So I ran this command on 24th:
java -jar tzupdater.jar --update

And now(10:19) time doesn't work with new timezone:
 public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d);

    }

Output:

Mon Oct 27 11:19:35 MSK 2014

I tried to run that command again:

You have the same version as the embedded one

Versions are:

tzupdater version 1.4.8-b01 JRE time zone data version: tzdata2014h
  Embedded time zone data version: tzdata2014h

What's wrong?

A: You don't seem to understand what a timezone is, and what this command does.
A Timezone is not an hour offset. A TimeZone is something like "Europe/Paris". And a TimeZone encapsulates the offset, along with the rules that govern the changes to the offset. For example, if you use the timezone "Europe/Paris", then you'll be at UTC+2 in the summer time, and at UTC+1 in the winter time. The TimeZone knows the rules and knows when to go from summer to winter time.
Since these rules frequently change, you can update them thanks to the command you executed. So, the command doesn't change the offset from UTC+2 to UTC+1. It simply updates your Java installation so thet new rules, that have been introduced since the last update, are taken into account.

A: You must be sure which jre you expect to be updated. It can be more than one jre on your host. In my windows i have at least two jre-s: in /Program Files/jdk/jre and in /Program Files/jre folders.
You have to check ALL jre/lib folders. The folder jre_home/lib/zi should be updated (notice the folder time).
I don't know how updater choose the jre_home but i know that it doesn't always update the jre-s you expect.
In Windows you seems can just put updated zi folder to jre_home/lib, but in Unix i'm not sure.


text:
Q: How can I compress files with the output name same as parent folder? How can I compress files with the output name same as parent folder?
For example, I have a the folders:
ubup@neter:/NeuroNER-master/output$ tree
.
├── en_2017-04-28_20-26-59-439552
│   ├── 000_test.txt
│   ├── 000_test.txt_conll_evaluation.txt
│   ├── 000_train.txt
│   ├── 000_train.txt_conll_evaluation.txt
│   ├── 000_valid.txt
│   ├── 000_valid.txt_conll_evaluation.txt
│   ├── 001_test.txt
│   ├── 001_test.txt_conll_evaluation.txt
│   ├── 001_train.txt
│   ├── confusion_matrix_for_epoch_0005_in_valid_binary_evaluation.df
│   ├── confusion_matrix_for_epoch_0005_in_valid_bio_evaluation.df
│   ├── confusion_matrix_for_epoch_0005_in_valid_token_evaluation.df
│   ├── model
│   │   ├── checkpoint
│   │   ├── dataset.ickle
│   │   ├── tensorboard_metadata_characters.sv
│   ├── results.son
│   └── tensorboard_logs
│       ├── test
│       │   └── events.ut.fevents.493425627.er

I would like to compress the folder en_2017-04-28_20-26-59-439552 into en_2017-04-28_20-26-59-439552.tar.bz2
I could use with the free, open source program  lbzip2:
tar -c -I lbzip2 -f en_2017-04-28_20-26-59-439552.tar.bz2 *

However I don't want the command to contain the name of the archive file (en_2017-04-28_20-26-59-439552.tar.bz2), because in my application I don't know it ahead of time.

A: I eventually used the following bash script:
for d in */ ; do
   tar -c -I lbzip2 -f "${d%/}.tar.bz2" "$d"
done

Some comments:

*

*for d in */ ; do loop through directories  (How do I loop through only directories in bash?)

*${d%/} removes the trailing slash of the folder name (it would return $d unchanged if there was no trailing slash).

*This creates an archive for both subdirectories of the current directories, and symbolic links in the current directory that point to an existing directory.


text:
Q: Display Opportunity field history Visualforce I am new to Salesforce development and trying to resolve an issue i have come across. Any inputs are highly Appreciated.
I have developed a custom visual force page for the Opportunity details and i want to display a Opportunity Field History Related list. I used the Following Apex tag to display the code, but Its showing " Histories is not a valid child relationship name for entity Opportunity". Can you please let me know what the issue is?
 <apex:relatedlist list="OpportunityTeamMembers" title="Opportunity Team"/>
 <apex:relatedlist list="Histories" title="Opportunity Team"/>
 <apex:relatedlist list="OpportunityHistories" title="Stage History"/>
 <apex:relatedlist list="Contracts__r" title="Contracts"/>

Thanks.

A: Histories is a special related list you need to build it using  or  or
<apex:page standardController="opportunity">
 <apex:relatedlist list="OpportunityHistories" title="Stage History"/>
 <apex:pageBlock >
 <apex:pageblocktable value="{!opportunity.Histories}" var="hist" title="opporty">
 <apex:column value="{!hist.createddate}"/>
 </apex:pageblocktable>
</apex:pageBlock>
</apex:page>


text:
Q: Why do I have to explicitly nilify blanks for the shoulda matcher `inclusion:` validation to pass? I have a string column in my database that holds a time zone. Valid values include nil or anything that ActiveSupport recognizes as a timezone
I use shoulda-matchers to write specs for my model validation:
# app/models/my_model.rb
class MyModel < ApplicationRecord
  validates :timezone, inclusion: ActiveSupport::TimeZone::MAPPING.keys, allow_nil: true
end

# spec/models/my_model_spec.rb
describe "timezone" do
  it do
    should validate_inclusion_of(:timezone).
      in_array(ActiveSupport::TimeZone::MAPPING.keys).
      allow_blank
    end
end

It threw an error:
Failure/Error: it { should validate_inclusion_of(:timezone).in_array(ActiveSupport::TimeZone::MAPPING.keys).allow_blank }

     MyModel did not properly validate that
     :timezone is either ‹"International Date Line West"›, ‹"Midway Island"›,
     ‹"American Samoa"›, ‹"Hawaii"›, ‹"Alaska"›, ‹"Pacific Time (US &
     .....
     .....
     .....
     ‹"Auckland"›, ‹"Wellington"›, ‹"Nuku'alofa"›, ‹"Tokelau Is."›, ‹"Chatham
     Is."›, or ‹"Samoa"›, but only if it is not blank.
       After setting :timezone to ‹""›, the matcher expected the
       MyModel to be valid, but it was invalid
       instead, producing these validation errors:

       * timezone: ["is not included in the list"]

Shoulda matchers sets the column to "" and expects that the validations should pass. But why is that expected? nil is strictly allowed but a blank string value shouldn't be, right?
Is there a more proper way to set this up that I've missed?
To work around it, I use us a before_validation block. (And I know of the nilify_blanks gem that does the same thing). But it feels odd that I'd have to include that at all
before_validation do
  self[:timezone] = nil if self[:timezone].blank?
end

A: .blank? is an ActiveSupport method that returns true for nil, false and more imporantly "" (an empty string).
Thats why allow_blank tests with an empty string. Use allow_nil instead.
# spec/models/my_model_spec.rb
describe "timezone" do
  it do
    should validate_inclusion_of(:timezone).
      in_array(ActiveSupport::TimeZone::MAPPING.keys).
      allow_nil
  end
end


text:
Q: Is it possible to add a Canvas App to a Facebook (Place) Location? Is it possible to add a Canvas App to a Facebook (Place) Location?
It's easy enough to add them to standard pages, with the following:
https://www.facebook.com/dialog/pagetab?app_id=ID_OF_APP&display=popup&next=APP_URL

But is it possible to add canvas apps to Locations?  There are "holes" to put them in, but they don't appear in the add-an-app dialog that the link above triggers.
Locations to be clear, is what you see from a page's admin menu under "Locations" in the left-hand side.  Each location has its own page like count, and Timeline.

A: Figured it out, what a pain.  Listed the solution here:
http://circlical.com/blog/2013/4/15/adding-facebook-applications-canvas-to-location-pages


text:
Q: Make a DIV childrens appears one by one or Randomly on Page load I want to make
 '#it1', '#it2', '#it3' ... '#itX' to load(appear) one by one in random order on the page load.
Got this script:
var max = $('#line1').children().length;
var ctr = 1;
$('#itbg div').css('opacity','0');
setTimeout(delay,1000);
function delay(){
$('#it' + max).delay(1000).css('opacity','1'); // works Only for the Last DIV (#itX)
$('#it' + ctr).delay(1000).css('opacity','1'); // works Only for the First DIV (#it1)
}

And HTML like this

content

content2

content2

In which way I must dig to figure it out? I need #it1, #it2, #it3..#itX to appear in random order one by one or just one by one(directly). And the fiddle of this code is here.

A: You have to collect a list of your items, then scramble the list, then make the items appear:
var max = $('#line1').children().length;
var ctr = 1;
var i,j,k,t,next;

// items in order (ex. [1,2,3,4,5,6])

var itms=[];
for(i=1;i<=max;i++)
    itms.push(i);

// now scramble the items randomly (ex. [6,2,3,1,2,4,5])

for(i=0;i<max;i++)
{
    // choose two items randomly
    j = Math.floor(Math.random() * max);
    k = Math.floor(Math.random() * max);
    // swap
    t = itms[j];
    itms[j] = itms[k];
    itms[k] = t;
}

// fade in one item at time (following the scrambled list)

fadeIn(0, max, itms);

function fadeIn(current, max, itmsList)
{
    $('#it' + itmsList[current]).fadeIn(1000);
    if(current<max)
    {
        setTimeout( function() {fadeIn(current + 1,max,itmsList);}, 1000);
    }
}

Note that you have a bad mistake in your html: more elements with same id
Rewrite like this:

content1

content2

content3

content4

content5

Finally adjust your CSS in a way that items of class itbg are not visible initially.
.itbg div {
    border:1px solid grey;
    display: none;
}

See http://jsfiddle.net/pV55k/

A: at first you have to set the opacity to 0
then you can change it to "1" in One second , SO it will be like this :
if you have already change the opacity to zero you can eliminate the code which change the opacity to ZERO :D
this  Jquery just work on your HTML :D
 $(function () {
        max = new Array();
        $.each($('#line1 > #item > #itbg').children(), function () {
            //here it change the opacity to ZERO
            $(this).animate({'opacity' : '0'},1);
            max.push($(this));
        });

      $(max[0]).animate({ 'opacity': '1' }, 1000, function () {
            $(max[1]).animate({ 'opacity': '1' }, 1000, function () {
                $(max[2]).animate({ 'opacity': '1' }, 1000, function () {
                    $(max[3]).animate({ 'opacity': '1' }, 1000, function () {
                        $(max[4]).animate({ 'opacity': '1' }, 1000);
                    });
                });
            });
        });
    });

A: In my opinion if you want to keep the current structure you can just find the ids similar with regex in the selector and apply your css opacity change.
function delay(){
    $("div[id^='it']").delay(1000).css('opacity','1');
}

I hope this helps. Unfortunately jQuery does not have such a good regex so you cant find it + a number so it searches for string that starts with 'it'.

A: this one will not affect with the numbers of your IT You can have 1000 of them  :D
            var i = 1;
        $.each($("div[id^='it']"), function () {
            $(this).delay(1000 + (i * 100)).animate({ 'opacity': '1' }, 1000);
            i++;
        });


text:
Q: Create basic RESTful API Server to a datastore I have the most basic of questions, but the more I think about it, the more complex it gets.
I've been using rails and it follows the MVC paradigm in that db and api calls are abstracted through calls generated through the controller.  This seems way too heavy for what I want.
1) I want a simple (basic) web server that sits in front of my datastore. (The contents of which happen to be stored in a directory structure that follows: /LOCATIONS/LOCATION/PRESENTERS/PRESENTER/YEAR/MN/)
2) I want to be able to host json files within that directory structure and GET them as needed.
3) I want to be able to PUT/POST append to those json files.
Seems like all I'd need is nginx with my datastore as a doc root and index.html files at critical places within the structure (e.g. site.com/Locations/index.html , site.com/locations/SF/presenters/solomon/index.html)?
How would I begin to solve this problem, (without the use of controllers of coarse)?

A: MVC Frameworks

without the use of controllers

You must be aware that there are many more frameworks than Rails out there, so when you ask about using a system to "sit in front of your datastore", you're really looking for different frameworks to handle requests, of which there are many.
The problem you have is how do you keep data consistency, whilst ensuring you can handle the relevant API requests (through JSON). The answer is to look at how the systems you're examining work.
I can only really vouch for Rails (it's the only framework I've got production apps for) -
--
Rails
Creating an API in Rails is so simple - I don't know why you'd think about doing anything else
Using the MVC principle might seem bloated to you, but the security, structure and extensibility it provides is unmatched.
Here is how to create an API in Rails:
#config/routes.rb
namespace :api do
   resources :controller, only: [:update, :create] #-> only PUT / POST
end

#app/controllers/api/your_controller.rb
class API::YourController < ApplicationController
   respond_to :json

   def update
      # handle PUT request
   end

   def create
      # handle POST request
   end
end

#app/models/model.rb
Class Model < ActiveRecord::Base
end

This is all you need - you'll be able to access domain.com/api/controller.json POST to create data, and domain.com/api/controller/4.json PUT to update it :)


text:
Q: IBM Rhapsody RulesComposer documentation? The ADA rules for the Code Generation of Rhapsody by default, as far as I'm understanding it, relies on this java proyect <Rhapsody Instalation path\Sodius\RiA_CG\compiled_rules\RiA_CG.jar>
I have a big problem as I need to model an statechart and the generated code contains some bindings to OXF framework. I don't want to depend on a library that I don't know, I don't know how it behaves and I don't know its maintenance.
I have been spending weeks reading about customizing code generation in Rhapsody using RulesComposer, but the official documentation is like a recipe, you follow tones of steps but what you are doing is not really explained.
If someone can share me a video or a a link to a good explanation about it, even if it is not for the ADA language, I would be very grateful.


text:
Q: Modify the URL generated with Route::apiResource without changing the name I'm building a website where users can post ads : a VueJS app that requests routes on an Laravel API.
I have an AdController, with an Ad model, and my routing is done via stuff like :
Route::apiResource('ads', AdController::class)->only(['update', 'destroy']);
Route::apiResource('ads.photos', AdPhotoController::class)->only(['index']);

which generates routes like PUT "/ads/{ad}" or GET "/ads/{id}/photos"....
This works very well, and my VueJS app uses Ziggy to call the API by their route name
axios.get(route('ads.photos.index', id))

And... It still works flawlessly ! No problem at all, and I have a LOT of routes with a LOT of API calls.
Now my problem : we realised that URLs containing "ads" are blocked by adblockers. That completely shuts down all access to our website, and asking users to turn off the adblocker is NOT a solution.
I could change my routes to do something like
Route::apiResource('posts.photos', AdPhotoController::class)->only(['index']);

but I have a LOT of routes and I really don't want to rename everything, everywhere.
Is there an option to change apiResources generated URL, so 'ads.photos.index' would generate "/posts/{id}/photos" instead of "/ads/{id}/photos" ?


text:
Q: O DEFAULT CURRENT_TIMESTAMP também atualiza o campo no UPDATE? Usando o DEFAULT CURRENT_TIMESTAMP quando for feito um UPDATE essa data também sera atualizada para a data do UPDATE?
Ou ela e fixa inserida apenas uma única vez na hora do INSERT?

A: Não, ele atualiza apenas na criação da linha.
Para atualizar tanto no insert quanto no update, são necessárias as duas declarações:

*

*DEFAULT

*ON UPDATE
Por exemplo:
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Mais detalhes no manual.
Agora, pode ocorrer de você não especificar nada na criação da tabela, e nesse caso o engine pode setar as duas condições por padrão na primeira coluna timestamp, por isso fica a sugestão de declarar explicitamente, para evitar comportamento inesperado.


text:
Q: Need help converting RLE to ASCII art The goal is to convert RLE, which is stored a text file, into ASCII Art which is printed in the console. The user has to input the name of the text file. Every time I try to change or improve my code I get an error.
Code:
def convtoASCII():
    print("\nYou have chosen Convert to ASCII\n")
    name = input("\nWhat is the name of your RLE file?")
    try:
        lines = len(open(name).readlines(  ))
        for _ in range(lines):
            line = lines
        piece = [line[i:i+3] for i in range(0, len(line), 3)]
        for part in piece:
            length = int(part[0:2])
            character = part[2]
            print(length * character, end='')
    except:
        print("\nInvalid file name. Please try again\n")
        convtoASCII()

This is the error message I get:
Traceback (most recent call last):
  File "C:\Users\ayaan\Documents\RLE to ASCII\Raw Code.py", line 100, in <module>
    welcome()
  File "C:\Users\ayaan\Documents\RLE to ASCII\Raw Code.py", line 8, in welcome
    menu()
  File "C:\Users\ayaan\Documents\RLE to ASCII\Raw Code.py", line 19, in menu
    convtoASCII()
  File "C:\Users\ayaan\Documents\RLE to ASCII\Raw Code.py", line 83, in convtoASCII
    piece = [line[i:i+3] for i in range(0, len(line), 3)]
TypeError: object of type 'int' has no len()

Any help would be appreciated
Thanks


text:
Q: How to return a string from a node js api call I have using a code snippet which will return a value  after post rest call to an api.
But where ever i am calling the function its not returning the value and  prints undefined.
when ever i will call any where getAccessToken(), its says undefiuned, but ifi print the value am getting the output.
How do the called will get the return value, do i need to change anything in the below code.
Thanks

var getAccessToken = exports.getAccessToken = function (res) {
    // body...
 const request = require('request');
 const authKey='EAcEa4o4SkBLo9IpZpW4Y7oDn7d6b30GlouNh28pJ6Q='
 const ContentType='application/x-www-form-urlencoded' ;
 var postData={
   'grant_type':'client_credentials'
 };
 const options = {
     url: 'https://xyz/v1/login',
     method: 'POST',
     headers: {
         'Content-Type': ContentType,
         'Authorization':authKey
      },
     body:require('querystring').stringify(postData)
 };
 var token;
 request(options, function(errror, response, body) {
  //console.log(JSON.parse(body));
       token= JSON.parse(body).access_token;
 });
 return token;
}

A: Your function doesn't return anything. You may use async/await, promises or callbacks to fix it.
exports.getAccessToken = async (res) => {
  ...
  return await request(...)
}

OR
exports.getAccessToken = function(res) {
  ...
  return new Promise(function(resolve, reject) {
    ...
    request(options, function(errror, response, body) {
       var token = JSON.parse(body).access_token;
       resolve(token);
    }
  });
}

// Use it like
getAccessToken().then(function(token) { ... });

OR
exports.getAccessToken = function(res, cb) {
  ...
  request(options, function(errror, response, body) {
       var token = JSON.parse(body).access_token;
       cb(token);
    }
}

// Use it like
getAccessToken(res, function(token) { ... });


text:
Q: What does 'to be a story' means? Could you explain to me, please, what the expression "You are a story" means, used in the following dialogue:
A: "You mustn't pay any attention to old Addie," she now said to the little girl.
B: "She's ailing today."
A: "Will you shut your mouth?" said the woman in bed. "I am not."
B: "You're a story."


text:
Q: Javascript null or empty string does not work I am trying to test that my string is null or empty, however it does not work.
My Code :
var veri = {
  YeniMusteriEkleTextBox: $('#MyTextbox').val(),
};

if (veri.YeniMusteriEkleTextBox === "" ||
    veri.YeniMusteriEkleTextBox == '' ||
    veri.YeniMusteriEkleTextBox.length == 0 ||
    veri.YeniMusteriEkleTextBox == null) {
  alert("Customer Name can not be empty!!!");
}

How can ı check YeniMusteriEkleTextBox is null or empty ?

A: I would use the ! operator to test if it is empty, undefined etc.
if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}

Also you do not need the comma after YeniMusteriEkleTextBox: $('#MyTextbox').val(),
Also testing for a length on an object that may be undefined will throw an error as the length will not be 0, it will instead be undefined.

A: You need to .trim the value to remove leading and trailing white space:
var veri = {
    YeniMusteriEkleTextBox: $('#YeniMusteriAdiTextbox_I').val().trim()
};

The .trim method doesn't exist on some older browsers, there's a shim to add it at the above MDN link.
You can then just test !veri.YeniMusteriEkleTextBox or alternatively veri.YeniMusteriEkleTextBox.length  === 0:
if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}

A: You should use
if (!veri.YeniMusteriEkleTextBox) {

This also checks for undefined which is not the same as null

A: Since no one else is suggestion $.trim, I will
Note I removed the trailing comma too and use the ! not operator which will work for undefined, empty null and also 0, which is not a valid customer name anyway
var veri = {
  YeniMusteriEkleTextBox: $.trim($('#MyTextbox').val())
};

if (!veri.YeniMusteriEkleTextBox) {
  alert("Customer Name can not be empty!!!");
}


text:
Q: How to find the max, min value of ALL Dataframe [ not values by column neither rows ] I know how to find in a Dataframe the max and minimum value of a column:
df.min()
df.max()

If I want to find the min and max values by row is:
df.max(index=1)
df.max(index=1)

But this return a list with the respective row or column value. I want to find the minimum or maximum value of all the dataset, only one value.
I was thinking try to iterate by row and column finding the max value But I see here that this is anti-pattern for pandas.
I am thinking in a function that only output me a value with the respective location. This function exist or I need to create?
I research answer here and not find anything related.

A: You can try:
max_val = df.max().max()


text:
Q: C# program Slowing down due to function I am writing a C# program to interface with an Arduino through a serial port and I have a function updateRPMs() that slows down the program so much it is unusable. It gets called every 1 second when it is used. The program runs a few PWM fans.
Here is the function:
private void updateRPMs()
    {
        TextBox[] RPMS = { Fan1RPM, Fan2RPM, Fan3RPM, Fan4RPM, Fan5RPM, Fan6RPM, Fan7RPM, Fan8RPM, Fan9RPM, Fan10RPM, Fan11RPM, Fan12RPM };
        List<String> sepData = new List<String>();
        if (CONNECTED)
        {
            String data = serialPort1.ReadLine();
            // MessageBox.Show(data);

            sepData = (data.Split(';').ToList());

            if (sepData.Count == 12)
            {
                for (int i = 0; i < 12; i++)
                {
                    RPMS[i].Text = sepData[i];
                }
            }
            serialPort1.DiscardOutBuffer();
        }

    }

This is something the Arduino would send to the program:
a840.00;b885.00;c0;d0;e0;f0;g1635.00;h2070.00;i0;j0;k0;l0

I know I can push this to a different thread but I am trying to have it update as soon as the timer fires.
I was wondering if there is anything I could change or if there was anything stupid I did. I am new to C# and any help would be appreciated.

A: For reading from serial, I suggest you to avoid using a timer to read from the serial. You can use the DataReceived event, which is fired every time some data is received from the serial.
Of course you could receive a partial packet, so it's better to store the data in a buffer and then analyze it.
String readBuffer = "";

private static void DataReceivedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    readBuffer += sp.ReadExisting();

    int newLineIndex = -1;
    while ((newLineIndex = readBuffer.IndexOf("\n")) >= 0)
    { // Analyze buffer
        String currentLine = readBuffer.Substring(0,newLineIndex);
        if (currentLine.length() > 0)
            analyzeLine(currentLine);
        readBuffer = readBuffer.Substring(newLineIndex+1);
    }
}

public void analyzeLine(String data)
{
    static TextBox[] RPMS = { Fan1RPM, Fan2RPM, Fan3RPM, Fan4RPM, Fan5RPM, Fan6RPM, Fan7RPM, Fan8RPM, Fan9RPM, Fan10RPM, Fan11RPM, Fan12RPM };
    List<String> sepData = (data.Split(';').ToList());
    if (sepData.Count == 12)
    {
        for (int i = 0; i < 12; i++)
        {
            RPMS[i].Text = sepData[i];
        }
    }
}

I assume you know how to attach to an event, since you already used the timer one ini your code ;)


text:
Q: how to hide user id and other parameters in a jsp url? I have a URL using which users access my jsp web application
http:/testerpages.com/testpage/menu1?userId=27
how can i hide userID=27 from users and show the url something like
http://testerpages.com/testpage/menu1
is there any method by which we can hide parameters from users or we can just ignore the ids but there is a threat for security if we show id parameters in a url directly to front end users
i m calling this page using
Menu1

A: HEX(AES_ENCRYPT(userid,'"key"'))

use it in your sql or mysql query that will aes encrypt your userid i made use of it in mysql
that should solve your problem

A: You could transfer this parameters als GET whicht don't show in the url, but are also very easy to read and modify. Instead I would use some kind of encrytion and validation code for session ids. This would prevent users and attackers from accesing other users sessions.

A: You could store the user ID in the session after the user logged in. When a user accesses the menu page, you can still get the ID from the session, and you will not need to put it into the URL.


text:
Q: Connect separate Git repositories to virtual applications in Azure I have a regular web site (app service) in Azure which is connected to a Git repository. Now I would like to add virtual applications for APIs which reside in their own repositories.
So this is basically what I want to achieve:
Repository 1 -> MyWebSite
Repository 2 -> MyWebSite/api1
Repository 3 -> MyWebSite/api2
...

From what I have heard, this is possible with the help of Git subtrees. However, I would like to keep the repositories totally separate if possible, and deploy the projects individually with continuous delivery.


text:
Q: How to filter output of all existing stored procedures in SQL Server? I have many stored procedures in my SQL Server database, and about 90% of them return a table. The database has been created for storing data of a C# project.
In a scenario, from application side when I call a procedure, I want to be able to apply some general filter to process the output. For example get top 100 records of the output. This filter should be done for every procedure, so I have built a single and common static class which it is only point that calls the procedure in my app. Then I filter every output in there and return it.
Ok this work for me but it is not efficient, because database returns redundant rows which they will be filtered in app side.
I decided to improve the job. I'm thinking about migrating the filter to be applied on the database side, but without modifying any existing procedure.
My idea is that I create a RunnerProcedure in the database which gets the procedure name and its parameters, runs it, applies my general filter and finally returns the resulting output.
For example my general filter might be:
select top 100 * from output

So in this approach, I have to implement something like this:
CREATE PROCEDURE RunnerProcedure
AS
    @ProcedureName nvarchar(max),
    @ProcedureParameters dbo.ProcedureParametersTableType READONLY
BEGIN
 ...
 // @output = execute @ProcedureName with @ProcedureParameters
 Select top 100 * from (@output)
 I don't have any idea in implementation! please help.
 ...
END

I talked my idea to explain what I want exactly. If it is possible please let me know how. Complete it please. Or if it's not possible, please let me know your suggestions.
Thanks

A: go for a stored procedure created in managed code.
build a c# library that contain the code you already have, put it on the server and then 'wrap' it in a stored procedure as documented in the linked msdn page.
all the calls from the application will be routed through the 'c# stored procedure' that will filter the records on the server.
i don't see a big advantage from load perspective because the full recordset is produced anyway and the server is now responsible for output cutting but the amount of data transferred on the network would be reduced.

A: You can try something below
SELECT * INTO #temptable
FROM OPENROWSET('SQLNCLI', 'Server=loclhost;Trusted_Connection=yes;', 'exec procedurename')

SELECT TOP 100 * FROM #temptable


text:
Q: Google Chrome doesn't open on click "View in Browser" Using Visual Studio 2019 for ASP.Net application, when I right click and choose "View in Browser (Chrome Browser)" it doesn't open or no response whereas when I change and set default as internet explore "View In Browser (Internet Explorer)" it work fine. Anyone know how to fix this?

A: drop down
click the drop down in the run and debug button and make sure chrome is selected,
Hope this helped


text:
Q: How to run Mojolicious on OpenShift? I already tried https://github.com/degtyarev-dm/mojolicious-lite-openshift but no luck
it returns 500 error page.
Does anyone know how to run Mojolicious on OpenShift ?
I also tried PerlDancer example, and it run well. But it run on Plack (with PSGI, I don't really understand about PSGI).
Can I use morbo / myapp.pl daemon / plackup command from shell script to start as worker on OpenShift ?

A: Finally I know how to run Mojolicious on OpenShift:
https://github.com/dns/OpenShift-DIY-Perl
Unfortunately unlike heroku, OpenShift block every port except 80 & 443.
The cool things about Openshift, they give 1GB database (shared with app). And mojolicious app can handle file upload. (for comparison: Heroku only give 6MB database & can't handle file upload)
Currently OpenShift using Apache 2.2 with mod_perl.


text:
Q: Does Using React Context API In NextJS App Disable Static Site Generator? I've got some questions about nextJS and SSG (static site generator)
1 - I want to manage my app state globally so I want to use react's context api. As I understand using redux in next js app disables SSG. If I use react context api does that disable too?
2 - I know that I can do server side rendering but I want to have a custom nodejs server that I created from scratch. And I want to fetch data from my nodeJS server in the client side. Does making that way disable SSG and bad for performance?

A: This documentation will help you clarify your understanding on how Next.js handles automatic static optimization. Take a look at the caveats in that documentation to understand when that gets disabled at a global level.
Beyond that, whether or not each individual page behaves as SSG, ISR, SSG + CSR or SSR is a matter of the data requirements of the individual page. See this documentation to better understand the different ways Next.js handles each page depending on the data requirements.
Now, to answer your two questions directly:

*

*I cannot find any indication that using Redux in Next.js disables SSG. In fact, here is an official example using Redux to illustrate both an SSG and SSR Next.js page implementation. Same goes for the react context API. On the other hand, it is entirely possible for you to unintentionally disable SSG by both using Redux / react context while requiring dynamic data in your page. Read up on the documentation linked in the second paragraph above to understand this better.

*Fetching data from your custom NodeJS server client-side does not necessarily disable SSG. It will disable SSG if you require dynamic data on each page load. You have the choice to either statically generate your page (SSG + CSR) and then request your data client-side post page load (think axois / browser fetch API + loading indicator); OR, if you need the data to be present immediately upon page load (SSG & SSR), you can use getStaticProps + getStaticPaths to inject that data at build time (SSG) or getServerSideProps to inject the data on each page load (SSR).


text:
Q: HTLM with Bootsrap, Images & css to PDF in .NET Core 3.1 I was using below mentioned JavaScript function for export HTML to PDF, even though. css and splitting the page as of break also not working. can anybody help me to solve this issue.
 function generatePDF() {
    var doc = new jsPDF();  //create jsPDF object
    doc.fromHTML(document.getElementById("divMainScreen"), // page element which you want to print as PDF
        15,
        15,
        {
            'width': 170  //set width
        },
        function (a) {
            doc.save("VehicleInspection.pdf"); // save file name as VehicleInspection.pdf
        });
}

HTML:

            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="red" class="bi bi-caret-right-fill" viewBox="0 0 16 16">
                <path d="m12.14 8.753-5.482 4.796c-.646.566-1.658.106-1.658-.753V3.204a1 1 0 0 1 1.659-.753l5.48 4.796a1 1 0 0 1 0 1.506z" />
            </svg>
            DATE : 08/09/2021

//--USING FOR BREAK PAGE

          //--Body Content


text:
Q: Three set object in front of camera in a dolly I'm placing an object in front of the camera using
        var dist = -100;
        var vec = new THREE.Vector3( 0,  0, dist );
        vec.applyQuaternion( camera.quaternion );
        object.position.copy( vec );
        object.lookAt(camera.position);

This works really well.
I'm now having to rotate the camera (its for a VR video player) to set it's starting position and to do that and still work with WebVR boilerplate, I add the video to a dolly object and rotate that.
    dolly = new THREE.Group();
    dolly.position.set( 0, 0, 0 );
    scene.add( dolly );

    camera.up.set( 0, 1, 0 );
    dolly.add( camera );

And the object is now not in front of the camera. I'm trying to apply the dolly rotation to the vector to account for that angle.
        var rotation = new THREE.Euler().setFromQuaternion( camera.quaternion, camera.rotation.order );
        rotation.y += dolly.rotation.y;
        var quat = new THREE.Quaternion().setFromEuler(rotation, camera.rotation.order);
        vec.applyQuaternion( quat );

This mostly works when  the camera is particular angles but sometimes not and the object is also rotated on it's x axis.
I assume   rotation.y += dolly.rotation.y; is wrong but I'm not sure of a better way to merge the numbers.

A: @WestLangleys answer on here
three.js tween object to front of camera
Answered my question
      var pLocal = new THREE.Vector3( 0, 0, dist );

        var target = pLocal.applyMatrix4( camera.matrixWorld );

        object.position.copy( target );
        object.lookAt(camera.position);


text:
Q: Screenshot Taker on Windows 7 (or any platform, if possible) using C/C++ I want to code a program in C++ that takes screenshots and saves them. Can you suggest any sources to refer to?

A: I've seen several applications of this nature. Don't forget to include your platform.
http://www.rohitab.com/discuss/topic/22809-screenshot-c/
Screenshots in X11
Several things pop up instantly from Google =]


text:
Q: Save UIWebView Access to Current Location A UIWebView in my app is loading up a site that is requesting access to the user's location.  In Safari, it stores this preference and does not ask it again, but in my app, it continues to ask every time.  Is there a way to store the user's preference on this so they are not asked every time they use the app?

A: It looks like this cannot be done under the current OS (iOS 4.0).


text:
Q: Volley upload image using PHP I am trying to upload image from android app using Google Volley to the server but for some reason the SQL command to insert the URL to database and upload doesn't work. The rest of the commands as well as the code in android seems to be working. But the response is incorrect. Check the else statement below highlighted by comment, that statement is executed for some reason whatever I do.
<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){

 $image = $_POST['image'];
 $name = $_POST['name'];
 ...
 $conn = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect to db');

 $sql ="SELECT id FROM volleyupload ORDER BY id ASC";

 $res = mysqli_query($conn,$sql);

  $id = 0;

  while($row = mysqli_fetch_array($res)){
    $id = $row['id'];
  }

  $path = "uploads/$id.png";

   $actualpath = "http://myurl.co/prak/$path";

   $sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";

   if(mysqli_query($conn,$sql)){
      file_put_contents($path,base64_decode($image));
      echo "Successfully Uploaded";
   } else{
       echo "ERROR in insertion to DB!"; //THIS ERROR COMES UP
     }

   mysqli_close($conn);
 }else{
 echo "Error";
  }

 ?>

The tutorial I am following for volley image upload is here: https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Please let me know what's the problem and if there is an issue with the question do let me know that as well.

A: Fact that else branch is always entered means that mysqli_query($conn,$sql) function result is FALSE.
This is most likely caused by problem with your SQL statement. Fortunately there is a way to find out where exactly the problem origins - you can use mysqli_error($conn) to find out where the issue is exactly.
Possibly by adjusting your code to something like this:
    if(mysqli_query($conn,$sql)){
      file_put_contents($path,base64_decode($image));
      echo "Successfully Uploaded";
   } else{
       echo "ERROR in insertion to DB:" . mysqli_error($conn); //THIS ERROR COMES UP
     }


text:
Q: Make a forward from one UART to another UART I am working with the TI TM4C MCU. Connected to one UART of this MCU, I have a GSM module or a GPS Module (let's say UART1). I need to establish communication between the MCU and the module by sending some "AT commands" and receiving some replies to verify what the module is doing.
Therefore I need to see what AT commands are sent by the MCU to the module and I need to see what the module replies to the MCU. Of course those commands are defined via C files, but I need to check what is sent when and how and what is received when and how.
I suppose that I can not use CCS to visualize those data flow, correct?
Therefore to achieve this, I am thinking to use MCU UART0 and connect that to my computer, where I use "Tera Term" software to receive a copy of what is sent and received by the MCU on UART1.
I am not an expert in C but I have some notion of it. I found some example of UART use in the TI lab workshop for TM4C, but I am not sure fully about how to implement this "forwarding" (copy like). I think I need to copy the value in the FIFO/ buffer of the UART1 to UART0 and then sent them to UART0.
I am a bit confused about how to operate it.
I would appreciate if someone got experience about it to explain how you usually process to analyze sending and receiving of data via UART, which are not directly linked to a computer terminal.

A:
I am not sure fully about how to implement this "forwarding" (copy like)

An (often quicker) alternative to this type of software "forwarding" approach, is to monitor the two signals you mention, directly via hardware.
I'm short of time, so excuse the lack of a diagram at the moment. In brief:
MCU Tx -> GSM module Rx -> Here connect Rx of UART-to-USB adapter 1
MCU Rx <- GSM module Tx -> Here connect Rx of UART-to-USB adapter 2
Note: You only connect the Rx inputs of those two UART-to-USB adapters. Leave the Tx pins of those adapters unconnected.
Then you can monitor (and, although I've forgotten the name at the moment, I'm sure I've used software to merge or view) these two data streams on a PC. You could even run two simultaneous copies of "Tera Term" as you suggested, one opening the PC COM port for UART-to-USB adapter 1; the other opening the PC COM port for UART-to-USB adapter 2.
This avoids adding complexity at the MCU now. You can add this MCU functionality later, if you need to and when you have learned those programming skills. However during development, using hardware monitoring can be a quicker way to achieve the end result (i.e. monitoring those serial data streams) which you want.

A: A totally different approach would be to use a JTAG debugger connection (if you have one) back to the PC - if you don't mind that you wouldn't be using UART0 for the PC connection. (Thanks to Chris Stratton for comments on my other suggestion, which reminded me about this possibility.)
If your TM4C is connected via JTAG to a typical USB-JTAG debugger (I use Segger, but I believe the debugger built-in to the TM4C Launchpad has similar functionality), then you can send simple text strings back to the host, to be displayed in a debugger window (the presentation of the data depends on your PC software & toolchain).
It would be easy to duplicate any sending of data to your UART1 also to the Cortex-M ITM port in the TM4C. A common approach is to write (or use, if already included in your toolchain) a simple printf() routine which writes to the ITM port and can be called like any other C function. Then, when you receive any data from your external GPS/GSM module, your MCU code again uses printf() to send that data to the ITM port and therefore to the PC.
You would need to create some type of encoding to differentiate the "send" and "receive" data, as you printf() both of them to the ITM port e.g. prefix a string sent to the external module with "S:" when you printf() it to the PC, so that on the PC you can see it was Sent to the module. Something similar with characters Received from the module.
This is just another approach, with pros and cons, compared to my previous suggestion, or compared to forwarding to another UART on the MCU. Depending on what you really want to do (i.e. do you really want to learn UART programming, or do you really want to monitor the data you mentioned; do you mind doing some more MCU programming or do you prefer a solution which is mostly hardware and no additional MCU programming), then you have options. As is typical in engineering, there is no single "one size fits all" solution - you have various options, with different compromises, from which you can choose. :-)


text:
Q: feathers.js - saving one record to multiple databases - mysql and elastic search I have built an app with Feathers.js and I'm trying to find the way, how can I save any record to the multiple databases? I would like to save a "message" for example to the mysql and also to the elastic search.
I would like to use elastic search for "full text" search, but I would also like to have all data saved in some relational database.
I've created a service using:
feathers generate service
but I can select only one specific database there.
Any help will be really appreciated.

A: Fast way to me is to create another feathers app (microservice) for elasticsearch and post the data to elasticsearch too.
If you are using socket in the frontend app you can define 2 sockets (1 for each micro service).
When you post new data to feathers app 1 (mysql) you can :

*

*on response of the data created post the same data to feathers app 2 (elasticsearch)

*on error abort and correct

or

*

*add a service('your_post_service').on('created', ... and then post data to feathers app 2 (elasticearch)


text:
Q: How to run a script every hour, on the hour only on weekdays using time-based trigger? I need to run a Google App Script script every hour on the hour only on weekdays.
It seems easy to do one of the two, but to combine it I'm not sure...
The hourly trigger:
ScriptApp.newTrigger("RefreshRates").timeBased().inTimezone("GMT").everyHours(1).nearMinute(0).create();
It needs to run every hour as close as possible to the hour.
So for example 09:00, 10:00, 11:00 etc. I know App Script not very accurate with this but then just as close as possible to the hour.
I found this that might help with the weekdays issue, but is it possible to then combine the above with something like this:
 function createWeeklyTrigger() {
    var days = [ScriptApp.WeekDay.MONDAY, ScriptApp.WeekDay.TUESDAY,
                ScriptApp.WeekDay.WEDNESDAY, ScriptApp.WeekDay.THURSDAY,
                ScriptApp.WeekDay.FRIDAY];
    for (var i=0; i<days.length; i++) {
       ScriptApp.newTrigger("your_function_name")
                .timeBased().onWeekDay(days[i])
                .atHour(11).create();
    }
 }

Ideal is actually Friday 9:45 pm till 10:15pm Sunday GMT, when Forex markets close and open...
Edit:
I think I made something not very clear in my initial question about every hour every weekday, not certain hours. But the week for markets start 22:00 Sunday GMT and ends Friday 22:00 GMT. Thus the ideal is from Sunday 22:00 GMT until Friday 22:00 GMT every hour around the hour...

A: Your best choice, I think, would be setting a Trigger to each hour you want the script to run at, using a second loop inside the one that sets weekdays, since everyHours() does not accept start and end arguments.
Please, note that this will create separate triggers that fire on the same day of the week.
function setWeekdaysTrigger() {

  var startHour = 9;
  var endHour   = 13;
  var daysWeek  = []; //put Enums for days of the week here;

  //set trigger to specific week days;
  daysWeek.forEach(function(day){
    //set trigger for 9AM to 13PM;
    for(var h=startHour; h<endHour; h++) {
      var tg = ScriptApp.newTrigger('doSomething').timeBased();
          tg.onWeekDay(day);
          tg.atHour(h).nearMinute(15).create(); //arbitrary precision (minutes);
    }
  });

}

As an update to the answer - please, note that, unfortunately, there are quotas on how many triggers you may create for the project on behalf of one user (currently equals to 20 per user per project).
Configurable triggers
As clarified in comments, configuring custom-days + custom-hours triggers requires a more sophisticated handling. Proposed solution (not counting explicit date-time checks) is dynamic trigger configuration (since one cannot set both the onWeekDay(day) + everyHours(n) due to recurrence overlapping [I found that onWeekDay(day) sets implicit everyWeeks(1) recurrence pattern]):
First, create a main trigger function that sets days recurrence
function custom24trigger() {
  var days  = [ScriptApp.WeekDay.TUESDAY]; //put Enum values here;

  //create trigger for each date (arbitrary hours);
  days.forEach(function(day){
    for(var offset = 0; offset < 23; offset=offset+4) { //every 4 hours;
      var tg = ScriptApp.newTrigger('changeTriggers').timeBased();
          tg.onWeekDay(day).atHour(offset).create(); //change every N hours;
    }
  });

}

Secondly, create a trigger change function that will be fired with set recurrence, which clears previously set triggers and creates new ones:
function changeTriggers() {
  var triggers   = ScriptApp.getProjectTriggers(); //get project's triggers;
  var props      = PropertiesService.getScriptProperties(); //get script properties store;
  var triggerIds = props.getProperty('triggerIds'); //get arbitrary property to set Ids to;

  //if ids are not empty, split into Array of Ids, else set up empty Array;
  if(triggerIds!==null) { triggerIds = triggerIds.split(','); }else { triggerIds = []; }

  //loop over triggers and delete saved;
  triggerIds.forEach(function(id){
    triggers.forEach(function(trigger){
      if(trigger.getUniqueId() == id) {
        ScriptApp.deleteTrigger(trigger);
      }
    });
  });

  var today = new Date(); //current date;
  var start = today.getHours(); //current hour;

  var stop = start+3; //hour to stop (sets N triggers);

  //create hourly trigger for each hour;
  var newId = '';
  for(var h = start; h < stop; h++) {
    var trg = ScriptApp.newTrigger('doSomething').timeBased();

    //make trigger fire once at specific date and hour;
    today.setHours(h);
    today.setMinutes(0);

    var created = trg.at(today).create();
    newId += ','+created.getUniqueId(); //get new trigger Id;
  }

  props.setProperty('triggerIds', newId); //set trigger property;
}


text:
Q: Forming a magic square We define a magic square to be an  matrix of distinct positive integers from  to  where the sum of any row, column, or diagonal of length  is always equal to the same number: the magic constant.
You will be given a  matrix  of integers in the inclusive range . We can convert any digit  to any other digit  in the range  at cost of . Given , convert it into a magic square at minimal cost. Print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range .
For example, we start with the following matrix :
5 3 4
1 5 8
6 4 2
We can convert it to the following magic square:
8 3 4
1 5 9
6 7 2
This took three replacements at a cost of .
5-8 + 8-9 + 4-7 = 7
I Have Write a programm to slove this but i get the incorrect result when i try to run it.
def formingMagicSquare(s):
    arr=[]
    duplicates=[]
    totaldifference=0
    for i in range(0,len(s)):
        linesum=sum(s[i])
        for j in range(0,len(s[i])):
            if(s[i][j] in arr and linesum!=15):
                duplicates.append(i*10+j)
            else:
                arr.append(s[i][j])
    for i in range(0,len(duplicates)):
        iarr = duplicates[i]//10
        jarr = duplicates[i]%10
        linesum=sum(s[i])
        difference=15-linesum
        totaldifference = totaldifference + difference
    return totaldifference

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = []

    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))

    result = formingMagicSquare(s)

    fptr.write(str(result) + '\n')

    fptr.close()

A: class Magic(object):

    pre = [
            [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
            [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
            [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
            [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
            [[8, 3, 4], [1, 5, 9], [6, 7, 2]],
            [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
            [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
            [[2, 7, 6], [9, 5, 1], [4, 3, 8]],
            ]

    def evaluate(self, s):
        totals = []
        for p in self.pre:
            total = 0
            for p_row, s_row in zip(p, s):
                for i, j in zip(p_row, s_row):
                    if not i == j:
                        total += max([i, j]) - min([i, j])
            totals.append(total)
        return min(totals)
def main():
    s=[]
    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))

    magic = Magic()
    result = magic.evaluate(s)

    print(result)

if __name__ == '__main__':
    main()

Thank You I Have Write A new Code And I Have Change my code from the base.

A: I think you can easily try:
def forming_magic_square(s):

    # Flaten s
    s = list(itertools.chain.from_iterable(s))

    magic_squares = [
        [8, 1, 6, 3, 5, 7, 4, 9, 2],
        [6, 1, 8, 7, 5, 3, 2, 9, 4],
        [4, 9, 2, 3, 5, 7, 8, 1, 6],
        [2, 9, 4, 7, 5, 3, 6, 1, 8],
        [8, 3, 4, 1, 5, 9, 6, 7, 2],
        [4, 3, 8, 9, 5, 1, 2, 7, 6],
        [6, 7, 2, 1, 5, 9, 8, 3, 4],
        [2, 7, 6, 9, 5, 1, 4, 3, 8],
    ]

    costs = []
    for magic_square in magic_squares:
        costs.append(sum([abs(magic_square[i] - s[i]) for i in range(9)]))

    return min(costs)


text:
Q: Need to Open MDF file in MS Office 365 Access I found links to this topic on this and other sites but have had no luck. I know a lot of code but I am REALLY out of my wheelhouse here so please provide very specific instructions if possible.
I would like to import this SQL Server .MDF database file (200 MB) into Access tables (or link to the external SQL Server tables, so that I can transfer the data within Access).
I installed SQL Server Management Studio (thought I needed to) but cannot figure out how to get it to connect to the DB... then I think I would need to use the external data ODBC option in access to connect from there but I haven't been able to get anything to work...
This is a one-time need so any creative workaround would be acceptable also...
Any help that you can provide would be greatly appreciated. Thanks!!

A: Install SQL Server Express With Tools (2012 should be fine).
When you install this, include the following features:
Database Engine and Management Tools - Basic.
Once you have this installed, open SQL Server Management Studio (Run > ssms.exe).
As marc_s said, you'll need to attach the .MDF file to your SQL Server.
I usually copy the MDF file to C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA so when I attach the database, it's the first folder that's open.
Next, in Access 2013, use the Data Import wizard to connect to SQL Server.  You'll need to enter the SQL Server name and instance, usually "localhost\SQLExpress" works for a default SQL Express install.
Follow the Wizard, and it'll allow you to pick which tables/views you want to use.
You can also do this in Excel first, then save the data as .csv or something similar, then import the CSV into Access.


text:
Q: Git merge results in 400 rename/rename conflicts, how do I resolve them quickly? So, I have a number of Wordpress sites managed with a Git repository, all of which are branches off of a central upstream Git repository. I recently applied a bunch of updates to the parent repo, but one of the child website repos had a plugin updated to a different version and now throws up about 400 rename/rename conflicts. All of these conflicts are in an upstream plugin directory that would be safe to just resolve in favor of the upstream branch.
I want to do the following:

*

*Ensure the upstream version of the files 'wins' the merge conflict (e.g. what the --theirs flag does with checkout)

*Produce a mergeable history (If it's not safe for a coworker to type "git pull origin master" with an old repo, it's not an option. I'm religiously opposed to rebasing.)

*Not restructure my Git repository (My hosting provider, Pantheon, will not install Composer dependencies at deploy time. Upstream plugins have to be part of the repo.)

*Not get a repetitive stress injury (Has to be a reasonably small number of commands because I have to resolve these kinds of messes once a month or so.)

If I just type "git checkout wp-content/plugins/** --theirs", I get hit in the face with about 400 errors, and Git refuses to checkout the files. They look like this:
....400 or so errors omitted...
error: path 'wp-content/plugins/wordpress-seo/js/dist/wp-seo-quick-edit-handler-710.min.js' does not have their version
error: path 'wp-content/plugins/wordpress-seo/js/dist/wp-seo-quick-edit-handler-720.min.js' does not have their version
error: path 'wp-content/plugins/wordpress-seo/js/dist/wp-seo-recalculate-710.min.js' does not have their version
error: path 'wp-content/plugins/wordpress-seo/js/dist/wp-seo-recalculate-720.min.js' does not have their version

I categorically refuse to type 400 git rm/git add commands with each individual path included. git checkout --force is not an option, as --theirs and --force are mutually incompatible (for some reason). My current solution is to open Git GUI and manually right-click -> Use Remote Version and then click Yes... 400 times. I don't have to type the path at least but this is still time consuming.
How do I efficiently resolve a large number of rename/rename conflicts in favor of the remote repository?

A: Do you want to just resolve the conflicted files in favour of the remote, or just take a whole tree as it is in the remote?
For the latter, you could do this:

*

*Just accept the files as-is with conflicts. git add . or similar

*Commit the merge.

*rm -Rf path/in/question

*git checkout origin/branch -- path/in/question

*git commit --amend -a
For the former, it's probably something pretty similar

*

*Just accept the files as-is with conflicts. git add . or similar

*Commit the merge.

*Find files with conflicts. e.g. grep -r -l '>>>>' path/in/question > /tmp/conflicts.txt

*Delete the files with conflicts, check out the desired versions, and amend the commit in a similar means to the above.

(If there are files/paths with spaces in them, small adjustments to the above commands may be necessary. I've given the simpler versions for clarity.)


text:
Q: Java Servlet работа с Json Недавно начал изучать servlet. На данный момент на томкате развернут проект с одной jsp страничкой. Есть база данных MySQL.
Не совсем понимаю, как реализовать общение клиента с сервером.

*

*Правильно ли я понимаю, что, на данный момент, клиентская часть - это jsp страничка, а сам сервлет и все остальное - серверная?

*Если это так, то я должен отправлять и принимать на клиенте json объекты. Как это правильно делается?


text:
Q: bloc state is the same after coming back to a page even though it was explicitly changed I have a widget that utilizes CourseBloc
class CourseBloc extends Bloc<CourseEvent, CourseState> {
  final GetCoursesQuery getCoursesQuery;
  final GetSettingsQuery getSettingsQuery;
  final PullCoursesFromServerCommand pullCoursesFromServerCommand;
  final UpdateTasksToServerCommand updateTasksToServerCommand;
  final GetNetworkInfoQuery getNetworkInfoQuery;

  CourseBloc({
    @required GetCoursesQuery getCoursesQuery,
    @required GetSettingsQuery getSettingsQuery,
    @required PullCoursesFromServerCommand pullCoursesFromServerCommand,
    @required UpdateTasksToServerCommand updateTasksToServerCommand,
    @required GetNetworkInfoQuery getNetworkInfoQuery,
  })  : assert(getCoursesQuery != null),
        assert(getSettingsQuery != null),
        assert(pullCoursesFromServerCommand != null),
        assert(updateTasksToServerCommand != null),
        assert(getNetworkInfoQuery != null),
        this.getCoursesQuery = getCoursesQuery,
        this.getSettingsQuery = getSettingsQuery,
        this.pullCoursesFromServerCommand = pullCoursesFromServerCommand,
        this.updateTasksToServerCommand = updateTasksToServerCommand,
        this.getNetworkInfoQuery = getNetworkInfoQuery;

  @override
  CourseState get initialState => CourseInitialState();

  @override
  Stream<CourseState> mapEventToState(
    CourseEvent event,
  ) async* {
    if (event is CoursesReturnedFromTasksEvent) {
      yield CourseInitialState();
    } else if (event is CoursesPageLoadedEvent) {
      yield CourseLoadingState();

      final getCoursesEither = await getCoursesQuery(
        GetCoursesParams(
          truckNumber: event.truckNumber,
        ),
      );

      yield* getCoursesEither.fold((failure) async* {
        yield CourseFetchedStateFailureState(error: "coursesDatabaseError");
      }, (result) async* {
        if (result != null) {
          final getSettingsEither = await getSettingsQuery(NoQueryParams());

          yield* getSettingsEither.fold((failure) async* {
            yield CourseFetchedStateFailureState(error: "coursesDatabaseError");
          }, (settingsResult) async* {
            if (result != null) {
              final networkInfoEither =
                  await this.getNetworkInfoQuery(NoQueryParams());

              yield* networkInfoEither.fold((failure) async* {
                yield CourseErrorState();
              }, (success) async* {
                yield CourseFetchedState(
                  settings: settingsResult,
                  courses: result,
                  isThereInternet: success,
                );
              });
            } else {
              yield CourseFetchedStateFailureState(
                  error: "coursesFetchFromDatabaseError");
            }
          });
        } else {
          yield CourseFetchedStateFailureState(
              error: "coursesFetchFromDatabaseError");
        }
      });
    } else if (event is CoursesRefreshButtonPressedEvent) {
      yield CourseLoadingState();

      final networkInfoEither = await this.getNetworkInfoQuery(NoQueryParams());

      yield* networkInfoEither.fold((failure) async* {
        yield CourseErrorState();
      }, (success) async* {
        if (success) {
          final updateTasksToServerEither = await updateTasksToServerCommand(
              UpdateTasksParams(truckNumber: event.truckNumber));

          yield* updateTasksToServerEither.fold((failure) async* {
            yield CourseFetchedStateFailureState(error: "coursesDatabaseError");
          }, (result) async* {
            final pullCoursesFromServerEither =
                await pullCoursesFromServerCommand(
                    PullCoursesParams(truckNumber: event.truckNumber));

            yield* pullCoursesFromServerEither.fold((failure) async* {
              yield CourseFetchedStateFailureState(
                  error: "coursesDatabaseError");
            }, (result) async* {
              if (result != null) {
                yield CoursePulledFromServerState();
              } else {
                yield CourseFetchedStateFailureState(
                    error: "coursesFetchFromDatabaseError");
              }
            });
          });
        } else {
          yield CourseNoInternetState();
        }
      });
    } else if (event is CoursesRefreshFromTasksButtonPressedEvent) {
      serviceLocator<TaskBloc>().add(
        TasksLoadingEvent(),
      );

      final networkInfoEither = await this.getNetworkInfoQuery(NoQueryParams());

      yield* networkInfoEither.fold((failure) async* {
        serviceLocator<TaskBloc>().add(
          TasksReloadingErrorEvent(),
        );
      }, (success) async* {
        if (success) {
          final updateTasksToServerEither = await updateTasksToServerCommand(
              UpdateTasksParams(truckNumber: event.truckNumber));

          yield* updateTasksToServerEither.fold((failure) async* {
            yield CourseFetchedStateFailureState(error: "coursesDatabaseError");
          }, (result) async* {
            final pullCoursesFromServerEither =
                await pullCoursesFromServerCommand(
                    PullCoursesParams(truckNumber: event.truckNumber));

            yield* pullCoursesFromServerEither.fold((failure) async* {
              serviceLocator<TaskBloc>().add(
                TasksFetchedFailureEvent(failure: "coursesDatabaseError"),
              );
            }, (result) async* {
              if (result != null) {
                serviceLocator<TaskBloc>().add(
                  TasksPulledFromServerEvent(
                    truckNumber: event.truckNumber,
                    courseNumber: event.courseNumber,
                    courseId: event.courseId,
                  ),
                );
              } else {
                serviceLocator<TaskBloc>().add(
                  TasksFetchedFailureEvent(
                      failure: "coursesFetchFromDatabaseError"),
                );
              }
            });
          });
        } else {
          yield CourseNoInternetState();
        }
      });
    }
  }
}

I use BlocBuilder and BlocListener in the widget page as follows:
BlocBuilder<CourseBloc, CourseState>(
   builder: (context, state) {
     if (state is CourseFetchedState) {
     // here I have logic if the course is fetched
   }
...
),

BlocListener<CourseBloc, CourseState>(
   listener: (context, state) {
     if (state is CourseNoInternetState) {
     ...
   }
...
),

At some point I am navigating away of this widget. Then I want to come back to this first (Course) widget. I do:
serviceLocator<CourseBloc>().add(
     CoursesReturnedFromTasksEvent(),
);

serviceLocator.resetLazySingleton<TaskBloc>(
     instance: serviceLocator<TaskBloc>(),
);

Navigator.of(context).pop(true);

This tells the CourseBloc to expect a CoursesReturnedFromTasksEvent() , resets the new TaskBloc (because I am not on this page anymore and I don't need to know what state is it at) and pops the current context.
Then I am navigated back. The CourseBloc's mapping method works with the new state and according to the 'if' it yields:
if (event is CoursesReturnedFromTasksEvent) {
  yield CourseInitialState();
}

But the Builder in the Course page is at the previous state. CourseFetchedState. And it has not 'taken' the new state (Initial).
Any ideas why that might happen?
Here are the States:
abstract class CourseState {
  CourseState();
}

class CourseInitialState extends CourseState {}

class CourseReturnedFromTasksState extends CourseState {}

class CourseLoadingState extends CourseState {}

class CourseErrorState extends CourseState {}

class CourseNoInternetState extends CourseState {}

class CoursePulledFromServerState extends CourseState {}

class CourseFetchedState extends CourseState {
  final SettingsAggregate settings;
  final List<CourseAggregate> courses;
  final bool isThereInternet;

  CourseFetchedState({
    @required this.settings,
    @required this.courses,
    @required this.isThereInternet,
  });
}

class CourseFetchedStateFailureState extends CourseState {
  final String error;

  CourseFetchedStateFailureState({@required this.error});
}

And Events:
abstract class CourseEvent {
  CourseEvent();
}

class CoursesRefreshButtonPressedEvent extends CourseEvent {
  final String truckNumber;

  CoursesRefreshButtonPressedEvent({@required this.truckNumber});
}

class CoursesRefreshFromTasksButtonPressedEvent extends CourseEvent {
  final String courseNumber;
  final String truckNumber;
  final int courseId;

  CoursesRefreshFromTasksButtonPressedEvent({
    @required this.courseNumber,
    @required this.truckNumber,
    @required this.courseId,
  });
}

class CoursesReturnedFromTasksEvent extends CourseEvent {}

class CoursesPageLoadedEvent extends CourseEvent {
  final String truckNumber;

  CoursesPageLoadedEvent({
    this.truckNumber,
  });
}

EDIT
Here is how the Bloc is provided:
Column buildBody(BuildContext context) {
    return Column(
      children: <Widget>[
        BlocProvider(
          create: (_) => serviceLocator<CourseBloc>(),
          child: BlocBuilder<CourseBloc, CourseState>(
            builder: (context, state) {
              if (state is CourseFetchedState) {
              ...
              }
            ...
            }
           ),
          ),
         ],
        );
       }

The serviceLocator() is instantiated only once, at app startup. It registers all instances needed throughout the app life in order to achieve dependency injection. Here is the CourseBloc registration:
import 'package:get_it/get_it.dart';

final serviceLocator = GetIt.instance;
...
serviceLocator.registerLazySingleton(
    () => CourseBloc(
      getCoursesQuery: serviceLocator(),
      getSettingsQuery: serviceLocator(),
      pullCoursesFromServerCommand: serviceLocator(),
      updateTasksToServerCommand: serviceLocator(),
      getNetworkInfoQuery: serviceLocator(),
    ),
  );
...

A: I am not really familiar with GetIt, but from what I can tell:

*

*You make a singleton of CourseBloc with serviceLocator.

*You use BlocProvider to provide that singleton to the relevant context (Resulting in 2 instances of CourseBloc).

*Your BlocBuilder uses the instance provided via BlocProvider because you don't explicitly tell via bloc parameter (It will look up the widget tree to find CourseBloc within the same context).

*You use the instance of CourseBloc made by serviceLocator to add CoursesReturnedFromTasksEvent().

Try adding event the usual way via BlocProvider.of, but you still need manually dispose the CourseBloc singleton made by serviceLocator
BlocProvider.of<CourseBloc>(context).add(
  CoursesReturnedFromTasksEvent(),
);


text:
Q: How to perform an apex batch update on multiple fields for multiple Objects stored in map (Record list approx 10million)? I have a custom setting which stores object and its associated fields which need to be updated.
I am planning to create a map to store the object name as key and the list of fields as values.
 Map<String, List<String>> objToLongTextFieldsMap = new Map<String, List<String>>();

I need to iterate the keyset to object name and its associated field names and pass this to a custom function to build a query string and return this query to the executeBatch method.
Query generator function: Utils_PullDataFromObject.generateQuery(strObjectName, objToLongTextFieldsMap.get(strObjectName));
However, my concern is to ensure that the Querylocator only processes the sobject records which are not updated in every transaction (say if the batch size is 2000) and for the first transaction on the first iteration of Account object - I pass the records list to executeBatch, then on the second transaction - it must process only the next set of Account records in the iteration and when all Account records are processed, it must break the loop for object names iteration. So on the next transaction, it must repeat the same process for the next object name.

A: How about no?
You won't be able to make a query in batch's start method that runs on multiple possibly unrelated objects at same time. SOQL doesn't have "union" keyword.
Keep it simple. Mark the batch as "implements Stateful". In start method pick one of keys, build the query. Do your thing. In finish method check if there's still something to process and fire off new batch. Search for "daisy chaining" batch jobs.


text:
Q: Select all hierarchy level and below SQL Server I am having a difficult time with this one. I have seen a few examples on how to obtain all child records from a self referencing table given a parent and even how to get the parents of child records.
What I am trying to do is return a record and all child records given the ID.
To put this into context - I have a corporate hierarchy.  Where:
#Role        Level#
--------------------
Corporate         0
Region            1
District          2
Rep               3

What I need is a procedure that (1) figures out what level the record is and (2) retrieves that record and all children records.
The idea being a Region can see all districts and reps in a district, Districts can see their reps. Reps can only see themselves.
I have table:
ID            ParentId           Name
-------------------------------------------------------
1             Null               Corporate HQ
2             1                  South Region
3             1                  North Region
4             1                  East Region
5             1                  West Region
6             3                  Chicago District
7             3                  Milwaukee District
8             3                  Minneapolis District
9             6                  Gold Coast Dealer
10            6                  Blue Island Dealer

How do I do this:
CREATE PROCEDURE GetPositions
    @id int
AS
BEGIN
    --What is the most efficient way to do this--
END
GO

For example the expected result for @id = 3, I would want to return:
3, 6, 7, 8, 9, 10

I'd appreciate any help or ideas on this.

A: You could do this via a recursive CTE:
DECLARE @id INT = 3;

WITH rCTE AS(
    SELECT *, 0 AS Level FROM tbl WHERE Id = @id
    UNION ALL
    SELECT t.*, r.Level + 1 AS Level
    FROM tbl t
    INNER JOIN rCTE r
        ON t.ParentId = r.ID
)
SELECT * FROM rCTE OPTION(MAXRECURSION 0);

ONLINE DEMO

A: Assuming that you're on a reasonably modern version of SQL Server, you can use the hierarchyid datatype with a little bit of elbow grease. First, the setup:
alter table [dbo].[yourTable] add [path] hierarchyid null;

Next, we'll populate the new column:
with cte as (
   select *, cast(concat('/', ID, '/') as varchar(max)) as [path]
   from [dbo].[yourTable]
   where [ParentID] is null

   union all

   select child.*,
      cast(concat(parent.path, child.ID, '/') as varchar(max)) as [path]
   from [dbo].[yourTable] as child
   join cte as parent
      on child.ParentID = parent.ID
)
update t
set path = c.path
from [dbo].[yourTable] as t
join cte as c
   on t.ID = c.ID;

This is just a bog standard recursive table expression with one calculated column that represents the hierarchy. That's the hard part. Now, your procedure can look something like this:
create procedure dbo.GetPositions ( @id int ) as
begin
   declare @h hierarchyid
   set @h = (select Path from [dbo].[yourTable] where ID = @id);

   select ID, ParentID, Name
   from [dbo].[yourTable]
   where Path.IsDescendentOf(@h) = 1;
end

So, to wrap up, all you're doing with the hierarchyid is storing the lineage for a given row so that you don't have to calculate it on the fly at select time.


text:
Q: Alice and bob xor nim game Alice and Bob are playing a game. The rules of this game are as follows:

*

*Initially, there are $N$ piles of stones, numbered $1$ through $N$. The i-th pile contains $A[i]$ stones.

*The players take alternate turns. If the bitwise XOR of all piles equals 0 before a player's turn, then that player wins the game.

*In his/her turn, a player must choose one of the remaining piles and remove it. (Note that if there are no piles, that player already won.)
We need to decide which player wins, given that both play optimally and Alice starts the game.
Example :  Let $N=4$ and  stones in piles are : $[1,2,4,8]$ in this Alice will win. But if $N=3$ and stones in piles are : $[2,3,3]$ then Bob is going to win.

A: Alice wins if and only if the number of piles is even.
In any given situation, there is only one way to lose immediately, namely by removing a pile corresponding to the current XOR sum. Thus, the only situation in which a player is forced to lose immediately is when there is only one size of piles left. If there had been an even number of them, the player would have won at the beginning of the turn, so it must be an odd number. Since one can only be forced to lose when encountering an odd number of piles and it's always the same player who encounters an odd number of piles, the claim follows.


text:
Q: Show different links based on Javascript function output I'm trying to display different possible links on a page depending on the user. For example, mobile users aren't allowed to submit data to our database. I found a Javascript function that detects mobile users, but I can't get its output to dictate the links that are shown to the user. In fact, when I try using the following code, no links show up at all.

          Find the best study space

            Check Your Internet Speed With WiFly

A: You cant use html code directly in your javascript like this.

This would follow your current approach. It might be better (and easier) if you just create your elements in 2 blocks and fadein the needed one.

   ...

   ...

It will be even more easy if you use jquery and just toggle the elements.
Important Note: By this you cant ensure people don't post data to your database. You should also check this in your backend
Update: As Anand said in the comments - you also should rethink your boxing. You cant add a div inside a paragraph. You should only use paragraphs if you directly add text to them.

A: You cannot just render HTML directly inside script tag. This syntax is allowed in ASP.NET Rajor but not for JavaScript.
Working Demo: http://jsfiddle.net/2tLzrzz8/
You should create the HTML string based on the condition and then assign the string as innerHTML of the surrounding container. For better performance, you can give a unique id to your container.
HTML:

JavaScript:
function checkMobile(){
                var strHtml="";
              if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                strHtml=''
                        + 'Wifi Study Areas'
                        + ''
                        + 'View all Speeds'
                        + ''
                        + 'Best Speed Near You'
                        + ''
                        + 'About Us';
              }
              else{
               strHtml= ''
                        + 'Wifi Study Areas'
                        + ''
                        + 'View all Speeds'
                        + ''
                        + 'Best Speed Near You'
                        + ''
                        + 'Add Speed Data'
                        + ''
                        + 'About Us';
              }

               document.getElementById("linkContainer").innerHTML=strHtml;
            }

//finally call the function.
checkMobile();


text:
Q: What trace length is considered short in case of buck voltage regulator I'm working on LM2596 based voltage regulator circuit that will be printed on PCB.
According to LM2596 datasheet some traces should be kept as short as possible. However no numbers are given.
This is my design (with ground plane hidden), from left to right:

*

*LM2596S voltage regulator

*SS54 Diode

*12.5mm 100uH Inductor

*2x Low impedance 300uF capacitor

First attempt:

I'm a little bit worried about C In (capacitor on the right between input voltage and ground) connection with regulator. The trace length is about 35mm.
Next attempt:

A: As to loop area, while your design is probably fine as is -- there is one improvement you can make to it.  Simply rotate the output capacitor 180 degrees and delete any stitching vias that are in the way of the new routing for the Vout trace.  This shrinks both the D-Cout and the Cin-Cout loops, and makes it so they don't have to traverse stitching vias, either.
HOWEVER, you do have a problem with this layout that should be corrected before you go and get a board made -- the via connecting Cin to the Vin trace on the bottom needs to be not in that pad, lest it turns into a manufacturing headache, sucking all the solder away from that pad and leaving Cin disconnected on one end. Oops!

A: Grouping of the LM2596, catch diode, inductor, and Cout aren't too bad. But, Cin is too far from the LM2596 (as you were worried).
With a buck, there are two main signals that need to be minimized:

*

*The current loop from Cin through the LM2596 and catch diode needs to be as short as possible. This is a pulsed current, most likely the highest current, and richest in harmonics on the board.

*The switching node: pin 2 of LM2596 and it's connection to the inductor and catch diode, also needs to be minimal. This voltage signal is very rich in harmonics, and is the primary source of common mode noise.
The easiest way to minimize the input current loop is probably to take the LM2596, catch diode, and Cout as a group and rotate them 180 degrees. This will allow Cin to be much closer to the LM2596.
Minimizing the switching node could be done by rotating the inductor by 90 degrees, ending with the inductor input very close to the cathode of the catch diode.
Currents through the inductor and out to the load aren't such a concern. It's mostly DC with some ripple current (contained by Cout), and not that harmonically rich.
Additionally, it will be desirable to have some input filter inductance to reduce EMI for the rest of your system. Probably a common mode choke, which if you choose well will have enough leakage inductance to also use differentially. (You may already have this, but couldn't see any in the board section shown)


text:
Q: There a way to get contribution graph to light up for open source? Ive been doing open source recently but I really want my contribution graph to light up with them green boxes. Trouble is that it only lights up for a non forked repository, so to get around this I just push my git log of all my commits to another non forked repo that simply keeps track of my commits from the forked repo.
Have any of you found solutions to this?


text:
Q: I can't run the Android SDK Manager through the Eclipse im getting an error in the Console window This is the error/s im getting:
[2013-01-21 21:24:14 - SDK Manager] [SDK Manager] 'lib\find_java.bat' is not recognized as an internal or external command,
[2013-01-21 21:24:14 - SDK Manager] [SDK Manager] operable program or batch file.

Now I tried to update the Path variable in the computer settings so it looks like:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Users\bout0_000\android-sdks\platform-tools;C:\Program Files\Java\jdk1.7.0_11\bin

I just installed now again the JDK
And still when clicking on the icon of the Android SDK Manager though the Eclipse im getting this error.
This is the content of the find_java.bat file:
@echo off
rem Copyright (C) 2007 The Android Open Source Project
rem
rem Licensed under the Apache License, Version 2.0 (the "License");
rem you may not use this file except in compliance with the License.
rem You may obtain a copy of the License at
rem
rem      http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.

rem This script is called by the other batch files to find a suitable `Java.exe`
rem to use. The script changes the "`java_exe`" env variable. The variable
rem is left unset if Java.exe was not found.

rem Useful links:
rem Command-line reference:
rem   http://technet.microsoft.com/en-us/library/bb490890.aspx

rem Check we have a valid Java.exe in the path. The return code will
rem be 0 if the command worked or 1 if the exec failed (program not found).
for /f %%a in ('%~dps0\find_java.exe -s') do set java_exe=%%a
if not defined java_exe goto :CheckFailed

:SearchJavaW
rem Check if we can find a javaw.exe at the same location than java.exe.
rem If that doesn't work, just fall back on the java.exe we just found.
for /f %%a in ('%~dps0\find_java.exe -s -w') do set javaw_exe=%%a
if not exist %javaw_exe% set javaw_exe=%java_exe%
goto :EOF

:CheckFailed
echo.
echo ERROR: No suitable Java found. In order to properly use the Android Developer
echo Tools, you need a suitable version of Java JDK installed on your system.
echo We recommend that you install the JDK version of JavaSE, available here:
echo   http://www.oracle.com/technetwork/java/javase/downloads
echo.
echo You can find the complete Android SDK requirements here:
echo   http://developer.android.com/sdk/requirements.html
echo.
goto :EOF

This find_java.bat file is located in:
C:\Users\my user name\android-sdks\tools\lib

What else should I do ? This problem I think was from the beginning when using the Eclipse.

A: Have you told Eclipse where the Android SDK is via:-
Eclipse -> Preferences.
Click the Android section on the left hand side, and set the SDK Location. It should read:-
C:\Users\my user name\android-sdks
Thanks,
Ryan


text:
Q: SharePoint 2013 Description does not show for calculated fields I have added descriptions to calculated fields in a SharePoint 2013 list, but am unable to make them display in the form like other column descriptions. How can I add these to be visible to my users?

A: In SharePoint "Description" column is the type of Multiline of Text - by the designed of SharePoint, we cannot create a calculated column out of Multiline of Text type column. Because of this limitation, though in my list I have added the "Description" column it does not show while creating the calculated column.

Solution:
Create a sample workflow using that update your desired column with the description column value.
You may look into the below trick workaround to create the calculated column out of multiline text column:
How to trick a Calculated column into referring to a Multiple Lines of Text column

A: I think following points should answer your question:

*

*If you are talking about the Description you give to the fields in their settings. Which will be shown on the list forms as instructions to users then:
As calculated columns are not shown on the list new/edit forms there is no OOTB way you can show the description of the calculated columns on list form.

*If you are are trying to use SharePoint OOTB Description column in calculated column formula then it is not possible to use it in formula as this is the multiple lines of text column (and multiple lines of text columns are not supported in calculated column formulas).

A: From your description, you want to show Description for Calculated fields.
By default, Calculated fields are not showed in NewForm or EditForm, so, users also could not see its description. It is normal behavior.
For your request, as a workaround, you can create another column using another column type (eg. Single Line of text) instead of Calculated type, then create a SharePoint Designer workflow to do the calculation and set calculated value to the new column.


text:
Q: ILMerge produces different checksum on subsequent builds If I create a .NET 3.5 application and apply the following post-build event:
if $(ConfigurationName) == Release
    "C:\Program Files (x86)\Microsoft\ILMerge\ILMerge.exe"
    /allowDup:DotfuscatorAttribute
    /ndebug
    /closed
    /out:"$(TargetPath)"
    "$(TargetPath)"
    "$(TargetDir)HelloWorld.dll"

where "HelloWorld.dll" contains a single static class with a single static method, the checksum of the resultant executable will change on subsequent builds.
Why?

A: This is closely related to the CLI and the PE format.
ECMA CLI Specification states that each module within an assembly (module is just another unit in the infrastructure - as far as I know, for regular C# VS projects there is one module per assembly, but that can also be changed) contains a Module Version ID metadatum MVID, which is different for each build.
Section II.22.30 says

The Mvid should be newly generated for every module, using the
  algorithm specified in ISO/IEC 11578:1996 (Annex A) or another
  compatible algorithm.

Furthermore the Portable Executable format contains a series of headers, some of which contain different timestamps (linking, file creation etc.). I don't know much about the details of the format, but this huge article may help if you're curious - it's a bit older (19 years? Wow), but I suppose the fundamentals of the format are still the same.
Those are just two thing that I found in a couple of minutes, there are likely other factors (I've also read the built file may contain some data specific to the machine which it was built on), which you cannot affect when building a .NET assembly.

If you need a reliable way to identify your assembly, take a look at Strong-Named Assemblies and how to create them.


text:
Q: Change global variables programmatically using Heroku? I currently have an application built with Express.js that runs via Heroku. I need to define a global variable that I can decrement each time a specific function is called, but I'm not sure how to do that programatically. I have a file of constants called consts.js and was trying to just set the variable (REMAINING) as follows: CONST.REMAINING -= 1 whenever the function is called, but unfortunately that doesn't work. What is a better way to go about this?

A: There's a good explanation of Heroku's ephemeral filesystem which is a good place to start. In a nutshell, do not use the /tmp to store any variables or application level data as it will get destroyed.
It is suggested to use Amazon S3 or a similar durable store. It may be overkill for a single variable but I would look at using Redis just because of its speed. You could also look at programmatic access of Heroku config vars as well.


text:
Q: I am getting error when set duedate creating issue in jira This is my post function. I am working on jython scripting suite.
from java.util import Calendar
from java.util import Date
import com.atlassian.jira.component.ComponentAccessor
from com.atlassian.jira import ComponentManager
from com.atlassian.jira.issue import Issue
from java.sql import Timestamp
import java
import time

ts = long(time.time())
issue.setDueDate(java.sql.Timestamp(ts))
issue.store()

and this is what i am getting error

Issue workflow initialization error: unable to find Issue created with
  workflowId '10694'. Did the IssueCreateFunction run successfully on
  workflow.initialize() ?

A: Just an educated guess:
Your post function is modifying the issue before it has been created.
Have a look at the postfunctions in the create-transition:
The first one called should be "Creates the issue originally.". Place your own postfunction after it and it should work.


text:
Q: Button Layout Issues with JFrame Picture included I have another issue where my buttons go to the top-right after the user inputs their name.  At this point, text shows up in the GUI on the LEFT side of the center which seems it would be "WEST" when I put "CENTER".  Code:
public TheDungeon()
{
  setTitle("InsertGameNameHere");
  setSize(750, 600);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setLayout(new BorderLayout());
  setLocationRelativeTo(null);

  buildButtonPanel();

  characterInfoPanel = new JLabel("Character information will go here");
  gameScreen = new JLabel();
  inventoryPanel = new JLabel("This is for the inventory");

  add(gameScreen, BorderLayout.CENTER);
  add(buttonPanel, BorderLayout.SOUTH);

  setVisible(true);

  //Program run
  userName();
  gameScreen.setText("Welcome "+name+", to the game that has no name!");
  classWindow();
}

private void buildButtonPanel()
{
  // Create a panel for the buttons.
  buttonPanel = new JPanel();

  // Create the buttons.
  b1 = new JButton("Button 1");
  b2 = new JButton("Button 2");
  b3 = new JButton("Button 3");
  b4 = new JButton("Button 4");
  b5 = new JButton("Button 5");

  // Add the buttons to the button panel.
  buttonPanel.add(b1);
  buttonPanel.add(b2);
  buttonPanel.add(b3);
  buttonPanel.add(b4);
  buttonPanel.add(b5);
}

private void userName() {
name = JOptionPane.showInputDialog("What will your name be?");
}

A: I'm not sure why your program is behaving as it seems to be since when I ran it, it did not do this. You may wish to check your code to make sure that it's the code you're posting here. But regardless, I do have some suggestions:

*

*Best to not set the sizes of anything, but rather to let the components and the layout managers do this for you.

*Consider if you must overriding getPreferredSize() if you need to control the size of a component more fully.

*Call pack() on your top level window after adding all components and before calling setVisible(true). This will tell the layout managers to do their things.

*Avoid extending JFrame since you will rarely need to override one of its innate behaviors.

*If you do add or remove components, or change their preferredSizes somehow after rendering your top-level window, you will want to call revalidate() and then repaint() on the component's container to have the container re-layout the components it holds and then redraw them.

For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.*;

public class TheDungeon2 extends JPanel {
   private static final int PREF_W = 750;
   private static final int PREF_H = 600;
   private static final String[] BUTTON_LABELS = {"Button 1", "Button 2",
         "Button 3", "Button 4", "Button 5"};
   private static final String WELCOME_TEXT = "Welcome %s to the game that has no name!";

   private JLabel welcomeLabel = new JLabel("", SwingConstants.CENTER);
   private String name;

   public TheDungeon2() {
      JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      for (String buttonLabel : BUTTON_LABELS) {
         JButton button = new JButton(buttonLabel);
         buttonPanel.add(button);
      }

      setLayout(new BorderLayout());
      add(welcomeLabel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.PAGE_END);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public void getAndSetName() {
      name = JOptionPane.showInputDialog(this, "What will your name be?");
      welcomeLabel.setText(String.format(WELCOME_TEXT, name));
   }

   private static void createAndShowGui() {
      TheDungeon2 dungeon2 = new TheDungeon2();

      JFrame frame = new JFrame("Nameless Game");

      dungeon2.getAndSetName();

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(dungeon2);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

A: I tested your code with an empty classWindow() method and the buttons are correctly placed in south,
for the CENTER issue, you should place something in WEST to have your text centred (even an empty panel) otherwise CENTER will take all the place,
look at this , i added this line :
add(new JButton("a button for test"),BorderLayout.WEST);

and here is the result :