text:
Q: Publish Snapshot to oss.jfrog.org with multiple modules fails with 403 I'm trying to publish a project with multiple modules to artifactory (oss.jfrog.org).  When I run artifactoryPublish I get a 403 error but I know it's not a permissions issue because it works with a single module. It only fails trying publish multiple modules.
Some modules are aars and others are jars and all include sources.  I can publish them all to Bintray, but can't publish to artifactory (for snapshots).
So the question is, how do I configure a multi-module project to publish snapshots to oss.jfrog.org.
I've figured out that if I change it to publish a single module and make the artifact name the same as the last part of the group, it works, but a different name doesn't work (gives 403 error).
So if group is com.example.foo I can publish foo.jar (com/example/foo/foo/1.0.0-SNAPSHOT/foo-1.0.0.jar).  But I can't publish bar.jar (com/example/foo/bar/1.0.0-SNAPSHOT/bar.jar).
This gradle is included in every project's build.gradle
afterEvaluate {
    publishing {
        publications {
            mavenPublication(MavenPublication) {
                artifact sourcesJar
            if (project.plugins.hasPlugin("com.android.library")) {
                artifact("$buildDir/outputs/aar/${project.name}-debug.aar")
            } else {
                artifact("$buildDir/libs/${project.name}-${version}.jar")
            }
            groupId "com.example.foo"
            artifactId project.name // changing this to "foo" works for a single project
            version version
            pom {
                name.set(project.name)
                url.set(POM_URL)

                packaging POM_PACKAGING
                version version

                licenses {
                    license {
                        name.set(POM_LICENSE_NAME)
                        url.set(POM_LICENSE_URL)
                    }
                }

                developers {
                    developer {
                        name.set(POM_DEVELOPER)
                        }
                    }

                    scm {
                        url.set(POM_SCM_URL)
                        connection.set(POM_SCM_CONNECTION)
                        developerConnection.set(POM_SCM_DEV_CONNECTION)
                    }
                }
            }
        }
    }

    bintray {
        user = project.findProperty('bintrayUser') ?: System.getenv('BINTRAY_USER')
        key = project.findProperty('bintrayApiKey') ?: System.getenv('BINTRAY_API_KEY')
        configurations = ['archives']
        publish = true
        dryRun = true
        pkg {
            name = project.name
            repo = BINTRAY_REPO
            userOrg = BINTRAY_ORG
            licenses = [POM_LICENSE_NAME]
            vcsUrl = POM_SCM_URL
            version {
                name = project.name
                released = new Date()
            }
        }
    }

    artifactory {
        contextUrl = 'http://oss.jfrog.org'
        publish {
            repository {
                repoKey = 'oss-snapshot-local'
                username = project.findProperty('bintrayUser') ?: System.getenv('BINTRAY_USER')
                password = project.findProperty('bintrayApiKey') ?: System.getenv('BINTRAY_API_KEY')
            }
            defaults {
                publications('mavenPublication')
                publishArtifacts = true
                publishPom = true
            }
        }
        resolve {
            repoKey = 'jcenter'
        }
    }
}

A: Artifactory returns a 403 whenever you're trying to publish an artefact that already exists. In your case, if you've previously published snapshot artefacts from your multi module build, whenever you will try doing that again, you will get a 403. I know you can configure the user access to provide delete permissions to the account you are using to deploy, as indicated here. However, overwriting history is not considered a good practice.
Regarding renaming your groups and artefacts, I don't think that will provide a solution, as it's not your GAV coordinates that are the issue, but rather the fact that artefacts with matching GAV already exist.
If I may ask, why do you want to use SNAPSHOT artefacts? Can you not achieve the same behaviour with dynamic dependencies and dependency locking?


text:
Q: ~Pods/Headers/Public/Google/Google/SignIn.h:1:9: 'GGLCore/GGLCore.h' file not found OS 10.10.5
xcode 7.2
Objective-C
iOS 9.2
CocoaPods 1.0.1
pod 'GoogleMaps'
pod 'Google/SignIn'
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
pod 'AFNetworking'
pod 'MBProgressHUD', '~> 0.9.2'
pod 'CardIO'
pod "PubNub"

ERROR, in file 'SignIn.h', 'GGLCore/GGLCore.h' file not found

But, the GoogleCore API is in it.

'SignIn.h' is in Google Sign In framework, so I cannot modify the import from <GGLCore/GGLCore.h> to "GGLCore.h"
I really don't know how to do it now.

A: I'm not so sure this is a solution as more of a somewhat larger list of things to look at to try and solve the problem. If you notice an issue with any of these things it may narrow your search to what's going on.
TLDR
(Everything is explained in more detail below)

*Make sure you're opening the .xcworkspace file instead of .xcproj file after installing CocoaPods

*As usual when Xcode trips out, always try to clean (Product > Clean Build Folder), and/or delete Derived Data (Xcode > Preferences > Locations > click on the arrow next to the Derived Data folder location) and force quit and reopen. Then rebuild once you launch Xcode

*Go to your target, and under Build Settings, find the Linking section and make sure your Other Linking Flags options has $(inherited) (Tapping on the it will expand that out to an actual list where you should be able to see your pod).

*If you don't see a path to your pod in Header Search Paths or you don't see libPods-YourProject.a in your the General tab (not Build Settings) under the Frameworks, Libraries, and Embedded Content you could try what I wrote below including a link to another post with more details, but chances are it'll be easier to just remove Cocapods (pod deintegrate) and re-integrate/install before going too deep down the rabbit hole.

Rambling Detailed Explanation
Have you tried option clicking to see if it will actually take you to the file? Sometimes Xcode will complain that it doesn't exist but that paradoxically take you to it when you try option clicking. This can hopefully be solved without resorting to the linking/search paths discussion I go into below but cleaning the project and other stuff.
But that being said, the first course of action with this should always be to Clean (Product>Clean) the project, and force quit Xcode.
On a similar course of action as this you should also try cleaning AND deleting Derived Data before launching Xcode (Xcode > Preferences > Locations > click on the arrow next to the Derived Data folder location).
Another silly mistake that can result in this is opening the .xcproj file instead of .xcworkspace after installing Cocoapods.
Now assuming this doesn't work, you'll probably want to make sure Cocoapods properly linked everything. If you go to your Build settings and specifically click on the Target:
You're going to want to make sure that libPods-YourProject.a is in the Linked Frameworks and Library section (will probably be giving you multiple other errors if somehow this wasn't the case but I'll just mention it to be complete). If it's not then that's some weird issue with Cocoapods and I would probably recommend installing pods again, or removing and adding Cocoapods to your project.
Similarly, if you click on Build Settings now, and scroll down to Linking there is an option called Other Linker Flags. Make sure there is a flag you have flags that say: $(inherited). Under that Cocoapods should have added a bunch of flags that start with -l"PodName" I'm not 100% positive here now because you have header files in addition to an extra frameworks folder, but what I think you should see is a -l"Google" flag and then under all the -l"name" flags you will see additional two line flags:
Make sure there is one that says
-framework
"GGLCore"
Now you're also probably going to want to check your search paths. So still under the Build Settings scroll a further down until you reach the Search Paths options. Make sure you're Framework Search Paths also has $(inherited) and you should see explicit search paths on the right (not when you click on it to edit, there you will only see the $(inherited).
Of more importance, however, is the section under that says Header Search Paths.
If you click on it you should see a bunch of options that look something like:
"${PODS_ROOT}/Headers/Public/NameOfPod" so I would again make sure Google is included in that list. If you open your project in the finder (right click on the Pods and click show in Finder) you also should be able to explicitly navigate to the header files by going through Pods > Headers > Public).
This is most likely where things are going wrong and there's an existing question on stack overflow you can find here that might give you some other suggestions for what to do.
Not entirely positive if this is recommended but if you find the location of the header you're trying to import, you could try explicitly adding it to the "User Header Search Paths" that is in the bottom of the Search Paths options you're looking at.
My suggestion to you however if you find anything weird about this is to remove and reinstall Cocoapods since this should be taken care of for you by them. And by that I mean completely de-integrating Cocoapods

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interfacing with a third-party API in Rails? ( Opening URLs and Parsing XML/JSON ) I'm working on a Rails project which will need to interface with multiple third-party APIs.  I'm pretty new to Rails, and I've never done this before, so I'm lacking some basic information here.  Specifically, What is the preferred Rails way of simply querying an external URL?
In the PHP world, it was cURL.  You take whatever the resource URL is, throw cURL at it, and start processing the response, whether it be XML, JSON, etc.
So, what's the cURL equivalent in Rails?  While we're at it, what is the preferred method of parsing XML and JSON responses?  My instincts are to Google around for some Ruby gems to get the job done, but this is such a practical problem that I wouldn't be surprised if the Rails community had already worked out a tried-and-true solution to this kind of problem.
If it's of any contextual value, I plan to run these third-party API interactions as nightly cronjobs, probably all packaged up as custom rake tasks.
Thanks for sharing your expertise.

A: In a perfect world, a gem already exists for the API you want to use, and you would just use that.  Otherwise, you have a few options:

*

*ActiveResource might make sense for you depending on the complexity of the API you want to use.  For example, here's an old (and no longer functional) example of using ActiveResource to connect to the Twitter API

*Net::Http is lower-level, but certainly does the trick

*open-uri is a wrapper for net/http

*Curb uses libcurl to get things done

Parsing JSON is generally very straightforward.  For XML, as stated in another answer, Nokogiri is probably the way to go.

A: for opening urls you can use open-uri
just
require 'open-uri'
file_handle = open("http://google.com/blah.xml")

to parse xml you can use Nokogiri
$ gem install nokogiri
document = Nokogiri::XML(file_handle)
document/"xpath/search"

very powerful library, can do all kinds of searching and modifying for both XML and HTML
same for html Nokogiri::HTML
there is also lots of JSOM support out there too
checkout Nokogiri also Hpricot is good for XML/HTML
for JSON in rails
parsed_json = ActiveSupport::JSON.decode(your_json_string)

parsed_json["results"].each do |longUrl, convertedUrl|
  site = Site.find_by_long_url(longUrl)
  site.short_url = convertedUrl["shortUrl"]
  site.save
end

see this question:
How do I parse JSON with Ruby on Rails?


text:
Q: Trivial Math Problem - Magnitudes and Simplification Good day, everybody!
I was handed this problem by a friend.
Prove that  $|z|=1$ if $z^n=1$.
$z$, in this case, is a complex number.
It should be very easy, but I'm missing something....
Could someone please provide a step by step solution?
So far, I've tried taking the magnitude of both sides of the given equation, but I don't know what to do after...

A: With the hint of the first comment you have $$1=z^n\implies 1=|z^n|=|z|^n$$
Since $|z|$ is a non-negative real number, it must be $1$, because $1$ is the only solution of $x^n=1$ in non-negative real numbers. To see that consider the cases $0\le x<1$ and $x>1$.


text:
Q: Spark saveAsTextFile in Google Compute taking quadratic time I am working with PySpark on a Jupyter notebook in Google Compute.
I am saving files to cloud storage using saveAsTextFile. The trouble is, it is taking quadratic time in terms of the number of records in the file. This ... doesn't work very well for decently large files.
The command I'm using is
bigFile_save.saveAsTextFile("gs://myBucket/myFolder")

Is there a way of doing things more efficiently?
As requested, a fuller code sample is
# We start with a ColumnSimilarity matrix. This is upper-triangular,
# so we append the transpose
x1 = columnSim.entries.map(lambda x: x)
x2 = columnSim.transpose().entries.map(lambda x: x)
x3 = (x1 + x2)
distMat= x3.map(lambda p: (p.i,p.j,p.value))

# Save the similarity file. Convert column indicies to meaningful
# names

bigFile_save = distMap.map(lambda p: (names[p[0]],names[p[1]],p[2]))

t1 = time.time()
bigFile_save.saveAsTextFile("gs://myBucket/myFolder")
t2 = time.time()

timeDiff = t2 - t1

On consideration, what may be happening is lazy execution: names[p[0]] may not be being resolved until the actual printout.


text:
Q: How to make code in Haskell to decide next character from the string is same as before character? Now I am making code for complicated caesar cipher in Haskell.
I succeeded to make code for normal caesar cipher.
But what I want to do is rotating by key positions again after having used a letter from the string.
For example, AAA with key position 3 will be XUR.
So my problem is after move 3, how can I make next letter will be move 6, and next move 9?

A: We only need to keep track of the position if I understand it correctly. We can do so by zipWith the [i, i+d ..] list.
So we can construct a function that looks like:
trithemiusEncrypt :: Int -> Int -> String -> String
trithemiusEncrypt i d = zipWith _ [i, i+d .. ]
with _ something we still need to fill in. This function should have type Int -> Char -> Char, so here Int is the "shift" we need to perform on the character. We can thus define this as:
import Data.Char(ord, chr)

trithemiusEncrypt :: Int -> Int -> String -> String
trithemiusEncrypt i d = zipWith f [i, i+d .. ]
    where f s c = chr (ca + mod (ord c - ca - s) 26)
          ca = ord 'A'
This gives us the expected result:
Prelude> trithemiusEncrypt 3 3 "AAA"
"XUR"
Prelude> trithemiusEncrypt 3 3 "ABC"
"XVT"


text:
Q: Python Dictionary remove pairs when key not matching reference list This is what I have:
names = ['Bob', 'Mike', 'Nia', 'Tim', 'Holly', 'Liam', 'Dave']
temperatures = ['-0.3', '-0.6', '-0.8', '-0.2', '-1.3', '-2.1', '-0.4']

main_dictionary = {'Bob' : '-0.3', 'Mike': '-0.6', 'Nia' : '-0.8', 'Tim':'-0.2', 'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}

I'm trying to produce a dictionary by comparing it to the list of selected_names against the main_dictionary to produce the updated_dictionary
selected_names = ['Nia', 'Holly', 'Liam', 'Dave']

updated_dictionary = {'Nia' : '-0.8',  'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}

So far in my project Ive compared many lists using .intersection but can seem to work out how to apply it to a dictionary.

A: Probably a simple dict comprehension is enough:
updated_dictionary = {x: main_dictionary[x] for x in selected}

If selected may contain invalid keys, you could explicitely ignore them:
updated_dictionary = {x: main_dictionary[x] for x in selected if x in main_dictionary[x]}

See also Create a dictionary with list comprehension and Filter dict to contain only certain keys?

A: Try this
main_dictionary = {'Bob' : '-0.3', 'Mike': '-0.6', 'Nia' : '-0.8', 'Tim':'-0.2', 'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}
selected_names = ['Nia', 'Holly', 'Liam', 'Dave']

newd = {k:v for k,v in main_dictionary.items() if k in selected_names}

print(newd)

A: Try this:
names = ['Bob', 'Mike', 'Nia', 'Tim', 'Holly', 'Liam', 'Dave']
temperatures = ['-0.3', '-0.6', '-0.8', '-0.2', '-1.3', '-2.1', '-0.4']

main_dictionary = {
    'Bob': '-0.3',
    'Mike': '-0.6',
    'Nia': '-0.8',
    'Tim': '-0.2',
    'Holly': '-1.3',
    'Liam': '-2.1',
    'Dave': '-0.4'
}

selected_names = ['Nia', 'Holly', 'Liam', 'Dave']
output = {
    'Nia': '-0.8',
    'Holly': '-1.3',
    'Liam': '-2.1',
    'Dave': '-0.4'
}
updated_dictionary = {k: v for k, v in main_dictionary.items() if k in selected_names}

if __name__ == '__main__':
    print("main", main_dictionary)
    print("updated", updated_dictionary)
    print(updated_dictionary == output)

# It produces:
# {'Nia': '-0.8', 'Holly': '-1.3', 'Liam': '-2.1', 'Dave': '-0.4'}
# updated {'Nia': '-0.8', 'Holly': '-1.3', 'Liam': '-2.1', 'Dave': '-0.4'}
# True


text:
Q: Lua: Adding multiple rows to tables Ok, so I'm looking to quickly generate a rather large table. Something that would look like this:
table{
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1},
}

Only the table would contain far more rows, and far more values in those rows. I know using table.insert() I can easily add however many I need to a single row, but is there anyway I can also add whole new rows without typing it all out?

A: Use a for loop.
t = { }
for i = 1,100 do
    table.insert(t, i) -- insert numbers from 1 to 100 into t
end

2D arrays are also very simple
t = { }
for row = 1,20 do
    table.insert(t, { }) -- insert new row
    for column = 1,20 do
        table.insert(t[row], "your value here")
    end
end

You could remember current row as in local current_row = t[row], but don't try these things to improve performance until you profile! Use them merely for readability, if you think it clearer expresses the purpose.
Also note that (and it's especially funky in 5.1 and newer with the #) you can just directly assing values to nonexisting indices, and they will be added.

A: You don't need to use table.insert:
t = {}
for row = 1,20 do
    t[row] = {}
    for column = 1,20 do
        t[row][column]= "your value here"
    end
end


text:
Q: Porque entra en la condición no deseada No entiendo porque cuando en el prompt le escribo pasapalabra, me entra en la condición que hay una alerta que dice "has fallado".En teoría debería entrar en la condición de (obj.answer === "pasapalabra") pero me entra todo el rato en la de (obj.answer != userAnswer && obj.answer != "pasapalabra").

var questions = [
        { letter: "a", answer: "abducir", status: 0, question: ("CON LA A.") },
        { letter: "b", answer: "bingo", status: 0, question: ("CON LA B.") },
        { letter: "c", answer: "churumbel", status: 0, question: ("CON LA C.") },
    ]

    function pasapalabra(myObject) {

        function pregunta() {

            var acertados = 0;
            var fallados = 0;

            myObject.forEach(function(obj){

                var userAnswer = prompt(obj.question);
                console.log(userAnswer)

                if (obj.answer === userAnswer) {
                    alert("Has acertado!!");
                    obj.status = 2;
                    acertados++;
                } else if (obj.answer != userAnswer && obj.answer != "pasapalabra") {
                    alert("Has fallado!!");
                    obj.status = 0;
                    fallados++;
                } else if (obj.answer === "pasapalabra"){
                    obj.status = 1;
                    console.log("Pasapalabra")
                } else {
                    console.log("Has salido")
                }
            })

            console.log("Aciertos: " + acertados)
            console.log("Fallos: " + fallados)
        }

        pregunta();
    }

    pasapalabra(questions);

A: El problema es que deberías de cambiar las comparaciones con "pasapalabra":
obj.answer != "pasapalabra" => userAnswer != "pasapalabra"
obj.answer === "pasapalabra" => userAnswer === "pasapalabra"
Otra buena páctica sería asegurarse de que las comparaciones ignoren mayúsculas o minúsculas (ya que el usuario puede introducir mayúsculas, con lo cual ya no te aceptaría la respuesta como válida), tan fácil de hacer como:
userAnswer != "pasapalabra"=>userAnswer.toLowerCase() != "pasapalabra"
userAnswer === "pasapalabra" => userAnswer.toLowerCase() === "pasapalabra"
obj.answer === userAnswer => obj.answer === userAnswer.toLowerCase()
etc...
Espero que te sirva :)


text:
Q: Adding up to text javascript I want to add to existing text based on the input user provide,
below is what I am trying to reach

Enter the IDs of devices seperated by comma

<input id="devicesIDs"></input>

I need "or (id eq 'entered ID3'))" to be added to the original text $filter=((id eq '{{entered ID1}}') if there more than one Id entered, based on the number of IDs, and to have each ID in it

A: You've got the IDs in an array, we can just format them then join them into the filter query
  function ButtonClicked(devicesIDs):
    var IDs = document.getElementById("devicesIDs").innerText;
    var inputArray = IDs.split(',');
    let filterGroup = inputArray.map(id => `(id eq '${id.trim()}')`)
    //  to choose one at random
    filterGroup = `$filter=(${filterGroup[Math.floor(Math.random()*filterGroup.length)]})`;
    // to use all with OR
    // filterGroup = `$filter=(${filterGroup.join(" or ")})`;

    let obj = {
      "c8y_isDynamicGroup": {
        "invisible": true
      },
      "type": "c8y_DynamicGroup",
      "name": " SmartGroupSendMessageXXX",
      "hajjMessage": "messages typed in the widget",
      "c8y_DeviceQueryString": filterGroup
  }

A:

document.querySelector("button").onclick=ev=>{
  const IDs = document.getElementById("devicesIDs").value.split(','),
        obj = {
  "c8y_isDynamicGroup": {"invisible": true},
  "type": "c8y_DynamicGroup",
  "name": " SmartGroupSendMessageXXX",
  "hajjMessage": "messages typed in the widget",
  "c8y_DeviceQueryString": "$filter=("+IDs.map(id=>"(id eq '"+id.trim()+"')").join(" or ")+")"
  };
 fetch('https://jsonplaceholder.typicode.com/users/',  // placeholder for testing ...
   {method: 'POST',body: JSON.stringify(obj),
    headers: {'Content-type': 'application/json; charset=UTF-8'}})
 .then(r=>r.json()).then(data=>console.log(data))
}

Enter the IDs of devices seperated by comma

<input id="devicesIDs" value="3,4,5">
<button>go</button>


text:
Q: Import images with Create-React-App dynamically I hope that somebody can help me with my problem.
I started learning React and I want to display images dynamically from an object named "project".
I am looping inside "projects" and pass each item as props of a component "Project".
It displays the other items (name, description, alt) but I can't get the images.
I tried this method : <img src={require(`./img/${project.image}`)} but it doesn't work.
There is no error message, but it shows nothing.
I saw a lot of people have the same problem, but I tried everything...I don't know what to do.
This is my object:

The organization of my folder:

My component Project:

And the website:

A: You don't need to use require. It will work if you use it that way.
<img src={`./img/${project.image}`} alt={project.alt} />

I hope that will be useful.

A: Thank you guys ! I found a way to do it.
I first imported the images to my object file "projects".
Then I imported my object and I made a loop
import images
loop
Finally, my component Project
component Project
Thank you all for your help!


text:
Q: Heroku - No module named wsgi I followed the getting started Django guide on the Heroku support center but I am getting the following error when I try to start it on either Heroku or with foreman:
ImportError: No module named wsgi

Here is my procfile:
web: gunicorn testproject.wsgi -b 0.0.0.0:$PORT

Here is my django project settings file:
from datetime import date, timedelta
import os
oneyr = date.today() + timedelta(days=365)
PROJECT_DIR = os.path.dirname(__file__)

DEBUG = os.environ.get('DEBUG')
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-gb'
USE_I18N = False
USE_L10N = True

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'static/')
MEDIA_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'static/'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'testproject.urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_DIR, 'templates')
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gunicorn',
    'storages',
)

STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

Does anyone have any idea why this app won't start?

A: It looks like you don't have a wsgi.py module file in your project directory. If you started your project (with django-admin.py startproject project) with Django 1.3 or earlier, the wsgi file was not automatically created. You'll want to create it yourself following this guide:
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
As per the guide, put this in the file, making sure to change 'mysite' to your project name:
import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

# This application object is used by the development server
# as well as any WSGI server configured to use this file.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Also, as I didn't see this in your settings, you'll want to make sure your project directory is included in your Python path as per the last sentence here: https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/gunicorn/#running-django-in-gunicorn-as-a-generic-wsgi-application
Or else you'll run into the same problem I did:
Python app import error in Django with WSGI gunicorn
After that, everything should work without a hitch. Cheers!
Sidenote: You might already be able to run gunicorn by changing your Procfile to:
web: python manage.py run_gunicorn

as per https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/gunicorn/#using-gunicorn-s-django-integration, but I haven't tested this myself so not sure. Might still need the wsgi.py module.

A: This is an old question but I'm responding to it nonetheless as I faced this exact problem recently and the answer by Intenex although helpful was not able to resolve my issue.
As pointed out by Intenex you're probably missing the wsgi.py file. This could be because you've created your project using Django 1.3 or a previous version. Creating a project using Django 1.4 automatically creates the wsgi.py just like manage.py, settings.py.
Unlike what Intenex has pointed out, here's what you should do. Assuming you're on Django 1.3 or earlier version, create wsgi.py file in the project directory (same directory as manage.py etc.) and add the following to your wsgi.py file:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

# This application object is used by the development server
# as well as any WSGI server configured to use this file.
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Note the difference in the last 2 statements compared to Intenex's answer.
With this you should be able to run foreman start with the following in your Procfile:
web: gunicorn mysite.wsgi

A: Just came across this problem; occured to me that my Procfile had Windows Format EOL Encoding; switched to UNIX EOL - and voilà, worked.

A: Came across this error and the above question just now.
Found the settings file had a syntax error in the line for ALLOWED_HOSTS. The above descriptions help point me in that direction (at least looking at the settings).
Thought it might help somebody else out...

A: I had this error as well, and the other solutions did not fix it.
The source of my problem was that I had installed gunicorn through apt-get. To solve, I removed gunicorn via apt and ran pip install gunicorn.

A: I ran into this error because I manually renamed my project folder from myproject to myproject_django, but I didn't fix all of the references in the settings file. In particular,
WSGI_APPLICATION = 'myproject.wsgi.application'

needed to be changed to
WSGI_APPLICATION = 'myproject_django.wsgi.application'

Again, there a few references in that file that need to be changed. Just do a search and a careful, one-by-one replace.


text:
Q: Count unique rows of 3 join tables I would like to count several items in the 3 tables:

*

*"Total" - The total Serialnumbers in a batch (Batch is the 3 first digits of Serialnumber)

*"Call_Per_Code" - Count the unique codes with a callnr for each batch

*"NoCall" - Count the unique codes without a callnr for each batch

Sample data below:
Table Test1
CallNr      CallType
1           rej
2           rej
3           rej
4           rej
5           QC
6           QC
7           rej
8           rej

Table Test2
CallNr     Code
1          201401
3          201402
4          201404
5          201401
7          201401
8          201401

Table Test3
Code    PartCode  SerialNumber
201401  68001     123-01
201402  68001     123-02
201403  68001     123-03
201404  68001     124-01
201405  68001     124-02
201406  68001     124-03

The result must be:
Batch Total NoCall Call_Per_Code
123   3     1      2
124   3     2      1

But I get the result:
Batch Total NoCall Call_Per_Code
123   3     1      4
124   2     1      1

I am using the sql code on a SQL Server 2012:
SELECT
   substring(T3.SerialNumber,1,3) as batch
   ,COUNT(DISTINCT concat(T3.code,substring(T3.SerialNumber,1,3))) as Total
   ,sum(case when T2.CallNr is null then 1 else 0 end) as NoCall
   ,sum(case when T2.CallNr is null then 0 else 1 end) as Call_per_Code
FROM Test1 T1
    INNER JOIN Test2 T2
        ON T1.CallNr=T2.CallNr AND T1.CallType='rej'
    RIGHT JOIN Test3 T3
        ON T2.Code=T3.Code
GROUP BY substring(T3.SerialNumber,1,3)

How can I get the correct count on the column Call_Per_Code. The Code 201401 with a CallNr is count as 3 instead of 1.

A: This query gets a lot easier if you start from Test3 - you don't even need to join to Test1 if you start from there:
SELECT
   SUBSTRING(T3.SerialNumber, 1, 3) AS Batch,
   COUNT(DISTINCT T3.Code) AS Total,
   SUM(CASE WHEN T2.CallNr IS NULL THEN 1 ELSE 0 END) AS NoCall,
   COUNT(DISTINCT T2.Code) AS Call_Per_Code
FROM Test3 T3
    LEFT OUTER JOIN Test2 T2 ON T3.Code = T2.Code
GROUP BY SUBSTRING(T3.SerialNumber, 1, 3)


text:
Q: how to convert a a hex byte stored as string to hex byte in python i have a list of hex byte that have stored as string in Mongodb because Mongodb doesn't support hex byte my data is :

'topics': ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x00000000000000000000000077337dfe579a03a07a475870db443d65127f0769', '0x0000000000000000000000003b6d0dd29a60ff5ea96b54e60fbb0d71da80ef78']

i have to change to be like :

'topics': [
HexBytes('0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62'), HexBytes('0x0000000000000000000000006036f4ea42a2d6d8b9a0120f0a7b95faf21e82d3'), HexBytes('0x0000000000000000000000004ba84d2ca525aa578f8e097acd4141dfd52b3e74'), HexBytes('0x000000000000000000000000e54c65316e8967c25c1357773b5e85bc063b7efd')
]

i have used the binascii , hex(int(topics[0],int16)) but didn't work is there any way to do it
thanks in advance


text:
Q: Notepad++ opening files containing En dash character I have two files with identical content. One file has an XML extension, the other txt. Both files are encoded in ASCII. They both contain the En dash character (hex value 96).
When I open the file with the txt extension the file displays as I would expect. The En dash correctly shows as a dash.
When I open the XML file, however, the En dash character displays as x96 in inverted foreground/background colours.
Does this display of the xml file have to do with the fact that it's an ASCII encoded file but the file contains:
<?xml version="1.0" encoding="UTF-8"?>
Why does the character not display correctly? When I hex edit the XML file I see the En dash is hex value 96 which is still within the extended ASCII table.
File sample:
<?xml version="1.0" encoding="UTF-8"?>
<x>Plug & Play ֠No wire splicing necessary</x>

The en dash follows "Play " and precedes " No". Please note the leading and trailing space.

A: You are creating an invalid XML file. I don't think there is a universally accepted correct behavior of an editor in such cases. Notepad is interpreting it as a text file. Notepad++ is trying to interpret it as a valid XML file and pointing out the problem.
The reason that Notepad succeeds if you use the Open dialog is that you telling it the encoding of the file: "ANSI". If you use drag and drop or other means, it's either guessing an encoding that's apparently close enough or always using "ANSI".
Notepad++ is helping you more because it's not just a general text editor. It is interpreting the file as an XML file (probably based on the extension).
An XML document optionally indicates the encoding used for its byte representation. You are writing the file as some ANSI encoding (maybe Windows-1252), yet marking it as as UTF-8. That requires XML processors to use UTF-8. (Due to similarities in encodings, a program can read using a guessed encoding to find the indicated encoding and the read the document again using that.)
You luck out here because instead of the wrong encoding resulting in the silent error of scrambling characters, your data actually shows up as invalid. UTF-8 does not produce or allow arbitrary sequences bytes with values 0-255. 0x96 is only allowed if it is part of a sequence and pattern of bytes that encode certain Unicode codepoints. Simply, the file is not valid UTF-8. Notepad++ highlight the bytes that prove that. You would be unlucky if the attempt to read the file as UTF-8 succeeded yet gave an unexpected result.
The solution is to match the indicated encoding to the actual encoding. Normally, XML libraries have writer functions that do this for you. The problem is that you are using a writer that doesn't and you don't actually know which "ANSI" encoding you are using. It seems that you also have a requirement to not use UTF-16. Perhaps you should get a positive statement of what you can use. If you use a post-processing step many tools such as PowerShell could rewrite the XML file for you using a document encoding that you specify.


text:
Q: Sobre jasper IReports, preciso ordernar colunas quem vem do banco de dados para serem exibidas ordenadas no relatório O problema que já ordenei pelo iReport ide, query sql na string da classe clienteDAO, mas meu chefe quer que ordene com uma das classes do jars do Jasper, eu estou procurando sem sucesso. Alguém já passou por isso?
Eu só quero ordernar o relatório que o java gera e preciso utilizar algum método de alguma classe do jar do jasper.
grata...

A: Tente dar uma olhada nesse link:
https://solutiondesign.com/blog/-/blogs/building-dynamic-columns-in-jasperrepor-1
Ele exemplifica a criação de colunas dinamicas com o jar Dynamic Jasper.
Eu já utilizei para resolver um problema parecido com o seu (no meu caso, dependendo da consulta, eu precisava adicionar ou remover colunas no relatório). A implementação não é tão simples, por isso para utilizar você vai precisar dar uma estudada em alguns exemplos.


text:
Q: Codeigniter - $sOrder and $sLimit in datatables I'm retrieving records using Codeigniter and datatables. Removing $sOrder and $sLimit loads the data but on filtering, there's a database error:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''desc' LIMIT '0', '10'' at line 5

SELECT SQL_CALC_FOUND_ROWS id, FName, LName, status, authorizedby, userName
FROM users
ORDER BY id 'desc'
LIMIT '0', '10'"

Here's the code:
        if (isset($_REQUEST['iSortCol_0'])) {
            $sOrder = "ORDER BY  ";
            for ($i = 0; $i < intval($_REQUEST['iSortingCols']); $i++) {
                if ($_REQUEST['bSortable_' . intval($_REQUEST['iSortCol_' . $i])] == "true") {
                    $sOrder .= $aColumns[intval($_REQUEST['iSortCol_' . $i])] . "
                    " . $this->db->escape($_REQUEST['sSortDir_' . $i]) . ", ";
                }
            }
            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == "ORDER BY") {
                $sOrder = "";
            }
        }

        $sWhere = "";
        // this for search code
        if ($_REQUEST['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 0; $i < count($aColumns); $i++) {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $this->db->escape($_REQUEST['sSearch']) . "%' OR ";
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }

        for ($i = 0; $i < count($aColumns); $i++) {
            if ($_REQUEST['bSearchable_' . $i] == "true" && $_REQUEST['sSearch_' . $i] != '') {
                if ($sWhere == "") {
                    $sWhere = "WHERE ";
                } else {
                    $sWhere .= " AND ";
                }
                $sWhere .= $aColumns[$i] . " LIKE '%" . $this->db->escape($_REQUEST['sSearch_' . $i]) . "%' ";
            }
        }

        // generate sql query
        $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aResultColumns)) . "
       FROM   $sTable
       $sWhere
       $sOrder
       $sLimit
    ";

Now, removing the last two lines ($sOrder and $sLimit) works for loading the data but error on filtering. How is this fixable.

A: This is how I solved it:
        $sWhere = "";
        // this for search code
        if ($_REQUEST['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 0; $i < count($aColumns); $i++) {
                $sWhere .= $aColumns[$i] . " LIKE '*%" . $this->db->escape($_REQUEST['sSearch']) . "%*' OR ";
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }

        for ($i = 0; $i < count($aColumns); $i++) {
            if ($_REQUEST['bSearchable_' . $i] == "true" && $_REQUEST['sSearch_' . $i] != '') {
                if ($sWhere == "") {
                    $sWhere = "WHERE ";
                } else {
                    $sWhere .= " AND ";
                }
                $sWhere .= $aColumns[$i] . " LIKE '*%" . $this->db->escape($_REQUEST['sSearch_' . $i]) . "%*' ";
            }
        }

        $sOrder = str_replace("'", "", $sOrder);
        $sLimit = str_replace("'", "", $sLimit);
        $sWhere = str_replace("'", "", $sWhere);
        $sWhere = str_replace("*", "'", $sWhere);

        // generate sql query
        $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aResultColumns)) . "
       FROM   $sTable
       $sWhere
       $sOrder
       $sLimit
    ";```


text:
Q: In java Trying to convert "2020-11-22T05:57:10+01:00" into Java Date object try {
    SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD'T'HH:mm:ss+hh:mm");
    Date dateTime = format .parse("2020-11-22T05:57:10+01:00");
    System.out.println(dateTime);
} catch (ParseException e) {
    e.printStackTrace();
}

Above out put is Sun Dec 29 05:00:10 IST 2019 the 57 minutes part is lost.
The above date I am receiving from JSON response with TimeZone Europe/Berlin.
Currently I haven't include TimeZone. What is correct way to address this string while converting into Java Date object?
Does the above conversion is correct ?
If not then how to convert this data ?


text:
Q: How does MS know which public IP addresses are dynamically assigned I came across this article which says that Microsoft is blocking SMTP from dynamically allocated public IP addresses.
https://support.microsoft.com/en-us/help/886692/microsoft-com-now-blocks-incoming-smtp-mail-from-servers-that-use-dyna
I don't know any mechanism that will tell whether an IP address on the internet is dynamically assigned or not. Reverse IP lookups may be able to give a clue with the name assigned to it but it would not be very accurate. I'm just curious , let me know what this can be.

A: They may, for example, use PBL from Spamhaus. See the first answer on Spamhaus PBL FAQ.

A: Under IANA, regional registries such as ARIN (for the US) and RIPE (for Europe) will ask any IP block taker to know if it's for residential usage.
This means that ARIN, RIPE and other registries willl know which IP blocks are dynamically allocated for residential use.
In big, an ISP can ask ARIn for an IP block, and ARIN can make sure those ip blocks remain in DHCP. It's to prevent running out of IP addresses, as space with static IP addresses are harder to control.
Note also that when an ISP needs more IP, ARIN can refuse to give them if they have too much static space used.
There are blackhole lists, such as the Spamhaus PBL. who will simply check that information, and if you're in a block allocated for dynamic addresses you'll be tagged. It doesn't make any difference if your ISP has reserved an IP address for you from their DHCP server or from PPPoE.
Edited:
You might also want to read Help! My IP address is on the PBL! What should I do?, which says:
Nothing, in most cases. Read through this FAQ for further explanations.
The first thing to know is: THE PBL IS NOT A BLACKLIST. You are not listed for spamming or for anything you have done. The PBL is simply a list of all of the world's dynamic IP space, i.e: IP ranges normally assigned by ISPs to broadband customers routers/modems (DSL, DHCP, PPP, cable, dialup). It is perfectly normal for these IP addresses to be listed on the PBL. In fact all dynamic IP addresses in the world should be on the PBL. Even static IPs which do not send mail should be listed in the PBL.


text:
Q: floorspace do-while program I am supposed to write a program that calculates the total floor space in a house. The program prompts the user to enter the length & width of at least one  room and it needs to verify with the user if he wants to enter more room dimensions.
It isn't working. Someone please help me?
import java.util.*;

public class FloorSpace
{

    public static void main (String[] args)
    {

        Scanner input = new Scanner(System.in);

        double length = 0.0, width = 0.0, floorSpace = 0.0;
        char ans;

        do
        {
            System.out.print("Enter length: ");
            length = input.nextDouble();

            System.out.print("Enter width: ");
            width = input.nextDouble();

            floorSpace = length * width;

            floorSpace += floorSpace;

            System.out.print("Do you want to enter more room dimensions? (y/n): ");
            ans = input.nextLine().charAt(0);
        }
        while (ans == 'y');

        System.out.println("\nTotal floor space is " + floorSpace);

    }

}
Oh my I just found out something's wrong with my computation formula. Can someone please help me.

A: You are setting floorSpace to length * width every time and then incrementing that value by itself (which is really just multiplying it by two).
Replace
floorSpace = length * width;

floorSpace += floorSpace;

with just
floorSpace += length * width

A: Instead of:
ans= input.nextLine().charAt(0);

use:
ans = input.next().charAt(0);

To fix your formula use:
    floorSpace += length * width;

and remove:
floorSpace = length * width;

So the final solution looks like:
import java.util.*;

public class FloorSpace
{

    public static void main (String[] args)
    {

        Scanner input = new Scanner(System.in);

        double length = 0.0, width = 0.0, floorSpace = 0.0;
        char ans;

        do
        {
            System.out.print("Enter length: ");
            length = input.nextDouble();

            System.out.print("Enter width: ");
            width = input.nextDouble();

            floorSpace += length * width;

            System.out.print("Do you want to enter more room dimensions? (y/n): ");
            ans = input.next().charAt(0);
        }
        while (ans == 'y');

        System.out.println("\nTotal floor space is " + floorSpace);
    }
}

A: Try this:
import java.util.*;

public class FloorSpace
{

    public static void main (String[] args)
    {

        Scanner input = new Scanner(System.in);

        double length = 0.0, width = 0.0, floorSpace = 0.0;
        char ans='n'; //not for default

        do
        {
            System.out.print("Enter length: ");
            length = input.nextDouble();

            System.out.print("Enter width: ");
            width = input.nextDouble();

            floorSpace +=  length * width;

            System.out.print("Do you want to enter more room dimensions? (y/n): ");
            if (input.hasNext()){
                ans = input.next().charAt(0);
            }
        }
        while (ans == 'y');

        System.out.println("\nTotal floor space is " + floorSpace);

    }
}

Regards


text:
Q: How to rank a list with original order in c# I want to make a ranking from a list and output it on original order.
This is my code so far:
     var data = new[] { 7.806468478, 7.806468478, 7.806468478, 7.173501754, 7.173501754, 7.173501754, 3.40877696, 3.40877696, 3.40877696,
            4.097010736, 4.097010736, 4.097010736, 4.036494085, 4.036494085, 4.036494085, 38.94333318, 38.94333318, 38.94333318, 14.43588131, 14.43588131, 14.43588131 };

        var rankings = data.OrderByDescending(x => x)
               .GroupBy(x => x)
               .SelectMany((g, i) =>
                   g.Select(e => new { Col1 = e, Rank = i + 1 }))
               .ToList();

However, the result will be order it from descending:

What I want is to display by its original order.
e.g.: Rank = 3, Rank = 3, Rank = 3, Rank = 4, Rank = 4, Rank = 4, etc...
Thank You.

A: Using what you have, one method would be to keep track of the original order and sort a second time (ugly and potentially slow):
var rankings = data.Select((x, i) => new {Item = x, Index = i})
       .OrderByDescending(x => x.Item)
       .GroupBy(x => x.Item)
       .SelectMany((g, i) =>
           g.Select(e => new {
               Index = e.Index,
               Item = new { Col1 = e.Item, Rank = i + 1 }
           }))
       .OrderBy(x => x.Index)
       .Select(x => x.Item)
       .ToList();

I would instead suggest creating a dictionary with your rankings and joining this back with your list:
var rankings = data.Distinct()
                   .OrderByDescending(x => x)
                   .Select((g, i) => new { Key = g, Rank = i + 1 })
                   .ToDictionary(x => x.Key, x => x.Rank);

var output = data.Select(x => new { Col1 = x, Rank = rankings[x] })
                 .ToList();

As @AntonínLejsek kindly pointed out, replacing the above GroupBy call with Distinct() is the way to go.
Note doubles are not a precise type and thus are really not a good candidate for values in a lookup table, nor would I recommend using GroupBy/Distinct with a floating-point value as a key. Be mindful of your precision and consider using an appropriate string conversion. In light of this, you may want to define an epsilon value and forgo LINQ's GroupBy entirely, opting instead to encapsulate each data point into a (non-anonymous) reference type, then loop through a sorted list and assign ranks. For example (disclaimer: untested):
class DataPoint
{
    decimal Value { get; set; }
    int Rank { get; set; }
}

var dataPointsPreservingOrder = data.Select(x => new DataPoint {Value = x}).ToList();

var sortedDescending = dataPointsPreservingOrder.OrderByDescending(x => x.Value).ToList();

var epsilon = 1E-15; //use a value that makes sense here

int rank = 0;
double? currentValue = null;

foreach(var x in sortedDescending)
{
    if(currentValue == null || Math.Abs(x.Value - currentValue.Value) > epsilon)
    {
        currentValue = x.Value;
        ++rank;
    }
    x.Rank = rank;
}

A: From review of the data you will need to iterate twice over the result set.
The first iteration will be to capture the rankings as.
var sorted = data
    .OrderByDescending(x => x)
    .GroupBy(x => x)
    .Select((g, i) => new { Col1 = g.First(), Rank = i + 1 })
    .ToList();

Now we have a ranking of highest to lowest with the correct rank value. Next we iterate the data again to find where the value exists in the overall ranks as:
var rankings = (from i in data
                let rank = sorted.First(x => x.Col1 == i)
                select new
                {
                    Col1 = i,
                    Rank = rank.Rank
                }).ToList();

This results in a ranked list in the original order of the data.

A: A bit shorter:
var L = data.Distinct().ToList();      // because SortedSet<T> doesn't have BinarySearch :[
L.Sort();

var rankings = Array.ConvertAll(data,
                                x => new { Col1 = x, Rank = L.Count - L.BinarySearch(x) });


text:
Q: How can I know what number is repeated? I'm trying to know what number is repeated in Java.
I'm using 1.8JDK and never enter in IF.
I don't know how can I do for program works, I'm hardstucked.
Can you check my code?
package exercici10;

import java.util.Scanner;

public class isRepeatedOrNot {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int[] myArray = new int[10];

        int[] myArray2 = new int[10];
        for (int i = 0; i < 10; i++) {
            myArray2[i] = myArray[i];
        }

        System.out.print("Enter 10 numbers: ");

        // Get myArray.
        for (int i = 0; i < 10; i++) {
            myArray[i] = sc.nextInt();
        }

        // Print myArray.
        for (int i = 0; i < myArray.length; i++) {
            for (int j = 0; j < myArray2.length; j++) {
                if (myArray[i] == myArray2[j]) {
                    System.out.println("Is repeated.");
                    return;
                }
            }
        }
        System.out.println("No numbers repeated.");

        sc.close();
    }
}

Thank you.
Regards,
Alex.

A: You do not need to have two arrays, it is enough to use one array and a function that will check if there is a repetition of a number:
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] myArray = new int[10];

        System.out.print("Enter 10 numbers: ");

        // Get myArray.
        for (int i = 0; i < 10; i++) {
            myArray[i] = sc.nextInt();
        }

        System.out.println(isNumberRepeated(myArray));

        sc.close();
    }

    public static boolean isNumberRepeated(int[] array)
    {
        for (int i=0; i<array.length; i++) {
            for (int j=i+1; j<array.length; j++) {
                if (array[i]==array[j]) {
                    return true;
                    }
            }
    }
        return false;
    }
}

Input :
Enter 10 numbers: 1
2
3
4
5
6
7
8
9
10
false

Input 2 :
Enter 10 numbers: 1
2
3
4
5
54
6
7
54
9
true

A: You could use HashSet which doesn't allow duplicate values.
public static void main(String[] args) {
    Integer[] myArray = {1, 2, 3, 1, 3, 4, 5, 7, 6, 3, 2};
    HashSet<Integer> uniqueNumbers = new HashSet<>();
    HashSet<Integer> repeatedNumbers = new HashSet<>();

    for (Integer integer : myArray) {
        if (uniqueNumbers.contains(integer)) {
            repeatedNumbers.add(integer);
        } else {
            uniqueNumbers.add(integer);
        }
    }
    System.out.println(repeatedNumbers);
}

Also if you need to modify your code to show number of times every number repeated, you could use hashmap.


text:
Q: Creating an SSH Key Pair for User Authentication with Expect in Bash I have tried the following steps to set ssh passwordless (SSH Key Pair Authentication)login.
Set ip and port in bash.
ip="xxxx"
port="xxxx"

Set ssh config file on client side
cat > $HOME/.ssh/config <<EOF
Host $ip
IdentityFile $HOME/.ssh/id_rsa
User root
EOF

Create a ssh key pair  on client side
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -q -b 2048 -N ""

Push id_rsa into ssh server from client side.
Prepare for ssh server
ssh -p $port  root@$ip  "mkdir -p  /root/.ssh"

Push authorized file into ssh server
scp -P $port id_rsa.pub root@$ip:/root/.ssh/authorized_keys

Set permission for authorized file
ssh -p $port root@$ip "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"

Succeeded!
Now i want to write all steps into a one-click bash script for the job.
Here is my try.
#! /bin/bash
ip="xxxx"
port="xxxx"
pass="yyyy"

cat > $HOME/.ssh/config <<EOF
Host $ip
IdentityFile $HOME/.ssh/id_rsa.bwg_root
User root
EOF

ssh-keygen -t rsa -f $HOME/.ssh/id_rsa.bwg_root -q -b 2048 -N ""
cd  $HOME/.ssh

    /usr/bin/expect <<EOF
    spawn ssh -p $port  root@$ip  "mkdir -p  /root/.ssh"
    expect "password:"
    send "$pass\r"
    spawn scp -P $port id_rsa.pub root@$ip:/root/.ssh/authorized_keys
    expect "password:"
    send "$pass\r"
    spawn ssh -p $port root@$ip "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
    expect "password:"
    send "$pass\r"
EOF

It got the following output info:
spawn ssh -p xxxx root@yyyy mkdir -p  /root/.ssh
root@yyyy's password: spawn scp -P xxxx id_rsa.bwg.pub root@yyyy:/root/.ssh/authorized_keys
root@yyyy's password: spawn ssh -p xxxx root@yyyy chmod 700 .ssh; chmod 640 .ssh/authorized_keys

Why and how to fix it?

A: I'd simplify it with sshpass.
#!/bin/bash
ip="x.x.x.x"
port="xx"
export SSHPASS="yyy"

cat >$HOME/.ssh/config <<EOF
Host $ip
IdentityFile $HOME/.ssh/id_rsa.bwg_root
User root
EOF

ssh-keygen -t rsa -f "$HOME/.ssh/id_rsa.bwg_root" -q -b 2048 -N ""
cd "$HOME/.ssh" || exit 1

sshpass -e ssh -oStrictHostKeyChecking=no -p "$port" "root@$ip" "mkdir -p -m 700 /root/.ssh"
sshpass -e scp -oStrictHostKeyChecking=no -P "$port" id_rsa.bwg_root.pub "root@$ip:/root/.ssh/authorized_keys"
sshpass -e ssh -oStrictHostKeyChecking=no -p "$port" "root@$ip" "chmod 640 .ssh/authorized_keys"

Btw: I replaced last id_rsa.pub with id_rsa.bwg_root.pub and added -m 700 to mkdir and removed chmod 700 .ssh.

A: Use ssh-copy-id to push the new key to the remote host. You'll need to enter the password for that login, of course, but it's the last time you'll have to use it.
#!/bin/bash
ip="x.x.x.x"
port="xx"
id_file=$HOME/.ssh/id_rsa_$ip

cat > $HOME/.ssh/config <<EOF
HOST $ip
IdentityFile $id_file
User root
EOF

ssh-keygen -t rsa -f "$HOME/.ssh/id_rsa_$ip" -q -b 2048 -N ""

ssh-copy-id -i "$id_file" -p "$port" root@"$ip"

As a general rule, always look for a non- (or less) interactive solution using existing tools before trying except.


text:
Q: Supercompact and Reinhardt cardinals without choice A friend of mine and I ran into the following question while reading about proper forcing, and have been unable to resolve it:
Definition. A cardinal $\kappa$ is supercompact if for all ordinals $\lambda$, there exists a  transitive inner model $M_\lambda$ of $V$ and an elementary embedding $j_\lambda: V\rightarrow M_\lambda$ such that $crit(j_\lambda):=\min\lbrace\alpha\in ON: j(\alpha)\not=\alpha\rbrace=\kappa$ and $M_\lambda$ is closed under $\lambda$-sequences (that is, $^\lambda M_\lambda\subseteq M_\lambda$).
Now in the definition of supercompactness, the inner models $M_\lambda$ are allowed to vary with $\lambda$. We could define a large cardinal notion, uniform supercompactness, by removing this possibility: $\kappa$ is uniform supercompact if there is a single $M$ and $j$ such that $M$ is closed under all sequences of ordinal length and $j: V\rightarrow M$ is an elementary embedding with critical point $\kappa$. But in ZFC, this is not an interesting notion. First, assuming choice, $M$ is closed under sequences of ordinal length if and only if $M=V$ (since two models with the same ordinals and sets of ordinals are equal), so $ZFC\models$ "$\kappa$ is uniformly supercompact $\iff$ $\kappa$ is Reinhardt;" second, Kunen showed that Reinhardt cardinals are inconsistent with $ZFC$. (EDIT: as Joel points out, this statement doesn't actually make sense, as Reinhardt-ness is not a first-order property. One needs to pass to some extension of ZFC which can talk about proper classes directly, like Morse-Kelly set theory, which is the setting Kunen used for his proof.)
However, assuming $\neg$Choice, both of these points seem suspect. It is still open whether Reinhardt cardinals are consistent with $ZF$, and it is unclear to me that $ZF$ alone proves that uniformly supercompact cardinals are Reinhardt. So my questions are the following:
Question 1: Does $ZF\models$ every uniformly supercompact cardinal is Reinhardt?
Question 2: What is the consistency strength of $ZF+$ there exists a uniformly supercompact cardinal?
Obviously $ZF$ proves that every Reinhardt cardinal is uniformly supercompact; also obviously, Question 2 is really only interesting in lieu of a positive answer to Question 1. The most basic obstruction to a positive answer to Question 1 is the fact that given an elementary embedding $j: V\rightarrow M$ with $M$ closed under ordinal-length sequences and $crit(j)=\kappa$, the restriction of $j$ to $M$, $j\upharpoonright M: M\rightarrow M$ is not obviously (to me at least) an elementary embedding.


text:
Q: WinForm scaling incorrectly for some users I've written a program that I've used and have tested it on xp, win7 and win 10 with various resolutions.
The main form displays correctly with the controls properly spaced as follows:
Correctly Scaled Form
However, when submitting it for review, the forms do not scale for the tester's system. The controls are overlapping and get cut off by the form edges and looks like this:
Incorrectly Scaled Form
The form is designed to resize and adjust the controls which all works perfectly on any system I test, I have tried changing the "autoscalemode" to "font" or "off" but nothing changes how it loads on the testers system.
I have submitted other programs that have not had this issue so I am at a loss as to what it could be.


text:
Q: How do I configure Spring to use my factory when instantiating POJOs Person class is a simple POJO with 2 fields:
String name
String role

My @Configuration annotated class includes
@Bean
@ConfigurationProperties(prefix = "people")
public List<Person> people() {
    return new ArrayList()
}

and the yaml configuration file
people:
  - name: Maria
    role: Buyer
  - name: Ana
    role: Seller
  - name: Patrik
    role: Buyer

and when I @Autowire people I magically get a List<People> with 3 elements and all fields correctly set.
This is brilliant!
But now I want to control how Person is instantiated so that I have 2 implementations Buyer and Seller based on the role string. I would do that by using some sort of factory but unsure how to wire my factory with Spring.
Note: implementing the factory itself is assumed knowledge, I just want to know how to configure Spring to use my factory when instantiating Person.

A: I would make the following classes:
public interface Person {
    String getName();

    /**
     * @return role retrieved from configuration or else
     * {@code null} if used in extensions
     */
    default String getRole() {
        return null;
    }
}

@Getter
@AllArgsConstructor
public class Buyer implements Person {
    private String name;
}

@Getter
@AllArgsConstructor
public class Seller implements Person {
    private String name;
}

And then use them like:
@Bean
@ConfigurationProperties(prefix = "people")
public Set<Buyer> buyers() {
    return new ArrayList<Person>()
            .stream()
            .filter(person -> "Buyer".equals(person.getRole()))
            .map(person -> new Buyer(person.getName()))
            .collect(toSet());

}

@Bean
@ConfigurationProperties(prefix = "people")
public Set<Seller> sellers() {
    return new ArrayList<Person>()
            .stream()
            .filter(person -> "Seller".equals(person.getRole()))
            .map(person -> new Seller(person.getName()))
            .collect(toSet());

}

WARNING: I have not tested this approach and it is possible that configuration properties are not resolved. If so just make your own configuration properties object:
@Data
@Component
@ConfigurationProperties
public class PeopleConfigurationProperties {

    private List<Person> people;

}

And use these like:
@Bean
public Set<Seller> buyers(PeopleConfigurationProperties properties) {
    return properties.getPeople()
            .stream()
            .filter(person -> "Seller".equals(person.getRole()))
            .map(person -> new Seller(person.getName()))
            .collect(toSet());
}

All of the examples have not been tested, so sorry if any typos or inaccurates are present. Hope this helps


text:
Q: Making C++ Pi approximation running in Paralell on GPU Nvidia 970M CUDA's I got this code from The Chudnovsky formula for Pi approximation and I want to do it faster and faster. But I have no experience or idea of how to deal with GPU's. How to make this code runs on GPU Nvidea 970M? It's on C++. There's some easy lib to make it? With my processor it's running about 3~4s...
#include <iostream>
#include <windows>
#include <iomanip>
#include <cmath>

double fac(double num) {
    double result = 1.0;
    for (double i=2.0; i<num; i++)
       result *= i;
    return result;
}

int main() {
    using namespace std;
    double pi=0.0;
    for (double k = 0.0; k < 10.0; k++) {
        pi += (pow(-1.0,k) * fac(6.0 * k) * (13591409.0 + (545140134.0 * k)))
            / (fac(3.0 * k) * pow(fac(k), 3.0) * pow(640320.0, 3.0 * k + 3.0/2.0));
    }
    pi *= 12.0;
    cout << setprecision(100000000) << 1.0 / pi << endl;
system("Pause");
return 0;
}

A: Before delegating to a GPU with multiple cores, I suggest you optimize the algorithm with one core first.
Running Factorial Values
Your factorial function is always starting at 2.0 for each value of k.  This has the following calculations:
+----+-------------------+
| 1! | 1                 |
+----+-------------------+
| 2! | 1 * 2             |
+----+-------------------+
| 3! | 1 * 2 * 3         |
+----+-------------------+
| 5! | 1 * 2 * 3 * 4 * 5 |
+----+-------------------+

These time of these iterations will add up as the values of k get larger.
The factorial can be expressed iteratively as:
+----+--------+
| 1! | 1      |
+----+--------+
| 2! | 1! * 2 |
+----+--------+
| 3! | 2! * 3 |
+----+--------+
| 5! | 4! * 5 |
+----+--------+

In other words, the next factorial uses the previous factorial value and multiplies by the value of k.
Your main could look like:
    int main()
    {
      double k_factorial = 1.0;
      //...
      for (/* ... */)
      {
        if (k > 1.0) k_factorial *= k;
        //...
                / (fac(3.0 * k) * pow(k_factorial, 3.0) * pow(640320.0, 3.0 * k + 3.0/2.0));
    //...
  }

Since you have 3 different factorials:  fac(3.0 * k), fac(k), and fac(6.0 * k), you could use 3 different factorial variables and update their values inside the for loop.
Running pow variables
Similar to the factorial variables, you can have running values for the pow functions.
The pow(-1.0, k) can be replaced by:
double pow_sign = 1.0; // pow(-1.0, 0)
//...
for (//...
{
  pow_sign *= -1.0;
  pi += (pow_sign * //...

Also, we know that pow(x, 3) is the same as x * x * x.  Making the substitution:
pow(fac(k), 3.0) --> factorial_k * factorial_k * factorial_k
Algebraic Simplification
You can also simplify your assignment statement algebraically.
For example, make a table consisting of the following columns:
+-----+--------------+--------------+
|  k  | fac(6.0 * k) | fac(3.0 * k) |
+-----+--------------+--------------+
|  0  |              |              |
+-----+--------------+--------------+
|  1  |              |              |
+-----+--------------+--------------+

See if you notice any patterns.
Also rewrite the assignment vertically to see if you can simplify by factoring.
Exploiting GPU cores
Once you have optimized the calculation to a running or iterative approach, you can delegate to multiple cores.
The first step is to figure out how you can divide the work into pieces that can be run in parallel.
Split your calculations into three pieces and run (on one core).  Verify correctness.
Next step is to either research "c++ parallel programming" for instructions on how to run the program using parallel processing on your platform, or search the internet on "c++ use gpu multiple cores".
You want the amount of work that each core receives to consume more time that the overhead of setting up the cores.


text:
Q: When Merging Duplicate Contacts, is the Id of the Non-Master Record redirected to the Master Record? When two contacts are merged, does the Non-Master Record Id get added to a list somewhere? It seems like it should, to

*

*ensure that Id does not get used again,

*redirect that Id to the Id of the Master Record, or

*give one the ability to handle systems outside of SalesForce that store a reference to the Id of the Non-Master Record after a merge.

From what I can tell, the Non-Master Record just gets added to the recycle bin, where it is deleted in two weeks. Is this the whole story?

A: The loser(s) get the winner's Id written into MasterRecordId. Check Contact for example. Nothing is saved on winner record though so when the losers eventually get wiped from recycle bin the Id is really gone.(*)
If you want to persist such info - you have to do it yourself. SF doesn't save anything on master (*) because what do you think would happen when you merge 10 contacts into 1? If you want to save the values anyway - use a text field and not lookups ;)
Id won't be reused for sure. "Ensuring" is done internally.
If you need to notify external systems - it's your job again. Triggers will fire on merge, send your callouts from them for example?
If you're concerned - either track them with your own code or "soft delete" your records (tick some checkbox that will cause them to be assigned to user that's outside Role hierarchy, excluded in criteria-based sharing rules etc.). Users with "View all data" will still see them but otherwise they'll disappear from reports for example.

(*) Actually there's something that's retained for you out of the box - in the field history tracking tables. We can see the name of the merged record but queries won't show the id. So in your external systems scenarios you probably could only "identify suspect winners" that way:
SELECT Id, Field, NewValue, OldValue
FROM AccountHistory
WHERE Field = 'accountMerged'
LIMIT 10

Notes:

*

*The query result renders incorrectly in workbench.developerforce.com. Try with the Developer Console if you're getting funny results.

*If you plan to build your logic around history trackers be aware that it's royal paint to unit test the code - histories are written to tables only after successful commit.

*... and they can be truncated / shortened when you refresh a sandbox.


text:
Q: Matplotlib (Python) normalizing data Well I'm trying to normalize some (infrared) thermography data, to display it later.
However I'm stuck at normalizing, I could of course do it by hand, but I wonder why the matplotlib code is not working, the python code is shown below:
import numpy as N
import matplotlib.colors as colors

test2 = N.array([100, 10, 95])
norm = colors.Normalize(0,100)
for pix in N.nditer(test2, op_flags=['readwrite']):
    val = (norm.process_value(pix)[0])
    print (val)

img = norm.process_value(test2)[0]
print(img)

Now I expect vals OR img to show the correct processed data. Depending on what matplotlib.colors.Normalize.process_value actually should get as argument.
But in any case: both functions do not normalize and just return the original function.. Not on the [0, 1] interval at all.

A: The documentation of Normalize might be a bit deceiving here: process_value is a function which is only used for preprocessing (and static). The actual usage is described with this sentence:

A class which, when called, can normalize data into the [0.0, 1.0]
  interval.

Thus the normalization happens when you call the class:
import numpy as N
import matplotlib.colors as colors

test2 = N.array([100, 10, 95])
norm = colors.Normalize(0,100)
for pix in N.nditer(test2, op_flags=['readwrite']):
    val = (norm(pix))
    print (val)

img = norm(test2)
print(img)

Output:
1.0
0.1
0.95
[ 1.    0.1   0.95]


text:
Q: User authenication being lost on remoting call My administration page and webpart make calls to a service via .Net remoting.
I've added AD credential checking to the service and discovered that the calls being made from both the admin page and the web part are coming thru as "NT AUTHORITY\ANONYMOUS LOGON" instead of the logged-on user.
As a test, I've written a WinForms application that makes the same calls and the service is correctly figuring out the credentials.
So....is there some special code that I can add to my SharePoint code to get the correct username attached to the thread making the calls?

A: I assume the service is running on a seperate server? It sounds like uou are running into the classic "double hop" issue with authentication.
Here is one (of many) blog posts that describes the double-hop authentication issue.
Double-hop authentication: Why NTLM fails and Kerberos works
You have 3 choices:

*

*Configure Kerberos (doable)

*Configure Claims and re-instrument your .NET remoting service to support claims (complicated)

*Use the Secure Store Service and configure single sign-on


text:
Q: How do I add parent instance specific information to a has_many relationship? I am using the acts as taggable on steroids plugin and my web app has 4 models:

*

*Category

*Entry - acts as taggable and contains the following using single table inheritance

*

*Story

*Topic

Category has two important fields:

*

*tags:string - A list of tags associated with this category

*primary_tag:string - A single tag that gets assigned to any Topics created for the category

In the site have the following two pages:

*

*The Stories Page for a Category lists all stories tagged with that category's tags.

*The Topics Page for a Category lists all Topics AND Stories tagged with that category's tags.

The creation of Stories and Topics is as follows:

*

*When an Editor creates a Story they supply a list of tags to tag the story with.

*When a User creates a Topic it is created within the context of a Category. It is automagically tagged with the category's primary_tag upon creation.

I'm trying to define 3 has_many relationships for Category that uses tags to find associated Entries, Stories and Topics. If I were doing it in controller code I would use the following:
@category = Category.find(1)
@entries = Entry.find_tagged_with(@category.tags) # All Entries
@entries = Story.find_tagged_with(@category.tags) # Just Stories
@entries = Topic.find_tagged_with(@category.tags) # Just Topics

I'd like to make this an instance method of Category so that I call it just as follows:
@category.find(1)
@entries = @category.entries # All Entries
@entries = @category.stories # Just Stories
@entries = @category.topics  # Just Topics

I can't figure out how/what to specify in the :has_many declaration to specify the Class methods above to do the work using the category instance in question.
I've tried this:
has_many :entries do
  def tagged
    Entry.find_tagged_with(self.tags)
  end
end

But end up with the following error:
>> @category = Category.find(2)
=> #<Category id: 2, title: "Comics", description: "Comics", enabled: true, tags: "comics", created_at: "2009-06-22 13:29:52", updated_at: "2009-07-01 13:44:09", parent_id: nil, image: "", important: true, stories_enabled: true, topics_enabled: true, primary_tag: "comics">
>> @category.entries.tagged
NoMethodError: undefined method `tags' for #<Class:0x22781dc>

I've tried this.tags and reflection.tags but they all complaign about an undefined method, so there's something I definitely don't understand about the scope of the method.

A: I think you want to use proxy_owner instead of self.
Try this:
has_many :entries do
  def tagged
    Entry.find_tagged_with(proxy_owner.tags)
  end
end

I found a good reference on Association Extensions here.


text:
Q: remove a character from the end of a text string only if it is there in excel I have a list of file names in excel I need to Match with another list. Some of the file names contain extra characters that need to be removed first though. I have a formula that will remove special characters and spaces from the file names;
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($E8,"_",""),"-",""),".","")," ","")
But some of the file names contain an extra 1 at the end I need to remove, please see example;

*

*2AALNOR120114

*DCA CDE 12-01-14

*OPASDOCS120114

*TWASCE1202141

*TWASCE1203141

*STCSRA120120141

*STCSRA120220141
If anyone could give me a Formula solution that strips out the above special characters and the 1 at the end of the filename that would be great.
Bonus credit if you can also strip out the 20 from the STC files as well to output as STCSRA120114 instead of STCSRA12012014
Edit: For clarification, final result would ideally look like this;

*

*2AALNOR120114

*DCACDE120114

*OPASDOCS120114

*TWASCE120214

*TWASCE120314

*STCSRA120114

*STCSRA120214

Thanks,
Ben

A: Maybe:
=LEFT(A1,LEN(A1)-IF(RIGHT(A1,1)="1",1,0))

(Replace the first two instances of A1 above with a suitable version of your SUBSTITUTE formula, and the last with E8).
With substitution:
=LEFT(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(E8,"_",""),"-",""),".","")," ",""),LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(E8,"_",""),"-",""),".","")," ",""))-IF(RIGHT(E8,1)="1",1,0))

A sightly shorter version of the A1 one:
=LEFT(A1,LEN(A1)-(RIGHT(A1)="1"))


text:
Q: functions before handlers spring 3 Im new in Spring and in frameworks in general ...
I have some lines of code I want to execute in almost every handler.
For example I save my DB session and the authenticated user as httpSession attributes and for most of my handlers I have:
@RequestMapping(....)
public ModelAndView get(HttpSession ses){
   User u = ses.getAttribute("currUser");
   DBsession session = ses.getAttribute("DBsession");
   if( u==null ) new ModelAndView("redirect:login");
   ...
}

Is there any way for spring to do that for me and get the DBsession and authenticated User objects directly as handler param ?
@RequestMapping(....)
public ModelAndView get(User u, DBsession session ){
   ...
}

A: The proper way to do this is to use a custom WebArgumentResolver, which cleanly extends @RequestMapping annotated handler methods to resolve parameters. I used this mechanism to handle cleanly merging JPA entities and passing them to my controllers.
You can see an example of doing this here and here or Google for more, there are plenty.


text:
Q: Servlet Session HTTPClient I got a Servlet A which has a HTTPClient configured in it - declared a GetMethod which calls Servlet B (basically passing the url to the constructor of Servlet B".
In Servlet B I am setting some session vars and when the Servlet A gets back the control after the "execute" method but the session vars set in Servlet B are returning as null.
Servlet A
doPost(req,res)
      {
         HTTPClient client = new HTTPClient();
         GetMethod get =  new GetMethod("/ServletB.do");
         client.execute(get);

         System.out.println("Value of a is :: " + session.getAttribute("a")) ; //gives a NULL
}

Servlet B
doPost(req,res)
{
HTTPSession session = req.getSession();
session.setAttibute("a",a);
session.setAttibute("b",b);

}

Can you please let me know what my options are here to get around this issue?

A: You have at least two issues with your code:

*

*You need to pass your session id from servlet A in the HTTP request to servlet B. How the session id is passed between the client and server is container specific, but usually the session id is passed as an HTTP cookie.

*The servlet specification does not guarantee that changes in the session attributes are immediately visible to all servlets, if several servlets are simultaneously accessing the same session and one of the servlets are adding or replacing a new attribute.
Your best option is probably to move the business logic in servlet B to a separate class and use that class from both servlet A or servlet B. Or do you have some other strange reason for making an HTTP call from one servlet to a different servlet within the same web application instead of simply making a method call?

A: I can see you are calling executing a 'get' from A while you have given code of handling 'post' in B.
Also session you are using to retrieve parameter using session.getAttribute("a")) is different than 'session' seen by the B servlet.

A: The right solution depends on where those servlets are actually running.

*

*If those servlets are running at the same webserver and servletcontext, then just use RequestDispatcher#include(). They will have access to exactly the same session.
request.getRequestDispatcher("/anotherservlet").include(request, response);

*If those servlets are running at the same webserver, but a different servletcontext, then consider sharing the sessions so that they will share exactly the same session. It's unclear what servletcontainer you're using, so here's just a Tomcat-targeted example to give you some hints. Just set the crosscontext attribute of the both webapp contexs to true:
<Context crossContext="true">

*If those servlets are running at a different webserver, then you need to pass the data of interest as request parameters. That's your best bet, really. They won't and can't share the same session, that would be a security hole.
new GetMethod("http://example.com/ServletB.do?name1=value1&name2=value2");

If the data is relatively large, then consider a shared database so that you only need to pass the PK value around as request parameter.


text:
Q: Get Collection With HasOne Relationship In my User model in Laravel 5.2 I have a relationship setup with their status to the company.
public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status');
}

The CompanyUser table has a company_id, user_id, and status field
Then in my controller I do the following:
$company   = Company::find($company_id);
$users     = CompanyUser::where('company_id', $company_id)->pluck('user_id')->toArray();
$user_data = User::with('companyStatus')->find($users);

but when I dump the user_data array it has all of the users related to the company, but just shows null for their status relationship
{
   "id":2,
   "name":"Moderator",
   "email":"mod@company.com",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status":null
 }

If I however return just the User collection to the view, and iterate over each user and run
$user->companyStatus->status

the value displays, but I am trying to include this within the collection for a JSON API to consume.
UPDATE
I tried adding the foreign key to the select call on my relationship method:
public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status', 'user_id');
}

and it now returns the following:
{
   "id":2,
   "name":"Moderator",
   "email":"mod@company.com",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status": {"status":"1","user_id":"2"}
 }

Not sure if this is the best/correct method or not though.

A: Okay I figured it out.
I tried adding the foreign key to the select call on my relationship method:
public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status', 'user_id');
}

Then that returns:
{
   "id":2,
   "name":"Moderator",
   "email":"mod@company.com",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status": {"status":"1","user_id":"2"}
}

Without the foreign key Laravel obviously can't determine the related data on the other table.


text:
Q: POST to REST server by php I want to make a post to a server I have by using php.
I was thinking in curl but all examples I find, urlfy data and I have to send a json file but not in the url.
I already have the json in an array : 'key'=>'value'...
I have to add headers, I think I can with this:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));

but I don't knoe how to add my array and post it.
Any idea?
I need to add a json like this:
[{"a":"q",
  "b":"w",
  "c":[{
        "e":"w",
         "r":"t"
      }]
}]

A: Here how you can post the data using CURL, and as you mentioned you already have a json you can do so as
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'your api end point');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // $postfields is the json that you have
$request_headers = array();
$request_headers[] = 'HeaderName: HeaderValue','HeaderName2: HeaderValue2';
$request_headers[] = 'Content-Type: application/json','Content-Length: ' . strlen($postfields) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$response = curl_exec($ch);
curl_close ($ch);


text:
Q: Is it possible to render a variable that has template syntax in jinja2? I have a variable in my python code like:
template_var = "{{ a_macro('var') }}"

Is it possible to have that template_var rendered in my template? Doing the following prints it as-is:
{{ params.template_var}}

A: You didn't share code so I guess a_macro  is a user defined macro that you created and what you are doing is something like:
op = BashOperator(
    task_id='my_task',
    bash_command="python script.py --key {{ params.template_var}}",
    params={'template_var': "{{ a_macro('var') }}"}
    )

This is not going to work.
You can not pass Jinja macros with params. Templated values needs to be set directly in the templated field.
In the above example bash_command is a templated field so you need to do:
op = BashOperator(
    task_id='my_task',
    bash_command="python script.py --key {{ a_macro('var') }}",
    )

The same goes for any other Airflow operator.


text:
Q: Is this an $L^p-L^{\infty}$ operator? Let $1\leq p <\infty$ and let $p^{\prime}$ denote its conjugate exponent. Consider the following operator on Schwartz functions:
$$Tf(x)=\int_{0}^{\infty}t^{\frac{n}{2 p^{\prime}}-1}e^{-t}
\int_{|x-y|^2\leq t}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy dt,\qquad x\in \mathbb{R}^{n}.$$
I have tried to prove that $T$ is bounded from $L^{p}$ to $L^{\infty}$ but failed so far.
Young's inequality for convolution is not useful with the $y$-integral as $|\cdot|^{\frac{n}{p^{\prime}}}$ is not in $L^{p^{\prime}}(B(t))$ with $B(t)$ the standard ball centered at the origin with radius $t>0$.
Hardy-Little-wood-Sobolev inequality is not useful for obtaining $L^{\infty}$ boundedness.
One could look at the Hardy-Littlewood maximal operator $\displaystyle Mf(x)=\sup_{r>0} \frac{1}{B(x,r)} \int_{B(x,r)}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy$ since
$$\frac{1}{t^{\frac{n}{2}}}\int_{|x-y|^2\leq t}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy\leq  Mf(x).$$
The maximal operator is known to be bounded from $L^{p}$ to $L^{p}$ for all $1<p\leq \infty$ and from $L^1$ to weak $L^{1}$. I have no idea about the boundedness of $M$ from $L^p$ to $L^{\infty}$ when $p<\infty$.
Is it true that
$$\|Tf\|_{L^{\infty}}\leq C \|f\|_{L^{p}}$$
for any $1\leq p<\infty$ or is there a counterexample ?

A: The case $p = 1$ asks if $$\int_0^\infty t^{-1} e^{-t} \int_{|x-y|^2\leq t} f(y) dy dt \leq 1 $$
for every $f$ with $\int |f| = 1$. Just take $|f_n|$ a family approximating the identity with support on $B(0,1/n)$, then you see that the corresponding integral blows up.
For $n < 2p'$ (this includes the case that Giorgio Metafune considered), let $f$ be a smooth function that is concentrated on the dyadic annulus of size $2^{-k}$ with height 1. Then its $L^p$ norm is of size $2^{-kn/p}$.
For $\sqrt{t} \approx 2^{-k}$, the inner integral evaluates to the same value.
So the full integral is bounded below by
$$ 2^{-kn/p} \cdot 2^{-k(n/p' - 2)} $$
for $k > 0$.  So we see that when $n < 2p'$ taking $k\nearrow \infty$ you also get counterexamples to the boundedness.
I think with some work a similar counterexample can be made for $n = 2p'$. But I am not sure about what happens when $n > 2p'$.

A: No this is not true. Take $n=1$, $p=2$ and $$f(y)=\frac{1}{\sqrt {|y|} (|\log|y||)^\alpha}\chi_{(-1,1)}(y)$$ with $\frac 12 < \alpha <1$. Then $f \in L^2(\mathbb R)$ but the innermost integral diverges at $x=0$ for every $t>0$.
EDIT The same counterexample can be done for general $n$ and $1<p<\infty$ (the case $p=1$ is in the answer by @Willie Wong). Take $$f(y)=\frac{1}{{|y|^{\frac np}} (|\log|y||)^\alpha}\chi_{B_r}(y)$$ with $r<1$ and $\frac 1p <\alpha <1$. Then $Tf(0)=\infty$ and, by Fatou, $\lim_{x \to 0}Tf(x)=\infty$.


text:
Q: singularities of higher dimensional toric sections Is there any (general) theory on singularities of higher dimensional toric sections. I mean singularities of an intersection of an n-tori with a linear space. So for example singularities of the variety defined by
\begin{align*}
 x_1^2 + x_2^2 - 1 \\
 x_3^2 + x_4^2 - 1 \\
 x_5^2 + x_6^2 - 1 \\
 2\cdot x_1 - x_3 \\
 x_4 + x_5
\end{align*}
I'm mostly interested in a way to find them. I tried approaches with the principal minors of the jacobian. But there are soon (if you go to higher dimensions of the tori and/or linear spaces) too many polynomials, to compute a groebner basis.
I would very much appreciate a pointer to a resource of some kind, if there are any.
kind greetings,
Marc


text:
Q: Java Namespace - Two classes with the same name in different packages I am coming from Objective-C where we don't have packages and namespacing.
Android has android.text.format.DateFormat which has static methods that return java.text.DateFormat instances (getLongDateFormat() and getMediumDateFormat() specifically).

*

*Are these methods referred to as "static methods" or "class methods" or both interchangeably?

*Looking at Android documentation, how am I suppose to know that the android.text.format.DateFormat methods return a java.text.DateFormat instance and not an android.text.format.DateFormat instance (returning an instance of the latter is what I initially expected)?

*How do I import the necessary packages to be able to use both of these classes in my source?

*Is it possible to write my implementation code this way:

DateFormat df = DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());

The other way I would write it would be to use the full package names, but this seems unnecessary:
java.text.DateFormat df = android.text.format.DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());

A: Not sure why this is downvoted, it's a useful discussion.
1) I've always heard them referred to as "static methods".
2) The only way to see it is to follow the links. The documentation is definitely misleading in this case.
3/4) The typical way to do this in java is to not import one of the classes, and fully-qualify its class name. So if you elected to import java.text.DateFormat and not the android version, you'd do something like DateFormat df = android.text.format .DateFormat.getLongDateFormat(this.getActivity());

A: *

*From the JLS:

A method that is declared static is called a class method.

I would say that I hear "static method" used more often than "class method", but both are in use and should be understood by competent Java developers.

*The only option would be to hover the links on the return values. This is an example of extremely poor API design, with a name conflict built in, and the android.text.format.DateFormat should have been named something like DateFormatFactory. It appears that this class may have been intended to serve the same purpose as the java.text class originally and that API compatibility left it stuck. See java.sql.Date for a similar story.

*Using import is a convenience only, allowing you to use the simple class name in your code. It's always legal to use a fully-qualified class name, and the compiler translates imported class names into fully-qualified ones. You can't import multiple classes with the same name because then there's no way to distinguish them

*I suggest importing the class from java.text for two reasons: You'll probably be using it more often, and it's the more "standard" class. When faced with the choice of qualifying one of two classes with the same simple name, use the simple name for the one that developers would usually assume it refers to.


text:
Q: Laravel group by month with shop sales total I tried to build a Line chart where I have multiple shops and the monthly sales report will be shown with the shop name. I can achieve the monthly data or yearly data but how do I can get the groupBy Month sales total for each shop group array data as my desired line chart data? I share some of my code and screenshot. Please have a look and if you can help me. Thanks
shops table

sales table

my line chart expected data

I know I have to join sales and shops table and I can able to get the shops group data but how to get the shop group monthly sales total?
$sales = Sale::select(
            DB::raw('year(created_at) as year'),
            DB::raw('month(created_at) as month'),
            DB::raw('sum(total) as total'),
        )
            ->where(DB::raw('date(created_at)'), '>=', Carbon::now()->startOfYear())
            ->orderBy('month')
            ->groupBy('year','month')
            ->get()
            ->groupBy(['year', 'month']);


text:
Q: Add together lists of tuples I have two lists of integers:
xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]

I want to add the first element of xList to the first element of yList etc so that the output is as follows
[(6, 8), (10, 12)]

Any ideas that I can try using numpy or otherwise?

A: Using a list comprehension:
out = [tuple(map(sum, zip(*x))) for x in zip(xList, yList)]

Output:
[(6, 8), (10, 12)]

generalization
This works independently of the number of input lists. For more lists:
lists = [wList, xList, yList, zList]

out = [tuple(map(sum, zip(*x))) for x in zip(*lists)]

input of uneven size
Use itertools.zip_longest:
xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]
zList = [(1,1)]

from itertools import zip_longest
lists = [xList, yList, zList]
out = [tuple(map(sum, zip(*x)))
       for x in zip_longest(*lists, fillvalue=(0,0))]

Output:
[(7, 9), (10, 12)]

A: [(a[0] + b[0], a[1] + b[1]) for a, b in zip(xList, yList)]

A: For a pure-Python approach you can use operator.add(a, b) (returns a + b) from the operator module combined with the built-in functions map(function, iterable, ...) and zip(*iterables, strict=False). The map function "[r]eturn[s] an iterator that applies function to every item of iterable, yielding the results" and the zip function iterates over several iterables in parallel, successively yielding tuples of these elements.
import operator

xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]

res = [tuple(map(operator.add, a, b)) for a, b in zip(xList, yList)]
print(res)

Output
[(6, 8), (10, 12)]

A: x = np.array(xList)
y = np.array(yList)
print(x + y)

Output:
array([[ 6,  8],
       [10, 12]])

To make your exact desired output, though I doubt it'll matter:
print([*map(tuple, (x + y))])
...
[(6, 8), (10, 12)]

A: numpy is overkill for this problem. All you need is zip() and a list comprehension:
[(x1 + y1, x2 + y2) for (x1, x2), (y1, y2) in zip(xList, yList)]

This outputs:
[(6, 8), (10, 12)]


text:
Q: Numbering page of an existing document Using iTextSharp, I would like to get example or help in order to number each page of an existing PDF document using VB.net (Windows Form) in VB express 2010.

A: As the OP indicated that a c# example also suffices:
The second pass in the Webified iTextSharp Example TwoPasses.cs (after the comment "SECOND PASS, ADD THE HEADER") adds Page x of y (and a title FOOBAR FILMFESTIVAL) header to each document page.
The pivotal code:
PdfReader reader = new PdfReader(SOURCE_PDF);
using (MemoryStream ms2 = new MemoryStream()) {
    // Create a stamper
    using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
        // Loop over the pages and add a header to each page
        int n = reader.NumberOfPages;
        for (int i = 1; i <= n; i++) {
            GetHeaderTable(i, n).WriteSelectedRows(
              0, -1, 34, 803, stamper.GetOverContent(i)
            );
        }
    }
    // retrieve the result PDF in ms2.ToArray()
}

which uses the helper method GetHeaderTable which assembles the header text for a page:
public static PdfPTable GetHeaderTable(int x, int y) {
    PdfPTable table = new PdfPTable(2);
    table.TotalWidth = 527;
    table.LockedWidth = true;
    table.DefaultCell.FixedHeight = 20;
    table.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
    table.AddCell("FOOBAR FILMFESTIVAL");
    table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
    table.AddCell(string.Format("Page {0} of {1}", x, y));
    return table;
}


text:
Q: Clarify the concept of Multiple inheritance: Can a diamond structure issue occur? Suppose you have two interfaces I1 and I2 both the interfaces have the same method
1)public int add(int a) throws exception e1    //(Interface 1)

2)public int add(int a) throws exception e2    //(Interface 2)

now a class implements both I1 and I2.
@override
public int add(int a) exception e1
{
//adding operation
}

Note: I understand that if you implement multiple interfaces which have same method then only one implementation will be there in the implementing class.

*

*Does the compiler infer whether this method is from I1 or I2 based on the throws clause? Is method signature clarification required? (I know that signature include name and parameters passed.)

*If we have implemented both the interfaces and then we are throwing only e1 will the compiler allow this since the implementing class doesn't really implement both interfaces? will it cause diamond structure problem?

*Do we need to implement the same method with throws clause e1 and 2nd time e2? When I tried this the compiler told me I had duplicate methods.

*If we implement the I1 first then it says that it is I1's method and if we write the I2 first then it says its I2's method.  Explain why this is so.

A: An interface defines a contract. If an interface defines a method
void foo() throws SomeException;

then it says: all implementing classes must have a method foo, returning void, not taking any argument, and which is allowed to throw SomeException but no other type of checkd exception.
The implementing method may of course choose to not throw any exception at all, since it would not violate the contract of the interface method. throws means: this method might throw this exception in some circumstances.
So, a method declared as
public void foo();

in an implementing class is valid for the interface defined above.
So, in your example,
public int add(int a) throws Exception1

is a valid method declaration to override
int add(int a) throws Exception1

but is not valid for
int add(int a) throws Exception2

(unless of course Exception1 is a subclass of Exception2).
The only way, if there is no inheritance between Excption1 and Exception2, to implement both interfaces is to have a method that doesn't throw any exception. That is the only possibility to fullfill the two contracts.

A: With regard to overriding, only the parameter types of methods are considered (8.4.2); return types and throw types are  checked later in a separate step (8.4.8.3).
It is possible for a class to inherit multiple methods with override-equivalent
signatures. (8.4.8.4) There is no problem there. In your case, two methods are inherited, then both are overridden by one method.
My IDE IntelliJ correctly reports that the method overrides two methods in two super interfaces.
In Java 7 and earlier, there is no diamond problem. However since Java 8, interface methods can have implementations! Therefore the diamond problem can occur when a class inherits two methods from two interfaces. Javac may reject the code if such ambiguity exists. (There are ways to disambiguate).


text:
Q: (Scheme) Implementing 2-Dimensional List Access (access lst x y) I know this seems so trivial, but having only ever worked in declarative/imperative languages, I find myself having issues with this problem.
I have a checker-board (essentially an 8x8 list/array of states), and I need to be able to grab the (x y)th element of the board.
I figure given rest-of-board as board, if I can (rest rest-of-board) y-1 times, then return (first rest-of-board), I will have the row. Then if I (rest row) x-1 times, then return (first row), I will have the right element. Then I return with (result )?
     #lang scheme
     (define new-board '((P2 OFF P2 OFF P2 OFF P2 OFF)
                (OFF P2 OFF P2 OFF P2 OFF P2)
                (P2 OFF P2 OFF P2 OFF P2 OFF)
                (OFF BLANK OFF BLANK OFF BLANK OFF BLANK)
                (BLANK OFF BLANK OFF BLANK OFF BLANK OFF)
                (OFF P1 OFF P1 OFF P1 OFF P1)
                (P1 OFF P1 OFF P1 OFF P1 OFF)
                (OFF P1 OFF P1 OFF P1 OFF P1)))
     (define (get-state board x y))

A: Create an abstraction for this:
(define (make-board)
  (make-vector 64 'blank))

(define (board-ref board x y)
  (vector-ref board (+ (* y 8) x)))

(define (board-set! board x y new)
  (vector-set! board (+ (* y 8) x) new))

Go from there.
(define (board-fill board list-of-64-values) ...)    ;; for example

A: Maybe a vector of vectors would be a better representation here:
(define new-board
  (list->vector
   (map list->vector
        '((P2 OFF P2 OFF P2 OFF P2 OFF)
          (OFF P2 OFF P2 OFF P2 OFF P2)
          (P2 OFF P2 OFF P2 OFF P2 OFF)
          (OFF BLANK OFF BLANK OFF BLANK OFF BLANK)
          (BLANK OFF BLANK OFF BLANK OFF BLANK OFF)
          (OFF P1 OFF P1 OFF P1 OFF P1)
          (P1 OFF P1 OFF P1 OFF P1 OFF)
          (OFF P1 OFF P1 OFF P1 OFF P1)))))

(define (get-state board x y)
  (vector-ref (vector-ref board x) y))

(define (set-state! board x y val)
  (vector-set! (vector-ref board x) y val))

then
> (get-state new-board 0 1)
OFF
> (get-state new-board 1 1)
P2

> (set-state! new-board 1 1 'hi)
> (get-state new-board 1 1)
'hi