text:
Q: Convert python objects to python AST-nodes I have a need to dump the modified python object back into source. So I try to find something to convert real python object to python ast.Node (to use later in astor lib to dump source)
Example of usage I want, Python 2:
import ast
import importlib

import astor

m = importlib.import_module('something')

# modify an object
m.VAR.append(123)

ast_nodes = some_magic(m)

source = astor.dump(ast_nodes)

Please help me to find that some_magic

A: There's no way to do what you want, because that's not how ASTs work.
When the interpreter runs your code, it will generate an AST out of the source files, and interpret that AST to generate python objects.
What happen to those objects once they've been generated has nothing to do with the AST.
It is however possible to get the AST of what generated the object in the first place.
The module inspect lets you get the source code of some python objects:
import ast
import importlib
import inspect

m = importlib.import_module('pprint')
s = inspect.getsource(m)
a = ast.parse(s)
print(ast.dump(a))
# Prints the AST of the pprint module

But getsource() is aptly named.
If I were to change the value of some variable (or any other object) in m, it wouldn't change its source code.
Even if it was possible to regenerate an AST out of an object, there wouldn't be a single solution some_magic() could return.
Imagine I have a variable x in some module, that I reassign in another module:
# In some_module.py
x = 0

# In __main__.py
m = importlib.import_module('some_module')
m.x = 1 + 227

Now, the value of m.x is 228, but there's no way to know what kind of expression led to that value (well, without reading the AST of __main__.py but this would quickly get out of hand). Was it a mere literal? The result of a function call?
If you really have to get a new AST after modifying some value of a module, the best solution would be to transform the original AST by yourself.
You can find where your identifier got its value, and replace the value of the assignment with whatever you want.
For instance, in my small example x = 0 is represented by the following AST:
Assign(targets=[Name(id='x', ctx=Store())], value=Num(n=0))

And to get the AST matching the reassignment I did in __main__.py, I would have to change the value of the above Assign node as the following:
value=BinOp(left=Num(n=1), op=Add(), right=Num(n=227))

If you'd like to go that way, I recommend you check Python's documentation of the AST node transformer (ast.NodeTransformer), as well as this excellent manual that documents all the nodes you can meet in Python ASTs Green Tree Snakes - the missing Python AST docs.

A: What Vladimir is asking about is certainly useful for compiler optimizations. Indeed, there are ways to accomplish that using the ast library. Here is a simple example demonstrating evaluation of constant functions:
from ast import *
import numpy as np

PURE_FUNS = {'arange' : np.arange}
PROG = '''
A=arange(5)
B=[0, 1, 2, 3, 4]
A[2:3] = 1
C = [A[1], 2, m]
'''

def py_to_ast(o):
    if type(o) == np.ndarray:
        return List(elts=[py_to_ast(e) for e in o], ctx=Load())
    elif type(o) == np.int64:
        return Constant(value=o)
    # Add elifs for more types here
    else:
        assert False

class EvalPureFuns(NodeTransformer):
    def visit_Call(self, node):
        is_const_args = all(type(a) == Constant for a in node.args)
        if node.func.id in PURE_FUNS and is_const_args:
            res = eval(unparse(node), PURE_FUNS)
            return py_to_ast(res)
        return node

node = parse(PROG)
node = EvalPureFuns().visit(node)
print(unparse(node))


text:
Q: ForEach Loop not hitting IF Statement I am struggling to make my foreach loop work for some property records.
The data consists of jobs against property numbers- below are the column names
Id
parentpropertyId
status = 1(open) =5(closed)
reviewedJob
jobTrigger
The first condition works fine when STATUS = 1 (which is open)
The second condition doesn't get hit STATUS = 5 (Which is Closed)
It just breaks out of the loop without even hitting the second condition when the STATUS is definitely 5 (closed).
Anyone got any ideas why my code breaks out of the loop even if the status is 5 but hits fine if status is 1
foreach (DataRow dr in selectedProperty.Rows)

if (Convert.ToInt16(selectedProperty.Rows[i]["Type"]) == Convert.ToInt32(JobType.HazardManagementAlert))

//variables declared///
{
String Id = selectedProperty.Rows[i]["Id"].ToString();
String parentpropertyId = selectedProperty.Rows[i ["ParentpropertyId"].ToString();
String status = selectedProperty.Rows[i]["Status"].ToString();
String reviewedJob = selectedProperty.Rows[i]["ReviewedJob"].ToString();
String jobTrigger = selectedProperty.Rows[i]["JobTrigger"].ToString();

//condition 1 - THIS WORKS//

if (status == "1" && jobTrigger != Convert.ToInt32(JobTrigger.SelfExpiring).ToString())                                        {
DialogResult newmessageBoxResult;
newmessageBoxResult = FriendlyMessageBox.Show("There is an existing open Hazard Management Alert job for this property: "
+ "  Job Number:"
+ Environment.NewLine
+ Strings.ToFriendlyJobNo(Id) + "."
+ Environment.NewLine
}

//condition 2- will not hit and exits the loop///
 else if ( status == "5")
 {
DialogResult newmessageBoxResult;
newmessageBoxResult = FriendlyMessageBox.Show("There is an existing closed Hazard Management Alert job to be reviewed for this property Job Number: "
 + Strings.ToFriendlyJobNo(Id) + "."
 + Environment.NewLine
 + "Click OK to  create a temporary self expiring Hazard Management Alert for this property or Cancel and review and edit the existing Hazard Management Alert."
 + Environment.NewLine

I have tried to run through the code whilst debugging, whenever the status is 5 it'll break out the loop. It will not even hit either of the conditions

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best way to prevent IE from Caching Ajax Calls? I was working on an MVC 5/Jquery project and we encountered an issue on IE 10/11. Internet explorer is caching succeeding ajax calls.
We solved this problem by
disabling cache on every jQuery ajax calls:
$.ajaxSetup({
                cache: false,
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                }
            });
disabling caching on the server side/Controller:
    // GetFolderDetails is the Action being called through ajax.
    public ActionResult GetFolderDetails(long folderId)
    {
        // Code Here...

        TurnOffResponseCaching();
        return PartialView(PartialView_FolderDetails, selectedFolder);
    }
    private void TurnOffResponseCaching()
    {
        Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
        Response.Cache.SetRevalidation(System.Web.HttpCacheRevalidation.AllCaches);
    }

Both of this solutions solved the problem.
Between the two, what is the best way to disable caching on every ajax calls?


text:
Q: How would I have multiple selenium browsers running at the same time? I am currently making a script utilizing selenium. I would like multiple "tasks" to be running at the same time. How would I write code to have the same code running multiple times at once?

A: You can use threading for this. Here's a short example:
from selenium import webdriver
import threading

def go_to_example(driver):
    driver.get('https://example.com')

drivers = []
for _ in range(3):
    drivers.append(
        webdriver.Chrome()
    )
threads = [threading.Thread(target=go_to_example, args=(d,)) for d in drivers]
for t in threads:
    t.start()
for t in threads:
    t.join()


text:
Q: How can I bring back the title bar in Nautilus and Document viewer? I've noticed that the classical title bars are missing from Nautilus and Document Viewer. It has been going for a sleeker hidden title bar. However, I prefer the older version. Is there anyway to bring back normal title bars?

A: You can get your classical title bar back by installing gtk3-nocsd using Synaptic package manager or the command line:
sudo apt install gtk3-nocsd

While this will perfectly answers your question as you asked it, note that this will not bring back a classical menu bar. This package merely returns control of the windows decorations (titlebar, window control buttons) to your window manager.
More information on how to configure the tool can be found on the projects Github page.


text:
Q: creating a leaderboard for noughts and crosses game {"Bob": 50,"Jane": 2,"Sarah": 5, "Amelia": 20}

I have a txt file like this and I wrote a code to be able to get different players name and score that will be saved to the dictionary from highest to lowest.but when ever a new player saves their name&score, my txt file create a new dictionary like this ("
{"tie": 0}{"bobby": 0}

").
here is my code>
import json
import os
def save_score(score):
    filename = 'leaderboard.txt'
    player = input('what is your name')
    dictionary = {}
    if os.path.exists(filename):
        with open("leaderboard.txt", "a") as leaderboard:
            dictionary[player]=score
            json.dump(dictionary,leaderboard)
        print("score"+ " " + str(score)+ " "+ "for" + " " +str(player)+ " "+"saved.")
    return

I want to be able to append and also update the new players name and score to the existing dictionary.
eg. if bob plays and gets 5{"bob": 5}, and he plays again and gets 7. instead of creating a new dictionary for bob it should update {"bob": 5} to {"bob": 6}.
and also if new users play the game, their name and score should be added to the same dictionary with bob. {"bob": 5}. instead of creating a new dictionary.
so instead of this {"bob": 5} {"tina": 5}. I want to have this {"bob": 5, "tina": 1}.
please how do I go on about it?. thanks in advance.

A: First load the scores from the file with json.load, then change the score of the specific player, then save the scores back to the file with json.dump.
Opening the file twice with different modes is necessary to overwrite the old dictionary in the file with the new dictionary rather than appending to the file.
with open("leaderboard.txt", "r") as leaderboard:
    dictionary = json.load(leaderboard)

dictionary[player] = score

with open("leaderboard.txt", "w") as leaderboard:
    json.dump(dictionary,leaderboard)


text:
Q: Import Keystore protected with password inside glassfish I trying to put inside glassfish a keystore but it didn't work, it is located inside the config folder of my domain and I have putted into the glass fish panel the alias and the name of the key store, as you can see in te image below:
glassfish panel
can You help me?!
What I have to do?


text:
Q: Signed to Unsigned and Vice Versa (arithmetical) How to convert a number from unsigned to signed?
signed: -32768 to 32767
unsigned: 0 to 65535
I am solving the problem in JavaScript. The situation is that I have a number that goes e.g. from 0 to 65535 and I want to convert it to a reasonable signed value.
e.g.: 65535 should become -1.
Please do not use any bit related operations but something arithmetical.
I guess this should be language independent assuming that we use a data type that is big enough.
Update:
Implementation according to the answer further down:
function convertWordToShort(ival) {
    if (isNaN(ival) === false) {
        if (ival > 32767) {
            ival = ival - 65536;
        }
    }
    return ival;
}
function convertShortToWord(ival) {
    if (isNaN(ival) === false) {
        if (ival < 0) {
            ival = ival + 65536;
        }
    }
    return ival;
}
function convertIntToDWord(ival) {
    if (isNaN(ival) === false) {
        if (ival < 0) {
            ival = ival + 4294967296;
        }
    }
    return ival;
}
function convertDWordToInt(ival) {
    if (isNaN(ival) === false) {
        if (ival > 2147483647) {
            ival = ival - 4294967296;
        }
    }
    return ival;
}

A: Just test if the number is over halfway, then subtract the modulus.
if(x > 32767) {x = x - 65536;}

A: In the case that you would be looking for bitwise operation related answers, you could try the following:

*

*to convert something akin to a 16 bit unsigned integer (i.e 0 <= n <= 65535) to a 16 bit signed one:

(number << 16) >> 16

*

*Or:

new Int16Array([number])[0]

Where number in both cases is your 16 bit number.
As a side note the reason the first solution works is because if you bit shift to the right 16 times, the most significant bit of your 16 bit number will actually become the most significant bit of the 32 bit JavaScript integer (so if the most significant bit was a 1, it'd make the number negative), and so when you shift it to the left 16 times it'd shift while keeping the standard 2s complement form and retain the value/sign it gained from being shifted to the right previously, see this Wikipedia article for more:
https://en.m.wikipedia.org/wiki/Arithmetic_shift

A: function signed(bits, value) { return value & (1 << (bits - 1)) ? value - (1 << bits)  : value; }
signed(8, 0xFF); // returns -1
signed(16, 0xFF); // returns 255


text:
Q: How to mock a setter method using Mockito that has multiple parameters My Question is how to use Mockito's doAnswer to call the original method and with my own test parameters. To complicate matters, one of the parameters is not a primitive. It's a custom class.
Given the following:
public class EnvironmentQualityStatus {
    public int environmentQuality = EnvironmentQualityStatus.NA;
    public long cht = -1;
    public int environmentSubType = -1;
    public String engineer="";
    public int engineerType = -1;
    public long timeStamp = 0;
    public static final String version = "tpv1";

    EnvironmentQualityStatus(){}

    EnvironmentQualityStatus(int environmentQuality, long cht, int environmentSubType, String engineer, int engineerType) {
        this.environmentQuality = environmentQuality;
        this.cht = cht;
        this.environmentSubType = environmentSubType;
        this.engineer = engineer;
        this.engineerType = engineerType;
        timeStamp = System.currentTimeMillis();
     }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("ts: ");
        sb.append(timeStamp);
        sb.append(", quality: ");
        sb.append(EnvironmentQualityStatus.valueOf(environmentQuality));
        sb.append(", cht: ");
        sb.append(cht);
        sb.append(", type: ");
        if (engineerType == Engineers.TYPE_CIVIL) {
            sb.append("civil");
        } else if (engineerType == Engineers.TYPE_INDUSTRIAL) {
            sb.append("industrial");
            if (!TextUtils.isEmpty(engineer)) {
                sb.append(", Engineer: ");
                sb.append(engineer);
             }
         } else {
             sb.append("n/a");
         }
         return sb.toString();
    }
}

Taking into use the code above to set some stuff in a class. It's this call (and others like this) that I'd like to mock using Mockito.
public class EnvironmentQuality {
...
public void updateEnvironmentQuality(EnvironmentQualityStatus eqStatus ,
                                      int environmentQuality ,int cht , String engineer, boolean notify ){
        //set some stuff....
    }
}

I understand that using Mockito's doAnswer is the right way to do this. I just can't figure out how to wire up the very last part, where I manipulate the called values with my own so that the program that uses them at test-run-time gets my values. I've read Mockito docs as well as several SO posts around this topic, but it's still not clear to me.
EnvironmentQuality environmentQuality = spy((EnvironmentQuality)EnvironmentQuality.getInstance(context));

    spy(environmentQuality).updateNetworkQuality(Mockito.any(com.something.internal.EnvironmentQualityStatus.class), anyInt(), anyInt(), anyString(), anyBoolean());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {

            //This is an example of how to spy the parameters that were passed.
            EnvironmentQualityStatus status = (EnvironmentQualityStatus)invocation.getArguments()[0];

            int environmentQuality = (int)invocation.getArguments()[1];
            int cht = (int)invocation.getArguments()[2];
            String engineer = (String)invocation.getArguments()[3];
            boolean notify = (boolean)invocation.getArguments()[4];

            //But how to customize the parameters so that every time updateEnvironmentQuality(...) is called, a test can customize the params and dynamically influence the values.
            return null;
        }
    }).when(environmentQuality).updateEnvironmentQuality(Mockito.any(com.something.internal.EnvironmentQualityStatus.class), anyInt(), anyInt(), anyString(), anyBoolean());

A: So I assume you want to invoke the method with other values. By checking the documentation of InvocationOnMock you can check how to get the Method and the Object that is called. So this should be quite easy to modify:
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object callingObject = invocation.getMock();
        Method method = invocation.getMethod();
        method.invoke(callingObject, /* arguments... */);
        return null;
    }


text:
Q: Moving Player Up by holding left mouse button /space Microsoft VIsual Studio (Unity) I'm not so good with Visual Studio.
I'm making a simple game and my gameobject (player) should move up when Space or Left Mouse Button is pressed.
Here is my code
using UnityEngine;
using System.Collections;

public class PixelMovement : MonoBehaviour {

    Vector3 velocity = Vector3.zero;
    public Vector3 PressVelocity;
    public float maxSpeed = 5f;
    public float fowardSpeed = 1f;

    bool didPress = false;

    // Use this for initialization
    void Start () {

    }

    //Do Graphic & Input updates
    void update() {
        if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
            didPress = true;
        }
    }

    //Do physics engine updates here
    void FixedUpdate () {
        velocity.x = fowardSpeed;
        if (didPress == true){
            didPress = false;
            velocity += PressVelocity;
        }

        velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
        transform.position += velocity * Time.deltaTime;
    }
}

So, it should move like contrary to gravity. And when it stops holding, it continues to fall. I already have gravity I just need that "Up movement"

A: //Do Graphic & Input updates
void update() {
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
        didPress = true;
    }
}

I think the problem is because update() should be Update()
Try:
//Do Graphic & Input updates
void Update() {
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
        didPress = true;
    }
}

A: This is a quick fix:  You're calling Input.GetKeyDown() and Input.GetMouseButtonDown() which only return true on the first frame that the button is pressed.
If you want a repeating event (I.E., the mouse button or space is held down), use Input.GetKey(KeyCode.Space) and Input.GetMouseButton(0).


text:
Q: Is there any way/function in boost to check if file is in INI format? I am new to boost library and my requirement is that I want to take the configuration file as a input from the user for my application. However, the file from the user should be in ini format, if it's not then I should prompt the user about that.
So, is there any way/function in boost which can tell us if the given file is in INI format?
Thanks!


text:
Q: Ubuntu 20.04 (update broke system stuck at "a start job is running") BACKGROUND:
So I updated Ubuntu today.
Nvidia appears to have made Nvidia driver 460 unavailable which is what my system was using.
So I swapped to Nvidia 510 using:
sudo apt-get install nvidia-driver-510
Then I rebooted and my desktop failed to boot.
I went into the recovery mode and swapped to the xorg drivers.
After this my system booted fine. Unfortunately, I was unable to do GPU related tasks and my GPU wasn't being utilized probably.
So I attempted to swap to 510 again and updated some drivers.
Upon restarting my system failed to boot.
I jumped into the recovery mode and ran the following command:
apt purge nvidia && apt install nvidia-driver-510
I then ran modprobe Nvidia and it worked. Nvidia-smi also connected great!
THE ACTUAL ISSUE:
I tried to boot the system after successfully fixing Nvidia 510. However, I'm now stuck at "a start job is running" with no time limit.
I attempted opening the recovery menu but keyboard is frozen and I can't select root.
No idea where to go from here. My system seems completely bricked.

A: You should be able to get into your computer this way:
Go to your login screen and press CTRL-ALT-F2, to get to the console.
At the console prompt, login with your username and password.
Once you're at your shell prompt, type sudo apt install nvidia-driver-460 to get back to your working driver.  Then reboot.
(This worked for me when trying to upgrade from the 470 driver to the 510 driver, which upgrade failed.)
Another way would be to -- before you get to your login screen -- press ESC (or whichever key puts you at the GRUB menu), select "advanced", and then select "drop into a root shell" and type sudo apt install nvidia-driver-460 from there. Good luck!


text:
Q: HAproxy ssl re-encryption and http header modification I want to use my Haproxy 1.6.5 as Https load balancer before my https servers but I stuck with a problem of misunderstanding .
I want this behaviour: haproxy is available as https://example.com but behind it there are several https servers with self signed certs which I can't switch to http.
So I configured my tcp frontend for this as
frontend tcp_in
       mode tcp
       option tcplog
       bind *:443 ssl crt /etc/ssl/certs/server.bundle.pem
       maxconn 50000

   tcp-request inspect-delay 5s
   tcp-request content accept if { req.ssl_hello_type 1 }

   acl example_acl req.ssl_sni -i example.com
   use_backend special_example if example_acl

After this I want to send my traffic to one of the backends, but the point is I want to request something like https:\eimA.customer.local from backend1 and https:\eimB.customer.local from backend2
My guess is that I need to rewrite host header in request. (Probably it won't work in tcp mode. So how can I modify the config to do that ?)
My backend config is :
backend special_eims
        mode tcp
        option tcplog
        balance roundrobin
        stick-table type binary len 32 size 30k expire 30m
        acl clienthello req_ssl_hello_type 1
        acl serverhello rep_ssl_hello_type 2
        tcp-request inspect-delay 5s
        tcp-request content accept if clienthello
        tcp-response content accept if serverhello

        server eim1 eimA.customer.local:443 check
        server eim2 eimA.customer.local:443 check

        stick on payload_lv(43,1) if clienthello
        stick store-response payload_lv(43,1) if serverhello

As a result from my config I receive ssl connection error in browser
and
curl -v https://example.com/default -k
* About to connect() to example.com port 443 (#0)
*   Trying 127.0.0.1... connected
* Connected to example.com (127.0.0.1) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* warning: ignoring value of ssl.verifyhost
* NSS error -12263
* Closing connection #0
* SSL connect error
curl: (35) SSL connect error

Direct connect to backend server with https: // ip-address/default returns 404 error so only https: //eimA.customer.local/default format are allowed.
Please help, sorry if the question is dumb.

A: I solved it after some time.
1. I switched from tcp to http mode, because in tcp mode you cannot get http header info.
2. Used real domain names in server statements and used http-send-name-header Host which basically sets host header to the name after server directive
3. For re-encryption mode front-end certificate is mandatory.
    frontend CUIC_frontend
           mode http
           bind *:443 ssl crt  /etc/ssl/certs/ssl-cert.pem
           option forwardfor
           option http-server-close
           reqadd X-Forwarded-Proto:\ https
    default_backend App_Backend
....
backend App_Backend
        mode http
        balance roundrobin
        http-send-name-header Host
        server full-application1-domain-name  10.10.10.1:443 cookie app1 check ssl verify none
        server full-application2-domain-name 10.10.10.2:443 cookie app2 check ssl verify none


text:
Q: Create Sequence Permission for Postgres When my postgres function is tries to create a new sequence, it returns a permission denied error. It looks like the only way to make it work is to give Create permission on schema using the below statement.
GRANT CREATE ON SCHEMA public to "myuser"

But, this will allow the user to create any other type of object as well, including tables. How can we control this? I want my user to be able to create a sequence, but not tables.
Note: Create is not a valid grant on Sequences.

A: There is no way to do this using permissions. The only option would be to create an event trigger that throws an exception if an undesirable object is created.


text:
Q: Simpler way to pass scope variables into a service? I have a controller with many $scope.variables
$scope.users = userService.getUsers();
$scope.selectedAvailableGroups;
$scope.selectedAssignedGroups;
$scope.availableGroups;
$scope.assignedGroups;

I have functions in my controller which uses a service and the service needs arguements passed to it:
$scope.removeUserFromGroup = function (){
  userService.removeUserFromGroup($scope.selectedUser,$scope.selectedAssignedGroups, $scope.availableGroups, $scope.assignedGroups)
};

Has you can see, the removeUserFromGroup function is taking in 4 arguments, but the name is long and it doesn't really seem efficient.
Is this really the best way to do this or am I doing something wrong?
I have a function called addUserToGroup and it's using basically the exact same arguements, seems redundant that I'd need to pass that information to the service again.

A: Although it really depends on the application, perhaps the variables in your scope have more to do with business logic and should be stored in the service. If they are needed by the view, the controller can access and scope the variables from the service, but does not need to send all of them back to the service except when they change.

A: If you're concerned about readability, you could format the call like this (which I think reads a bit better):
$scope.removeUserFromGroup = function (){
    userService.removeUserFromGroup(
        $scope.selectedUser,
        $scope.selectedAssignedGroups,
        $scope.availableGroups,
        $scope.assignedGroups
    );
};

If you're really bothered about the number of parameters, and they're likely to increase, you could pass them as properties of a single object:
$scope.removeUserFromGroup = function (){
    userService.removeUserFromGroup({
        selectedUser: $scope.selectedUser,
        selectedGroups: $scope.selectedAssignedGroups,
        availableGroups: $scope.availableGroups,
        assignedGroups: $scope.assignedGroups
    });
};


text:
Q: OpenLayers-5 reproject OSM in a custom projection Following OpenLayers examples, I try to reproject OSM in a custom projection. The view is empty, no OSM tile is downloaded.
index.js :
import {get as getProjection} from 'ol/proj';
import Map from 'ol/Map';
import 'ol/ol.css';
import OSM from 'ol/source/OSM';
import proj4 from 'proj4';
import {register} from 'ol/proj/proj4';
import TileLayer from 'ol/layer/Tile';
import TileWMS from 'ol/source/TileWMS';
import View from 'ol/View';
import * as Gp from 'geoportal-extensions-openlayers';

proj4.defs('EPSG:2154','+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3' +
'+x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
register(proj4);
var franceProjection = getProjection('EPSG:2154');

 var couches = [
  new TileLayer({
  source: new OSM()
})
];
var map = new Map({
 target: 'map',
 layers: couches,
 view: new View({
projection: 'EPSG:2154',
center: [524326, 6700656],
zoom: 14
 })
});

package.json
{
"name": "iliad_ol5.3.0",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"geoportal-extensions-openlayers": "^3.0.7",
"ol": "^5.3.0",
"proj4": "^2.6.0"
},
"devDependencies": {
"parcel-bundler": "^1.12.4"
},
"description": ""
}

I know that it is a basic projection issue but even that's hard for me.

A: The code below works without any problems, so there must be problem either in your environment (imports) or in your code after removing map.setView( function.
proj4.defs('EPSG:2154','+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3' +
'+x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
ol.proj.proj4.register(proj4);
var franceProjection = ol.proj.get('EPSG:2154');

var couches = [
  new ol.layer.Tile({
    source: new ol.source.OSM()
  })
];
var map = new ol.Map({
 target: 'map',
 view: new ol.View({
  projection: 'EPSG:2154',
  center: [524326, 6700656],
  zoom: 14
 }),
 layers: couches
});


text:
Q: Getting a senior job without the yrs of experience asked for My manager in my current company feels that I am selling myself short by getting another job - but as a senior. He feels I have sold myself short and missing out on a good salary by getting another junior job, given how he (my manager) has a lot of faith in my development skills.
However, I have not worked long enough for a proper senior job (5 years +) but then the senior developer we do have in my current company isn't given senior tasks (judged by difficulty).
How would I get a senior job if I lack the commercial experience? My manager still feels without that, I have the ability/knowledge (I help my manager with C# too).
Thanks

A: Network and see if a friend/colleague who knows your up to the challenge can help you get into something more at your level.  If you're dealing with a stranger who is just trying to put checks in a box I don't think you'll have much luck.

A: I think its all about selling yourself. Also in some companies they promote their developers to "senior software engineer" after one year, such as Accenture. A title doesn't necessarily have a required amount of years of experience attached to it.

A: Try for a Sr. programmer job and take a good referral letter from your current manager to help make your case.
However, if you just can't make the argument, take a Jr. programmer job somewhere else and PROVE to them that you deserve to be a Sr. Programmer. If your current manager is correct, then you should have no trouble doing that.

A: Another line is to see if you can find companies looking for intermediate/senior developers as this would be a way to get your foot in the door.  Lastly, don't forget that what one companies calls senior may not be the same somewhere else so one could have little experience yet still get a senior title as the company believes that may make one happier than other stuff.


text:
Q: Entity Framework 6 Code First Fluent API Table Mapping I have a table in an existing database that looks something like this:
PK
FK
Col1
Col2
Col3
Col4
Col5

I need to get it into a class hierarchy like this:
public abstract class BaseClass : Entity
{
    public int PK {get; set;}
    public string Col1 {get; set;}
}

public class Child1 : BaseClass
{
    public string Col2 {get; set;}
    public string Col3 {get; set;}
}

public class Child2 : BaseClass
{
    public string Col4 {get; set;}
    public string Col5 {get; set;}
}

I am currently using the Fluent API to configure the entities like so:
public abstract class BaseClassConfig<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : Entity
{
    public BaseClassConfig()
    {
        ToTable("TheTableName");
        HasKey(x => x.Id);

        Property(x => x.Col1).HasColumnName("SomeName");
    }
}

public class Child1Config : BaseClassConfig<Child1>
{
    public Child1Config()
    {
        Property(x => x.Col2).HasColumnName("SomeName");
        Property(x => x.Col3).HasColumnName("SomeName");
    }
}

public class Child2Config : BaseClassConfig<Child2>
{
    public Child2Config()
    {
        Property(x => x.Col4).HasColumnName("SomeName");
        Property(x => x.Col5).HasColumnName("SomeName");
    }
}

When I added these to the context the inherits from DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new Child1Config());
    modelBuilder.Configurations.Add(new Child2Config());
}

I get the following error:

The entity types 'Child1' and 'Child2' cannot share table 'TheTableName'
  because they are not in the same type hierarchy or do not have a valid
  one to one foreign key relationship with matching primary keys between
  them.

I had a look at this article: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application
But it does not really talk about using the fluent api to configure the types, rather directly adding them to the context via DbSet<>.
How do I setup a single table to map to different classes through a base class using the fluent api?

A: A good reference I turn to a lot is this MSDN article: Configuring/Mapping Properties and Types with the Fluent API
In it you'll see a reference to the Table-Per-Hierarchy (TPH) Inheritance pattern. Essentially what you are missing is a discriminator field (and based on the error, the FK is also not mapped).
By default, the discriminator column is called Discriminator, but as you can see from the article, this can be customized in the code-first mapping:
modelBuilder.Entity<Course>()
    .Map<Course>(m => m.Requires("Type").HasValue("Course"))
    .Map<OnsiteCourse>(m => m.Requires("Type").HasValue("OnsiteCourse"));

In the above example, Type is the discriminator which allows EF to know which entity type to materialize i.e. entity Course when Type == "Course".


text:
Q: Sideways Number Pyramid With Spaces Java Sorry for asking such a simple question, but I've been stuck on this for a while. I need to have a program print out a sideways pyramid with increasing numbers and with spaces between each number. I have done star pyramids with for loops before, but I am unable to make a sideways one with numbers like this:
                           10
                        9 10
                     8 9 10
                  7 8 9 10
               6 7 8 9 10
            5 6 7 8 9 10
         4 5 6 7 8 9 10
      3 4 5 6 7 8 9 10
      10 9 8 7 6 5 4 3 2

1 2 3 4 5 6 7 8 9 10
   2 3 4 5 6 7 8 9 10
      3 4 5 6 7 8 9 10
         4 5 6 7 8 9 10
            5 6 7 8 9 10
               6 7 8 9 10
                  7 8 9 10
                     8 9 10
                        9 10
                           10
This is what I tried so far, it prints the right pyramid, but I can't get the spaces between the numbers to work.
      int n = 10;

      for(int column = -n; column <= n; column++)
      {
          if (column == 0) column = 2;
          for(int row = 1; row <= n; row++)
          {
              if(Math.abs(column) <= row)
              {
                  System.out.print(row);
              } else
              {
                  System.out.print(" ");
              }
          }
          System.out.println();
      }

          }
          }

Sorry for the bad formating, I am new here and also new to programing.

A: Hope this helps:
for (i = 0; i < 10; i++) {
  for (int j = 1; j <= 10; j++) {
    if (j < 10-i) {
      System.out.print("  ");
    } else {
      System.out.print(j + " ");
    }
  }
  System.out.println();
}


text:
Q: Client-Server communication in REST, Spring (RestTemplate): getting 404 error I am trying to setup a Client-Server communication in REST, Spring.
In the client side I have the code:
Map<String, Double> variable = new HashMap<String, Double>(1);
variable.put(newTicket.getMovieName(),newTicket.getTicketPrice());
try{
     Boolean rresult = restTemplate.getForObject("http://localhost:8081/SpringMVCMerchant/movieTheater.htm", Boolean.class, variable);

In the server side I have the code (to receive the above 'variable', and get the below boolean as a return object):
@ResponseBody
@RequestMapping(value="/movieTheater/", method=RequestMethod.GET)
public boolean getCustomerInput(Map<String, Double> input) {
    return transactionService.addTransaction(input);
}

I am not sure if the above syntax is correct. When I am running the two servers, I am getting the following error at the client side(8080):
GET request for "http://localhost:8081/SpringMVCMerchant/movieTheater.htm" resulted in 404 (Not Found); invoking error handler

Please let me know what I am missing here, and what changes I need to make in my code.
Thanks in advance!

A: I guess you are using the wrong url to call the Web Service
http://localhost:8081/SpringMVCMerchant/movieTheater.htm

This ends with .htm whereas your RequestMapping does not contains this request pattern
Update:
Make sure there no console errors and also, if your server application is running on 8081.


text:
Q: Re-Call a String/Object from previous Sub Is it possible to recall a string or object that was stored in a previous sub?
The below code gives you an idea as to what I am trying to do.
Sub StoreUserData()
Dim StorName as Object
End

Sub WriteUserFile()
'Recall StorName here
End Sub

A: You need to make it into a field:
Dim StorName as Object

Sub StoreUserData()
  'Do stuff with  StoreName
End

Sub WriteUserFile()
'Recall StorName here
End Sub

If it is declared within a method, it is a local variable and not visible outside the method.
I suggest reading about Scope in Visual Basic.

A: Local variables are only accessible within their respective code block. To be able to access it you would have to widen its scope like this:
Class MyClass

    Dim storName as Object

    Sub StoreUserData()
        storName = something
    End Sub

    Sub WriteUserFile()
        ' Use storName here
    End Sub

End Class


text:
Q: Setting a bit in hexadecimal number Given a number (int a = 0XABCDE98) I am trying to set the D bit to 6.
ie after the Bit manipulation the number should be  (0XABC6E98).
I have written a small C program to do the bit manipulation, but somehow I am not able to see the correct bit change.
Please help me in finding what might be missing in the program.
#include<stdio.h>

int main()
{
    int n = 0xABCDE98;
    n |= (n & 0X0000) | 0x6000;
    printf("%x\n", n);
    return 0;
}

o/p - abcfe98

A: In your code
n |= (n & 0X0000) | 0x6000;

is wrong beacuse of is equal to
0xABCDE98 & 0x0000 = 0 and 0x0000 | 0x6000 = 0x6000 and 0xABCDE98 | 0x6000 = 0xABCFDE98
Instead you must write
n = (n & 0XFFF0FFF) | 0x6000;

A: Change:
n |= (n & 0X0000) | 0x6000;

to:
    n &= ~0xd000;
    n |=  0x6000;

or just:
    n = (n & ~0xd000) | 0x6000;

if you prefer.
Test:
#include <stdio.h>

int main()
{
    int n = 0xABCDE98;
    n &=   ~0x000d000;     // clear nybble
    n |=    0x0006000;     // set nybble to 6
    printf("%#x\n", n);
    return 0;
}

Compile and run:
$ gcc -Wall temp.c && ./a.out
0xabc6e98

LIVE CODE

A: Try This:
#include<stdio.h>

int main()
{
    int n = 0xABCDE98;
    n = n ^ 0x000B000;  //Ex-OR 'n' with  0x000B000
    printf("%x\n", n);
    return 0;
}

o/p - abc6e98

A: Lets have a look at what your program is doing:
(n & 0x0000)
Truth Table AND:
Anything & 0 = 0, so the result of this is simply 0x0000
Truth Table OR:
0 | Anything = Anything
so now (0x0000) | 0x6000 = 0x6000
Effectively the line:
n |= (n & 0X0000) | 0x6000;
simplifies to:
n |= 0x6000
The 4th last digit of n = D
Hex math: D | 6 = F
hence your result 0xABCFE98
Solution?
You need to try and 0 only the D digit first then OR with 0x6000 to set it to 6. There are many ways of doing this as suggested by other posters.
n = (n - 0xD000) | 0x6000 would also do the trick.

A: Try the following
#include <stdio.h>

int main( void )
{
    int x = 0XABCDE98;

    x = ( ~0xF000 & x ) | 0x6000;

    printf( "%#X\n", x );

    return 0;
}

The output is
0XABC6E98

A: n & 0x0000 "delete" the four last digits, so replace it with n & 0xFFF0FFF. That will keep all the digits except the fourth one (the 0).


text:
Q: Dispay html textbox with value from code behind using c# How can I display an html textbox with value obtained from code behinh?

A: As long as your string value is not private, you should be able to do something like this
<input type="text" value="<%= YourStringValue %>" />

A: You could use an actual <asp:Textbox /> and set it's "text" value directly from the code behind.  If you want to directly inject text into a "normal" html textbox (or anywhere else for that matter), you can use <%= SomeValue %>.  Yet another way is to include the "runat=server" attribute on standard html elements, allowing you to manipulate them from the codebehind.
Normally I'd just go for the built-in ASP textbox control so I don't have to worry about persisting values/wiring up viewstate/etc.  Injecting dynamic content into plain html elements tends to be an edge case requirement...

A: <%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        //assign text value here
        txt1.Value = "hello world!";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="txt1" runat="server" type="text" />
    </div>
    </form>
</body>
</html>


text:
Q: Divergent continued fractions? The solutions to
$$
x^2-6x+10=0 \tag 1
$$
are
$$
x = 3\pm i\tag2.
$$
Rearranging $(1)$ just a bit, we get
$$
x = 6 -\frac{10}x \tag3
$$
and then substituting the right side of $(3)$ for $x$ within the right side we get
$$
x=6 - \cfrac{10}{6-\cfrac{10}x}
$$
and iterating we have
$$
x=6 - \cfrac{10}{6-\cfrac{10}{6-\cfrac{10}{6-\cfrac{10}{6-\cdots}}}} \tag 4
$$
(or in lowest terms
$$
x=6 - \cfrac{5}{3-\cfrac{5}{6-\cfrac{5}{3-\cfrac{5}{6-\cdots}}}}
$$
with $3$ and $6$ alternating).
Just as one speaks of "summation methods" by which $1+2+3+4+\cdots=\dfrac{-1}{12}$, etc., might there be some "division method" by which $(4)$ is equal to $(2)$?
PS: Might one prove that this continued fraction diverges in the usual sense by proving that if it converges then it must converge to the solution of $(1)$ (and obviously it does not)?

A: Many regularization techniques are based on averaging. Let us define $a_0,b_0,m\in\Bbb C$ and
$$a_{n+1}=6-\frac{10}{a_n}$$
$$b_n=\frac{b_n+m\left(6-\frac{10}{b_n}\right)}{1+m}$$
If $a_n\to3\pm i$, then if $b_n$ converges, it also converges to $3\pm i$.
Choosing
$$m_\pm=-\frac{4\pm3i}5$$
gives us
$$b_{n,\pm}=\frac{(4\pm3i)\left(6-\frac{10}{b_n}\right)-5b_n}{-1\pm3i}$$
which should converge to one of the roots depending on the choice of sign.


text:
Q: oauth web api call returns 403 forbidden I implemented OAuth2 in my mvc web api project.I got the token but when I call the web api methods with this token the call will return 403 forbidden.I also called the same web api without the token it's working.Here is my token call:
public override  Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    AccountLogin LogCredentials = new AccountLogin();
    LogCredentials.UserName = context.UserName;
    LogCredentials.Password = context.Password;
    LogCredentials.IPAddress = "::1";

    string webHost = Convert.ToString(WebConfigurationManager.AppSettings["webHost"]);
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { webHost });

    ProviderLoginResponse providerLoginResponse = MembershipService.UserLogin(LogCredentials);
    if (providerLoginResponse.LoginStatus != "Y")
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return Task.FromResult<object>(null);
    }

    var claims = new List<Claim>()
        {
                new Claim(ClaimTypes.Sid, Convert.ToString(providerLoginResponse.UserID)),
                new Claim(ClaimTypes.Name, providerLoginResponse.UserName),
                new Claim(ClaimTypes.Email, providerLoginResponse.UserEmail)
        };

    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,
                Startup.OAuthOptions.AuthenticationType);

    AuthenticationProperties properties = CreateProperties(providerLoginResponse);

    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    context.Validated(ticket);
    return Task.FromResult<object>(null);
}

Here is my api method:
[HttpGet]
[Route("GetColumn")]
public HttpResponseMessage GetColumn(HttpRequestMessage request)
{
    string tableName = "";
    HttpResponseMessage response = null;
    try
    {
       var clientList = _settingsService.GetColumns(tableName);
       response = request.CreateResponse(HttpStatusCode.OK, new APIResponse { Status = true, Data = clientList, Message = Messages.Saved_Success });
    }
    catch (Exception ex)
    {
        response = request.CreateResponse(HttpStatusCode.OK, new APIResponse { Status = false, Data = null, Message = ex.Message });
    }
    return response;
}

My api call is :
function GetColumn(data, cb) {
    var token = sessionStorage.getItem('accessToken');

    var headers = {};
    if (token) {
        headers.Authorization = 'Bearer ' + token;
    }

    $.ajax({
        type: 'GET',
        url:  "api/Settings/GetColumn",
        headers: headers
    }).done(function (data) {
        cb(data);
    }).fail(function (Res) {
        cb(Res);
    });
};

I also tried the postman by passing the Authorization token but still got the 403.I searched the web for this problem but nothing will solve my problem .Why it is behaving like this?


text:
Q: Javascript prompt within a function not returning the value I expect var perimeterBox = function(length, width) {
    return (length * 2) + (width * 2);
};

var justAsk = prompt("what is the length, width?");

perimeterBox(justAsk);

When I run it the prompt pops up. However when I enter the length, width (ex:7,3) I get a value of null. Thought?

A: You need to extract the values from the string inputted by the user:
var perimeterBox = function(length, width) {
    return (length * 2) + (width * 2);
};

var justAsk = prompt("what is the length, width?"); // justAsk is "7,3"

var values = justAsk.match(/\d+/g); // values is ["7", "3"]
var width = parseInt(values[0]); // width is 7
var height = parseInt(values[1]); // height is 3

perimeterBox(width, height);


text:
Q: SDWebImage caching works only in Simulator I'm using SDWebImagePrefetcher to prefetch a list of images off my plist (about 100, max size 600kb) in order to save them (on disk possibily) for later use.
Point is that on simulator this is working fine, while on device, it's loading and caching only some of them and I honestly don't get why.
I know this because after prefetching them, i turn off WiFi connection and see if the images have been loaded correctly in the imageView (on detailView), and surprisingly there are only 1\5 of the images prefetched, even if the consoloe said it prefetched them all.
I tried to put in SDWebImagePrefetcher.m in method startPrefetchingAtIndex: this line of code
- (void)startPrefetchingAtIndex:(NSUInteger)index withManager:(SDWebImageManager *)imageManager
{
    if (index >= [self.prefetchURLs count]) return;
    _requestedCount++;

    [imageManager downloadWithURL:[self.prefetchURLs objectAtIndex:index] delegate:self options:self.options];
    [cache storeImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.prefetchURLs objectAtIndex:index]]]] forKey:[self.prefetchURLs objectAtIndex:index] toDisk:YES];

}

and then in my imageView class:
SDImageCache* cache = [SDImageCache sharedImageCache];
    UIImage* cachedImage = [cache imageFromKey:aString fromDisk:YES];

    if (cachedImage) {
        [imageView setImage:cachedImage];
    }
    else{
    [imageView setImageWithURL:[NSURL URLWithString:anUrl]
              placeholderImage:nil options:SDWebImageProgressiveDownload
                       success:^(UIImage *image) { [activityIndicator stopAnimating];[activityIndicator removeFromSuperview]; }
                       failure:^(NSError *error) {  [activityIndicator stopAnimating];[activityIndicator removeFromSuperview]; }];

    [imageView addSubview:activityIndicator];
    }

With no concrete results. Always working on simulator, not on device. Am I missing something here?
Should I put some caching method in SDWebImagePrefetcher to store them on disk or what?
I've being trying to make it work but failing every time.

A: Seems like i found the issue.
I shouldn't set the option to cache ( [prefetcher setOptions:SDWebImageMemoryCacheOnly]; ) ,but I had to leave it in low priority, so now everything works perfectly!


text:
Q: List creation on installation NOT activation for a feature? I have a Sharepoint feature that includes a settings list template, which is read by other features. The list must have a particular name for the whole thing to work, so ideally I would rather have a list created instead of a list template.
However I need the list to be permanent as the list can be updated manually to add more settings. Am I wrong in my understand that if I used this http://msdn.microsoft.com/en-us/library/ms476062.aspx every time it's activated the list is a new one that can't be saved? If so how do I go about just creating the list on installation instead?

A: No if you use List Definition with List Instance element, you can set the list instance property Deployment Conflict Resolution=None and your list instance will not be deployed (or not replaced with a new one).
The list instance will only be created if it doesn't already exists. If it exists nothing will happen, nor the items will be touched.


text:
Q: Prestashop: is there a way to limit invoice address to only one? I need to limit the invoice address registration to 1. So, no more than 1 invoice address, but multiple options shipping addresses.
Is it possible? How to? I'm thinking about building custom controllers for this task, but maybe there are faster ways to do it.

A: Without any custom change in the code, it doesn't seem to be possible to differentiate addresses in the address table (because there is no column to indicates that it is an invoice address or delivery address).
If you need to achieve this, we recommend you to add a new column in the table DB_PREFIX_address table to identify the type of the address. You will also have to make changes in checkout and registration page to the save type of the address.


text:
Q: Passing a file to a class First time writing a class here and I need a little help.
I've been trying to write a class in which the first takes a tab-delimited csv file and outputs a list of dictionaries. Each of the keys in the dictionary is a column title in the csv.
So far, this is what my class looks like:
import csv

class consolidate(object):

    def __init__(self, file):
        self.file = file

    def create_master_list(self):
        with(open(self,'rU')) as f:
            f_d = csv.DictReader(f, delimiter = '\t')
            m_l = []
            for d in f_d:
                m_l.append(d)
        return m_l

When I try to pass it a file, as follows:
c = consolidate()
a = c.create_master_list('Abilities.txt')

I get the following error:
TypeError: __init__() takes exactly 2 arguments (1 given)

I know that what I want to pass a file argument to the create_master_list function, but I'm unsure what the right syntax to do this is.
I've tried self.file and file as arguments, and both do not work as well.
Thanks!

A: Problem
You did not supply second argument for __init__():
class consolidate(object):
    def __init__(self, file):
        self.file = file
    # rest of the code

while you are instantiating it like this:
c = consolidate()

Solution
This should work. Change class definition to this:
import csv

class consolidate(object):

    def __init__(self, filename):
        self.filename = filename

    def create_master_list(self):
        with open(self.filename, 'rU') as f:
            f_d = csv.DictReader(f, delimiter='\t')
            m_l = []
            for d in f_d:
                m_l.append(d)
        return m_l

and then use it like this:
c = consolidate('Abilities.txt')
a = c.create_master_list()

This is one way of achieving the fix.
Note: I also changed the naming (self.file suggested it is file object, while it actually is a file name, thus self.filename). Also keep in mind that the path is relative to from where you execute the script.

A: You should pass the file as a parameter to __init__.
c = consolidate ('abilities.txt')

Then inside create_master_list you should open self.file.
with (open (self.file, 'rU') ) as f:

Now you can call
a = c.create_master_list ()

A: That's because your __init__ method of consolidate needs an argument for file:
def __init__(self, file):

but you don't give it anything:
c = consolidate()

To fix this problem, change your class like so:
import csv

# I capitalized the name of this class because that is convention
class Consolidate(object):

    def __init__(self, file):
        self.file = file

    def create_master_list(self):
        # 'self' is the instance of 'Consolidate'
        # you want to open 'self.file' instead, which is the file
        with(open(self.file,'rU')) as f:
            f_d = csv.DictReader(f, delimiter = '\t')
            m_l = []
            for d in f_d:
                m_l.append(d)
        return m_l

and then use it like this:
c = Consolidate('Abilities.txt')
a = c.create_master_list()


text:
Q: Model, controller or view to the other class library How can I separate Model and Controller to the other class library because in large project the number of views/model/controller might increase to "N" number which becomes difficult for me to traverse the correct code.

A: Does this one help you? (It's referenced on this question)


text:
Q: Should I distribute my skill point immediately or wait? When you gain a level, you gain a point you can spend on a skill, either a new one or ranking up an existing one. However most of the skills and skill ranks have level requirements that immediately outpace your skill point gains (e.g. the ranks may require levels 3, 8, 14, 20).
Since there are more levels than possible skill purchases, it seems like it is optimal to wait until I reach e.g. level 20 and buy all four ranks at once, rather than spending the points immediately on skills I don't really care about.
Is this the case? Or did the designers actually maybe play Diablo II and realize how stupid it is?

A: Yes, it's best to wait. The skill tree is broken in this regard.
However the difficulty curve of the game is so flat it doesn't matter anyway.


text:
Q: Django script that runs when the server starts Hi is it possible to create a script that runs when the server starts? I want a script that creates a few objects of a model so that a user has at least a few options to choose from before deciding to create a new one.
I would like the script to just create a few MemberRole objects so that when creating a member the role field has a few by default.
Would running a script be the ideal way to do this?
class Member(models.Model):
    first_name = models.CharField(max_length = 20)
    role = models.ForeignKey(MemberRole)

class MemberRole(models.Model):
    name = models.CharField(max_length = 20 )

A: You should take a look at this documentation page: Providing initial data for models.
You can create a JSON, XML or YAML fixture to load your data with manage.py loaddata admin command.
By the way automatic loading of data fixtures on database creation will be deprecated in favor of data migrations.


text:
Q: How do I remove elements from multiple Lists that are properties of a generic object using reflection? I have a generic object that could have mulitple Lists as properties.
How do I remove elements from those lists generically using reflection?
Let's say I have objects that are like below
public class ObjectA
{
    public List<long> listA
    public List<string> listB
}

public class ObjectB
{
    public List<int> listC
    public List<decimal> listD
}

How would I go about adding and removing elements from those lists generically?
Here's what I thought of, but it's wrong:
private bool PropertyIsGenericList(PropertyInfo property)
        {
            return property.PropertyType.IsGenericType && typeof(IList).IsAssignableFrom(property.PropertyType);
        }

private void RemoveElementsFromPropertyThatAreLists(object dto)
        {
            foreach (PropertyInfo property in dto.GetType().GetProperties())
            {
                if (dto != null && property != null && PropertyIsGenericList(property))
                {
                    RemoveElementsFromList(property, globalIndex); // Don't know what to pass to this
                }

            }
        }

protected void RemoveElementsFromList<ListType>(List<ListType>? columns, int? startingIndex = null)
        {
            startingIndex = startingIndex != null ? startingIndex.Value : globalIndex;
            if (columns != null)
            {
                for (int columnIndex = columns.Count - 1; startingIndex <= columnIndex; columnIndex--)
                {
                    columns.RemoveAt(columnIndex);
                }
            }
        }

A: Lists of any type supports interface IList, you can do your manupulations via that interface:
private void RemoveElementsFromPropertyThatAreLists(object dto)
{
    foreach (PropertyInfo property in dto.GetType().GetProperties())
    {
        if (dto != null && PropertyIsGenericList(property))
        {
            var list = (IList)property.GetValue(dto);
            RemoveElementsFromList(property, globalIndex);
        }

    }
}

protected void RemoveElementsFromList(IList columns, int? startingIndex = null)
{
    startingIndex = startingIndex != null ? startingIndex.Value : globalIndex;
    if (columns != null)
    {
        for (int columnIndex = columns.Count - 1; startingIndex <= columnIndex; columnIndex--)
        {
            columns.RemoveAt(columnIndex);
        }
    }
}


text:
Q: Drawing from 2 bags of different size and counting the number of outcomes I have a combination problem that I can't get my head around.  Similar problems were found here and here but are not quite the same of my problem.
I have two sets of units and I want to find the number of possible matches between the two.  So for every unit in set1, I pick a matched unit is set2 until there is no more units to pick in set1. This become one possible draw.  I want to find the number of possible draws that exist within two sets of size $m$ and $n$.
The two sets are of different length, however the first set is always smaller or equal to the second one.  Here are the problem description:

*

*set1: size $m$

*set2: size $n$

*$m <= n$

*The order do not matter

*The draws are done without replacement

*You keep drawing until set1 is empty, some items in set2 may not have been picked in one event.

I'll try to make it clearer with an example. Let's say my set1 is of length 2 and contains unit id: $\{A,B\}$.  On the other side, my set2 is of size 3 and contains units $\{1,2,3\}$.  There are 6 different outcomes possible $[\{A1,B2\},\{A1,B3\},\{A2,B1\},\{A2,B3\},\{A3,B1\},\{A3,B2\}]$.  I need a general solution to calculate the number of outcome possible for any sets of size $\{m,n\}$.
Like stated before, $\{A1,B2\}$ is equivalent to $\{B2,A1\}$ so it doesn't count as a different output.
I manually counted the number of outcomes for a bunch of examples with the hope of finding the pattern but I didn't succeed.  Here are the results of my manual calculations (hopefully I didn't miss any).
----------------------------
|  m   |   n   | outcomes  |
----------------------------
|  2   |   3   |     6     |
|  3   |   3   |     6     |
|  2   |   4   |     12    |
|  3   |   4   |     24    |
|  4   |   4   |     24    |
|  2   |   5   |     20    |
----------------------------

In this question, the problem is similar but they were asking for a Python script to list all possible outcomes.  In my case, I don't really need to list all the outcomes, I just need to know how many there are.  That why I'm mostly asking of the proper equation to represent my problem.  However, if such equation does not exist, having a similar script in R would be acceptable.
*** Edits:  To try to clarify.  My actual problem is that I have a multiple small tables where each lines represent an individual (so $m$ individuals in my set1).  All those small tables are inside their "group" (my set2) which is a spatial localisation of population $n$.  I want to identify the likelihood of matching perfectly each individual in a table to its associated person in the group. To do that, I just need to identify all the possible matches between the rows in my table and the people in the group.


text:
Q: C#. Dapper - вставка нескольких элементов и возврат их Id решил потренироваться на тестовой БД вставку нескольких значений в таблицу через Dapper
Postgress 14.0
create table actor
(
    actor_id    integer generated always as identity
        constraint actor_pkey
            primary key,
    first_name  varchar(45)             not null,
    last_name   varchar(45)             not null,
    last_update timestamp default now() not null
);

using IDbConnection db = new NpgsqlConnection(connectionString);
db.Open();

const string query = @"INSERT INTO actor(first_name, last_name) VALUES (@first_name, @last_name) RETURNING actor_id;";
var actorList = new List<ActorDal>
{
    new ActorDal {first_name = "Bob", last_name = "Torton"},
    new ActorDal {first_name = "Nikita", last_name = "Mickhalkov"}
};

var insertedIds = await db.QueryAsync<int>(query, actorList);

Выскакивает исключение
An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context

Если использовать
await db.ExecuteAsync(query, actorList);

то все нормально.
Но мне нужно получать Id вставленных элементов.
Если вставляю 1 элемент через
QueryAsync<int>(query, oneItem)

то тоже работает и возвращается Id вставленного элемента.


text:
Q: Woocommerce: menu products (wp-admin) visible for all users I would like to enable access to the administration menu of products not only to superadmin but to other users: author, editor, customer and shop managers so that they too can enter the products in the database woocommerce.
At the moment the administration screen / wp-admin menu appears woocomerce products. How can I then enable it for all users?

A: I recommend taking a look at User Role Editor to accomplish this. You can add/edit/remove capabilities to each role.


text:
Q: BASH: How to use Regex Negative Lookahead in sed command for a string? I have not found a way to use this regex expression - .+?(?=,) in the sed command to extract part of this string (using Lookbehind of the first instance of character).
In plain english I want to extract the part of the string that lies before the first comma. As I'm planning to extract in the future the specific filename of the string, I cannot rely on the cut command (I will have to eventually use sed command) , :-
name='ERROR 1: /home/rphillips/Desktop/empties/BN23_2303.tif, band 1: Failed to compute statistics, no valid pixels found in sampling.'
These are the variations that I've used including a test - sed 's/band/rose/' which worked. However the other variations (shown below) that I've used gave spaces as outputs.
while read -r line; do
    name="$line"
    echo $name
    #file_path=$(echo $name | cut -d "," -f 1)
    #file_path=$(echo $name | sed -e '/s\/.+?(?=,)///')
    #file_path=$(echo $name | sed 's/band/rose/')
    file_path=$(echo $name | sed '/s\/.+?(?=, )///')
    #file_path=$(echo $name | grep -P '.+?(?=,)')
    #file_path=$(echo $name | sed
    #file_path=$(echo $name | awk '/.+?(?=,)/{print $name}'
    echo $file_path
done < "$filename"

Expected Result - ERROR 1: /home/rphillips/Desktop/empties/BN25_2303.tif
Actual Results - 'lots of spaces'
I've also noticed that the regex expression that I've used have different 'matches' according to the Regex101 Website depending whether I'm using Firefox on Windows or Ubuntu 16.04LTS
Windows - https://regex101.com/r/WWGf8F/1
Ubuntu - https://regex101.com/r/NpL2Oa/1
I'm not sure if this is causing the expression not to be recognized by sed -e?
I have used these references to for the different expressions used in the code above
https://likegeeks.com/regex-tutorial-linux/
How to match "anything up until this sequence of characters" in a regular expression?
https://www.regular-expressions.info/lookaround.html?wlr=1
https://linux.die.net/man/1/sed

A:
In plain English I want to extract the part of the string that lies
  before the first comma. As I'm planning to extract in the future the
  specific filename of the string, I cannot rely on the cut command (I
  will have to eventually use sed command)

Input String
ERROR 1: /home/rphillips/Desktop/empties/BN23_2303.tif, band 1: Failed to compute statistics, no valid pixels found in sampling.

Expected Results
ERROR 1: /home/rphillips/Desktop/empties/BN25_2303.tif

Before we get to possible reasons why your sed command isn't working, let's look at your actual problem above. If you simply want to extract the text before the first comma, then all you need is:
sed 's/,.*//'

(which simply says delete everything from the first comma to end)
You can use a backreference as well (which will come in handy to reach your ultimate goal of extracting the filename), e.g.
sed 's/^\([^,][^,]*\).*$/\1/'

(which says '^' start at the beginning, \([^,][^,]*\) capture all text of at least 1 character that is not a comma, and including zero or more additional characters that are not commas, .*$ discarding all text to the end and \1 replacing with only the captured text using a back-reference)
To reach your goal of extracting only the filename, you need only modify the above to begin the capture with the first forward slash, e.g.
sed 's/^[^/]*\([^,][^,]*\).*$/\1/'

Example Use/Output
$ sed 's/^[^/]*\([^,][^,]*\).*$/\1/' <<< $name
/home/rphillips/Desktop/empties/BN23_2303.tif

I'm not sure if this is causing the expression not to be recognized by
  sed -e?

sed without the -E (--regexp-extended) option uses Basic regular expressions (which does not include look-behind or ahead).
If you plan on using the remaining fields of the comma-separated-values, you may want to consider awk to parse the fields. You can easily obtain all fields specifying the -F field separator and a simple loop.
$ awk -F', ' '{for (i = 1; i <= NF; i++) printf "field %d - %s\n", i, $i}' <<< $name
field 1 - ERROR 1: /home/rphillips/Desktop/empties/BN23_2303.tif
field 2 - band 1: Failed to compute statistics
field 3 - no valid pixels found in sampling.

(you can handle further parsing of each field with a conditional within the loop as well)
In Bash - Parameter Expansions Are All You Need
Not to lose sight of the forest for the trees, since you specified bash, if you simply want to extract the filename from name, all you need is parameter expansion with substring removal (first from the right, and then left), e.g.
tmp=${name%%,*}    ## trim to (and including) the 1st comma from the right
echo "/${tmp#*/}"  ## trim to and including the first / from the left
/home/rphillips/Desktop/empties/BN23_2303.tif

(a much more efficient way to go)
Look things over and let me know if you have further questions.


text:
Q: What solver should I use if my objective function is an nonlinear (also exponential explanation) function? Python GEKKO I'm trying to optimise an exponential objective function with GEKKO, but I don't know if the selected solver is the best one for these kind of problems.
Is the selected one a valid choice??
import numpy as np

'GEKKO MODELING'
from gekko import GEKKO
m = GEKKO()
m.options.SOLVER=1  # APOPT is an MINLP solver

# Initialize variables
x = []
x1 = m.Var(value=20,lb=20, ub=6555)  #integer=True
x2 = m.Var(value=0,lb=0,ub=10000)  #integer=True
x3 = m.sos1([30, 42, 45, 55])

x = [x1, x2, x3]
# Equations
m.Equation((x1 * x2* x3) * 10 ** (-6)>=50)

def fun(x):
    return 44440 + ((np.pi * x[0] * x[1] * x[2]) * 10 ** (-4))**0.613

x = [400,300,19]

'GEKKO Optimization'
m.Obj(fun(x))

m.solve(disp=False) # Solve
print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))

print('Objective: ' + str(m.options.objfcnval))

A: A problem with your script is that you are redefining the value of x = [400,300,19] before you call your objective function. The objective function should be called with your original definition x = [x1, x2, x3] so that it can optimize these variables. One other change is that the value of x3 is by default equal to zero. Setting it away from zero x3.value=1.0 allows APOPT and IPOPT solvers to converge because you previously started right on the border of an imaginary number objective with x3<0.
import numpy as np
from gekko import GEKKO
m = GEKKO()
x = []
x1 = m.Var(value=20,lb=20, ub=6555)  #integer=True
x2 = m.Var(value=1,lb=1,ub=10000)  #integer=True
x3 = m.sos1([30, 42, 45, 55])
x3.value = 1.0
x = [x1, x2, x3]
m.Equation((x1 * x2* x3) * 1e-6 >= 50)
def fun(x):
    return 44440 + ((np.pi * x[0] * x[1] * x[2]) * 1e-4)**0.613
m.Obj(fun(x))

# Change to True to initialize with IPOPT
init = False
if init:
    m.options.SOLVER=3
    m.solve(disp=False) # Solve

m.options.SOLVER=1
m.solve(disp=True) # Solve

print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('Objective: ' + str(m.options.objfcnval))

For the solver suggestion, here is a list of publicly available solvers in Gekko. There are additional commercially available solver options in Gekko but I'll stick with just the publicly accessible ones (APOPT, BPOPT, and IPOPT) for this response. Any nonlinear programming solver should be able to handle a nonlinear objective such as x**0.613. Your problem also includes a Special Ordered Set, Type 1 (m.sos1) and so your problem is not just a Nonlinear Programming (NLP) problem but also includes binary variables for the sos1. This means that you'll need to use a Mixed Integer Nonlinear Programming (MINLP) solver. The APOPT solver is the only MINLP solver publicly available in Gekko and it is automatically selected for you when you create an sos1 object. If you would like to try to solve the MINLP problem with an NLP solver (such as IPOPT), then you'll need to specify the solver after you create the m.sos1 object.
m.options.SOLVER = 3

This could lead to an incorrect solution because x3 can only be one of the following: 30, 42, 45, 55. IPOPT finds a minimum solution of x3==47.079550873 so in this case, it did not return an integer solution. If you want to guarantee an integer solution, you'll need to use APOPT.
 Successful solution

 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :   4.279999999562278E-002 sec
 Objective      :    44813.4405591393
 Successful solution
 ---------------------------------------------------

Results
x1: [677.59896405]
x2: [2459.665311]
x3: [30.0]
Objective: 44813.440559

If you need to change some of the tuning parameters of the MINLP APOPT solver then you can use something like the following:
m.solver_options = ['minlp_gap_tol 1.0e-2',\
                    'minlp_maximum_iterations 10000',\
                    'minlp_max_iter_with_int_sol 500']

There is additional information on the APOPT solver options.


text:
Q: Cannot use static method in BaseEntity class as serializer complains All of my Entities and Documents extend a BaseObject class (it handles getId(), getClassName() and a couple of handy shortcuts).
I added a static array of traits to it - so I can iterate through these traits when adding forms and validation rules on the fly.
/**
 * Class BaseObject
 */
abstract class BaseObject
{
    protected $id;

    public static $traits = ['blame', 'time', 'live', 'when', 'where', 'ugc', 'security'];
...

However, when I try and log in I get the following error -
*Notice: serialize(): "traits" returned as member variable from __sleep() but does not exist in ... symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php line 149*
Should I store this list of traits elsewhere, or is there something else I should be doing here?  Some posts pointed to using the Serializable interface, but I'm not sure what the best way to use that is.
Thanks,
James


text:
Q: I can't connect TableViewCell button to TableViewController! How do I connect values from TableViewCell to TableViewController? From what I understand, I can not connect the button in my cell to my TableViewController using an outlet connection. I can however connect the button in my cell to my TableView using an action connection. This is the root of my huge problems.
In my cell I have a textview, an imageView with overlaid button, and a send button. THIS IS THE CELL

I assign an image to the imageView using imagePicker. imagePicker must be opened from the tableViewController (it can not be opened in the cell).
var MyImage = UIImage?()
var MyName = String()
var MyStatus = String()

// This is ImgButton that overlays the imageView
@IBAction func MyImageButtonAction(sender: AnyObject) {

// Select Image
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    imagePicker.allowsEditing = false
    self.presentViewController(imagePicker, animated: true, completion: nil)

}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
// The image chosen by the user is now called MyImage
     MyImage = image
     self.dismissViewControllerAnimated(true, completion: nil)

}

Now when the send button is tapped, I make MyImage a PFFile for Parse.com and send it to the database. I don't need to give full details here. This part works fine.
The problem is that I don't know how to properly connect the cell to the tableViewController in a way that I can transfer values from one to the other. I want to get the textView.text from the cell, to the tableViewController so that from there I can send it to database with the image. The other problem is that, although the user can select an image and send it to database, they can't get the selected image into their imageView.
This is my attempt to connect the cell to the tableViewController:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("MyStatusTableViewCell", forIndexPath: indexPath) as! MyStatusTableViewCell

    cell.MyName.text = MyName

    return cell
}

I was hoping that his code meant that MyName is now the variable that contains the .text that the user input in the textView.text in the cell. I tried sending MyName to the database but it came up empty.
How do I get the textView.text from the tableViewCell into my database?

A: u can set tag of each element of UITableViewCell and then u can access it in cellForRowAtIndexPath like
if let textfield = cell.viewWithTag(21) as? UITextField {
    textfield.text = MyName
}

A: You can create IBAction instead of IBOutlet and in button action you can convert sender to position and find index path like this
 @IBAction func buttonClick(sender: AnyObject) {
    let btnPos: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(btnPos)!

    print("indexPath->\(indexPath.row)")
}

A: I found the problem which is inside your UITableView cellForRowAtIndexPath method. You have to load your custom cells like that below:-
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("MyStatusTableViewCell", forIndexPath: indexPath) as! MyStatusTableViewCell
if cell == nil{

//Here you have to load your custom cells like that below
let array = NSBundle.mainBundle().loadNibNamed("MyStatusTableViewCell", owner: nil, options: nil)
cell = array[0] as?  MyStatusTableViewCell
}
cell.MyName.text = "MyName" //Now it will set your textview value
return cell
}


text:
Q: Reload record detail lightning page on edit Is there a way to reload the Lightning page after saving the record detail? I have embedded a custom Lightning component on the Lightning page and trying to reload the page to use the updated field values on the record.

A: Use below code, if success is returned below code line should be fired.
$A.get("e.force:refreshView").fire();
A sample method can be written as
refresh : function(component, event, helper) {
var action = component.get('c.myController');
action.setCallback(component,
    function(response) {
        var state = response.getState();
        if (state === 'SUCCESS'){
            $A.get('e.force:refreshView').fire();
        } else {
             //do something
        }
    }
);
$A.enqueueAction(action);

}
https://developer.salesforce.com/docs/component-library/bundle/force:refreshView/documentation
Are you in the context of a custom lightning app? The default refreshView event is only available within the Lightning Experience / mobile Salesforce-App context. Say if you want to use the event within a .app you have to register and handle the event manually and cannot use the out-of-the-box behaviour.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_one.htm

A: force:refreshView is used to refresh the view when you need to get new data. Something like this:
$A.get("e.force:refreshView").fire();


text:
Q: fish protocol on Macintosh? I'm a fan of the fish protocol using konqueror (fish://user@host) on Linux.  Can I set up the same thing on the Mac?  Ideally, having it integrated with the Finder would be great.

A: OSX includes sftp.
OSX's Terminal  can open SFTP connections, open Terminal and hit cmd-shift-K.
Lets you save ssh, sftp, telnet and ftp sessions.
Not finder integrated.
For a more finder integrated way of using a file system over ssh have a look at http://code.google.com/p/macfuse/ and http://code.google.com/p/macfuse/wiki/MACFUSE_FS_SSHFS.

A: The fish thing seems to be using SFTP, so Macfusion might work (configure it for SSH). But not having a Mac, I can't test.

A: You might also like ExpanDrive (www.expandrive.com/mac), which allows you to mount SFTP connections like other network shares or removable drives. It's commercial software that uses MacFUSE, but has quite a lot of useful improvements over the basic MacFUSE SFTP functionality.

A: The finder allows you to make (S)FTP sessions.
'Connect to server' allows a range of protocols:
smb://
ftp://
afp://
etc...
I just can't remember which menu it is off the top of my head.


text:
Q: Error produced when trying to solve ordinary differential equation NDSolve[{x0'[t] == -x0[t]*s*x1^2 + s*x1^2, x1'[t] == x1*s*x1^2,
  x2'[t] == -x2[t]*s*x1^2, x0[0] == x1[0] == x2[0] == 1}, {x0, x1,
  x2}, {t, 0, 1}]

A: All dependent variables must depend explicitly on t, and all symbols must be defined.  For instance,
sol = NDSolve[{x0'[t] == -x0[t]*s*x1[t]^2 + s*x1[t]^2,
    x1'[t] == x1[t]*s*x1[t]^2, x2'[t] == -x2[t]*s*x1[t]^2,
    x0[0] == x1[0] == x2[0] == 1} /. s -> 1/2, {x0, x1, x2}, {t, 0, 1}]
Plot[Evaluate[{x0[t], x1[t], x2[t]} /. sol], {t, 0, 1}, AxesLabel -> {t, "x0,x1,x2"}]

Alternatively, and certainly more informatively, the equations can be solved with DSolve
First@DSolve[{x0'[t] == -x0[t]*s*x1[t]^2 + s*x1[t]^2,
    x1'[t] == x1[t]*s*x1[t]^2, x2'[t] == -x2[t]*s*x1[t]^2,
    x0[0] == x1[0] == x2[0] == 1} , {x0[t], x1[t], x2[t]}, {t, 0, 1}]
(* {x1[t] -> 1/Sqrt[1 - 2 s t], x0[t] -> 1, x2[t] -> Sqrt[1 - 2 s t]} *)


text:
Q: how to keep a column from a specific data set using data step in sas I've 2 tables who has a same column of same attribute. I want to select that column and other columns from both tables. example
table_1

ID | column_1 | column_2
 1 |  col_1   |  col_2
 2 |  col_1   |  col_2
 3 |  col_1   |  col_2

table_2
ID | column_3 | column_4
 4 |  col_3   |  col_4
 5 |  col_3   |  col_4
 6 |  col_3   |  col_4

I want to create a table as
Required

ID | column_1 | column_4
 1 |  col_1   |  col_4
 2 |  col_1   |  col_4
 3 |  col_1   |  col_4

I want to do it using data step
data required;
set table_1 table_2;
keep ID column_1 column_4;
run;

but it's giving me 6 rows.
I can get my table using proc sql
proc sql noprint;
create table required as
select t1.Id, t1.column_1, t2.column_4
from table_1 as t1, table_2 as t2;
quit;

I'm looking to do same with data step

A: If you use a SET then the datasets are read sequentially.  If you want to combine the datasets record by record then use a MERGE instead.  Normally you would use a BY statement to combine the records based on some key variables.  But if you leave off the BY statement then SAS will combine the records in order.
Also watch out for variable name conflicts.  Both of your inputs have an ID variable. It looks like you only want to keep the one from the first dataset.  You can use the KEEP= dataset option to tell SAS which variables to include from a dataset.
data required;
   merge table_1 (keep=id column_1) table_2 (keep=column_4);
run;


text:
Q: Offline video freezes every few minutes I have a custom computer running (legal, updated) Windows 7, 8GB Ram, 1-yo Graphics Card. My system runs on a new SSD and my media is stored on a <1-yo HDD.
Recently when I am watching (non-HD, offline) videos on VLC player, the video would freeze randomly (once every few minutes). The freeze would last 10-20 seconds, and then it would play for a fraction of a second, freeze again, for a few times until it becomes normal again.
During the freeze, other programmes are functioning normally. And the computer does not feel like it is lagging.
I restarted yesterday and it did not happen during playback then. I put the computer to sleep during the day today and the issue surfaced again tonight.
I am worried this might be a harddrive issue even though my media drive is less than a year old.
Has anyone encountered similar issues or have an idea what the cause of this was?


text:
Q: Android soft keyboard disappear when tap webView input field I am working on the android WebView.When i tap the input field the soft keyboard open for a few seconds and disappear then automatically.

A: in xml try this line might work
android:imeOptions="flagNoExtractUi"


text:
Q: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError I have used xuggle library in my project to trans code the video from mp4 to flv.
I have used slf4j libraries also to support logging end.
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaViewer;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.ToolFactory;

public class TranscodingExample {

    private static final String inputFilename = "E:\\VIDEO\\Facebook.mp4";
    private static final String outputFilename = "E:\\VIDEO\\Facebook.flv";

    public static void main(String[] args) {

        // create a media reader
        IMediaReader mediaReader =
               ToolFactory.makeReader(inputFilename);

        // create a media writer
        IMediaWriter mediaWriter =
               ToolFactory.makeWriter(outputFilename, mediaReader);

        // add a writer to the reader, to create the output file
        mediaReader.addListener(mediaWriter);

        // create a media viewer with stats enabled
        IMediaViewer mediaViewer = ToolFactory.makeViewer(true);

        // add a viewer to the reader, to see the decoded media
        mediaReader.addListener(mediaViewer);

        // read and decode packets from the source file and
        // and dispatch decoded audio and video to the writer
        while (mediaReader.readPacket() == null) ;

    }

}

Here I am getting an error
"Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.".

I have used both jar files as libraries in order to solve logging problems.
How can this problem be solved?

A: So you have to exclude conflict dependencies. Try this:
<exclusions>
  <exclusion>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </exclusion>
  <exclusion>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
  </exclusion>
</exclusions>

This solved same problem with slf4j and Dozer.

A: Encountered a similar error, this how I resolved it:

*

*Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below.

*Right click an import jar file and select Exclude Dependency

*To confirm, open your pom.xml file you will notice the exclusion element as below.

4. Initiate maven clean install and run your project. Good luck!

A: And for SBT : excludeDependencies += "log4j" % "log4j"

A: I got the solution
download Xuggler 5.4 here
and some more jar to make it work...
commons-cli-1.1.jar
commons-lang-2.1.jar
logback-classic-1.0.0.jar
logback-core-1.0.0.jar
slf4j-api-1.6.4.jar

You can check which dependencies xuggler needs from here:
Add this jars and xuggle-xuggler-5.4.jar to your project's build path and it s ready.
**version numbers may change

A: For gradle
compile('org.xxx:xxx:1.0-SNAPSHOT'){
    exclude module: 'log4j'
    exclude module: 'slf4j-log4j12'
}

A: SBT solution stated above did not work for me. What worked for me is excluding slf4j-log4j12

//dependencies with exclusions
libraryDependencies ++= Seq(
    //depencies
).map(_.exclude("org.slf4j","slf4j-log4j12"))

A: You need to exclude log4j-over-slf4j
<dependency>
    ....
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>


text: Q: I have two projects .one project contains emp table entity .I need same table entity to access in another project using spring boot I have two projects .one project contains emp table entity .I need same table entity  to access in another project using spring boot .How to do that.Thanks in advance.


text:
Q: Detect Child UIViewController being popped I'm sure this will be a simple answer, maybe a method I'm missing to implement. Here goes:
In my Controller1 I use a pushViewController to push a new view Controller2 onto my view stack. I'm getting a back button.
Now, when Back button is pressed in my Controller1 I want to be able to detect that Controller2 is being popped and we're back in Controller1. Makes sense?
I was trying to do that with ViewDidAppear, but I'm not sure how to detect a popped controller. There are other answers here but they all show examples in Controller2 on viewWillDisappear
How would I do that in Swift?

A: Without knowing more you should pass a reference of the first controller to the second controller so that the second controller can tell the first when it is done (this is a simple delegate relationship, it could also be implemented using a block / closure).
Ideally the first controller should be responsible for dismissing the second controller, either when it gets this callback or, more appropriately, directly when the 'dismiss' button is tapped.


text:
Q: How to type an "@" character in a Jupyter Notebook on a Mac I just tried to enter an "@" character in a Jupyter Notebook on a Mac by ALT+g which is the standard MAC way to type the at-sign. However, instead of inserting an "@" The "Jump to line:" input dialog was triggered in the active cell. How can an "@" be typed inside a Jupyter Notebook cell? One example where this is needed is function decorators.
Unbinding the key as by the by the documentation seems to fail in my setting. https://jupyter-notebook.readthedocs.io/en/stable/extending/keymaps.html
{
  ...,
  "keys": {
    "edit": {
      "unbind": [
        "alt-g"
      ]
    }
  }
}

The Settings > Advanced Settings Editor > Keyboard Shortcuts notes that
    // Note: To disable a system default shortcut,
    // copy it to User Preferences and add the
    // "disabled" key, for example:
    // {
    //     "command": "application:activate-next-tab",
    //     "keys": [
    //         "Ctrl Shift ]"
    //     ],
    //     "selector": "body",
    //     "disabled": true
    // }

but using
{
    "shortcuts": [
        {
            "command": "editmenu:go-to-line",
            "keys": [
                "Alt G"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode",
            "disabled": true
        }
    ]
}

does not actually unset the Alt G key binding.
I know copy-pasting the @ character works, but that is not a solution.

A: This depends on your keyboard - I am assuming you don't have an @ symbol on it!
You could unbind the CMD + g shortcut: https://jupyter-notebook.readthedocs.io/en/stable/extending/keymaps.html


text:
Q: How to create session for login in core php? i used this query to login and for creating session.
$username = $_REQUEST['user'];
$password = $_REQUEST['pass'];
$member = mysqli_query($conn,"SELECT * FROM `user` WHERE `email` = '".$username."' AND `password` = '".$password."' ");
$member1 = mysqli_fetch_assoc($member);
if ($member1>0)
    {
        $_SESSION['username']=$member1['fullName'];
        $_SESSION['companyid']=$member1['comapanyId'];
        header('Location: home.php');
    }
else
    {
        header('Location: index.php');

    }

i am able to create session means if i echo
  $_session['companyid'];die; on this page it will print that id
  perfectly.
Now, i will jump to home.php to use this session for that i write
  session_start() on top of the page.
Now, If i print_r($_SESSION['companyid']) i will get error Notice:
  Undefined index: companyid
for this problem i used isset function like this,

if (isset($_SESSION['companyid'])) {
      echo $_SESSION['companyid'];
    }

but i am again failed to print $_SESSION in home.php I dont know what
  i am doing wrong.

A:
i am able to create session means if i echo
  $_session['companyid'];die; on this page it will print that id
  perfectly.

The array $_session is different than the superglobal array $_SESSION due to case sensitivity. On top of that, you will need session_start() at the top of each PHP page that will be accessing this array.
If you change $_session to $_SESSION, PHP will know that you are calling the same array.


text:
Q: Produce the escaped character of a character I wonder if there is a legit and simple way to write a function, which:

*

*takes a character as input (e.g. 'n')

*and returns the escaped character (e.g. '\n')

without lengthy switch case forest or lookup tables.
char escape(char x) {

}

Maybe there is some binary trick, which works for ASCII characters, like clearing a bit?
cpp reference makes it look like a daunting task and hard to get right. Especially, also because of the \c thingy. Should there not be a standard library function for that conversion?


text:
Q: Мобильная верстка выпадает из размеров экрана Столкнулся с такой пролемой при мобильной адаптации верстки.
Когда я захожу в режим разработчика в хроме и выбираю мобильную версию показа страницы, то верстка уходит за пределы заданных максимальных размеров. Пример на скрине:

Но после того, как я начинаю выбирать несколько раз различные версии мобильных телефонов, то все становится нормально и начинает правильно отображаться на всех версия мобильных телефонов.
Help me, please!

A: Это нормально. После перехода в разработчик в хроме (да и других тоже) и выбора мобильной версии показа страницы, следует перегрузить страницу (F5 или Ctrl+F5) и пару раз переключить вид на разных устройствах - это эмуляция, и не все срабатывает сразу.
Следует учитывать, что не все моменты на реальных устройствах отрабатывают (или совсем так отрабатывают) в разработчиках.


text:
Q: iOS 12 Xcode 10 application:openURL:options: Crash I recently noticed some issues with my app causing a Warning when uploading  to the Appstore:
Invalid Document Configuration - Document Based Apps should support either the Document Browser (UISupportsDocumentBrowser = YES) or implement Open In Place (LSSupportsOpeningDocumentsInPlace = YES/NO). Visit https://developer.apple.com/document-based-apps/ for more information.
My app responds to a custom extension set in its plist 'Document Types' and worked fine up until iOS 12/Xcode 10.
When adding 'Supports opening documents in place' to YES in the .plist and 'Supports Document Browser' to NO it crashes with this message:
'Application has LSSupportsOpeningDocumentsInPlace key, but doesn't implement application:openURL:options: on delegate'
My app supports iOS 8 and higher, and worked fine responding to:
(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

in my AppDelegate.
When I add the new
- (void)openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *)options completionHandler:(void (^)(BOOL success))completion

it still crashes with the error above..

A: add this in your app delegate:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return YES;
}

since ios 12 it is required if you also added LSSupportsOpeningDocumentsInPlace in your info.plist


text:
Q: Check if music has ended, OnStopped? Is it possible to make SFML 1.6 handle end of music by itself? Currently I have this:
//in music.cpp
music.Play()

//in main.cpp
//on every frame check for end of music
if(music.getStatus() == Sound::Stopped)
    loadNextMusicFile();

Isn't there a way in SFML to just say, "Play until music stopped, then load the next," without implementing this yourself? Or at least a more "elegant" way of noticing when the music stopped (like an OnStopped event)?

A: If you look at the code from Music.cpp
bool Music::OnGetData(SoundStream::Chunk& data)
{
    Lock lock(myMutex);

    // Fill the chunk parameters
    data.Samples   = &mySamples[0];
    data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());

    // Check if we have reached the end of the audio file
    return data.NbSamples == mySamples.size();
}

You see that it will return false when its at the end of the file.
So what you want to do is subclass sf::Music. e.g.
class MyMusic : public sf::Music
{
   bool OnGetData(SoundStream::Chunk& data)
   {
       bool running = sf::Music::OnGetData(data);
       if(!running)
          OnMusicEnd();
       return running;
   }
public:
   void OnMusicEnd()
   {
       // ...
   }

};


text:
Q: Python and Bitfinex Web Sockets. I know this may be a dumb question but I am still learning web-sockets with python.
Here is the code I have for testing out the api.
import json

from websocket import create_connection
ws = create_connection("wss://api2.bitfinex.com:3000/ws")
ws.send(json.dumps({
    "event": "subscribe",
    "channel": "book",
    "pair": "BTCUSD",
}))

while True:
    result = ws.recv()
    result = json.loads(result)
    print ("Received '%s'" % result)

ws.close()

Now here is my issue. I know with the REST API you can define variable and assign a JSON request to it for example.
bitFinexTick = requests.get("https://api.bitfinex.com/v1/ticker/btcusd")
return bitFinexTick.json()['last_price']

This would return the following
{"mid":"2276.85","bid":"2274.6","ask":"2279.1","last_price":"2275.0","timestamp":"1495763263.217562408"}

and then output
"2275.0"

However, with the websocket API the response is not labled, for example below.
[5, 2306.9, 0.0989, 2307.2, 0.07409371, -176.49194056, -0.0711, 2307.2, 55446.734771, 2690, 2141.1]

The data format following bitfinex's documentation is the following.
[
   "<CHANNEL_ID>",
   "<BID>",
   "<BID_SIZE>",
   "<ASK>",
   "<ASK_SIZE>",
   "<DAILY_CHANGE>",
   "<DAILY_CHANGE_PERC>",
   "<LAST_PRICE>",
   "<VOLUME>",
   "<HIGH>",
   "<LOW>"
]

Now my question is, how do I pull specifically only the LAST_PRICE from the json array and assign it to result?
Thanks a million for the help!

A: So you have what in python is a list right?
So you just do:
return bitFinexTick.json()[7]

Instead of
return bitFinexTick.json()['last_price']

This is because they aren't returning a 'dictionary' - where they are nicely naming the keys and values, just a list of values.
So you know that the value you want (last_price) is always going to be the 8th value in the list. Therefore the index of that value is 7, seeing as we start counting indexes at 0 in Python.


text:
Q: CONREC With An Irregular Grid? I've been using the CONREC routine to plot some contours for a long time and it's been working fine.  Here's a link to the algorithm:
http://paulbourke.net/papers/conrec/
But now I have an (effectively) irregular grid. I have data with "fill values". So, a grid might look like this:
1  6  3  5
3  4  4 -9
4  3  2 -9
2  2 -9 -9

Where -9 is designated as the fill value. When I change the fill value to some out of bounds number, like say 100, then it won't create contours for the area, but it will create contours at a steep slope leading to that fill area.  Here's an example:

Notice the black bands before the magenta color (the gray area is just debugging).  If I use a fill value closer to the range of the data then the banding goes away but it creates contours for the fill area.
Does anyone have any suggestions on a way to fix this? If not possible using this algorithm are there any other contouring packages that will work with irregular grids? I'm using java so that would be the easiest to reuse.

A: It seems to me the conrec algorithm doesn't support this. If you want an irregular shape/border you need to use a constrained algorithm. You can use a 2 step algorithm. First off, compute the shape, and second the contour map and then use the shape to determine what pixel is to use from the contour map. You can use a simple color check on the shape and of course check the whole shape. You can try my php implementation of a contour plot at cntm.codeplex.com.