text:
Q: pip install docx2html throws error I am trying to in install docx2html in python library using pip install docx2html but I am shown this traceback:
Collecting docx2html
  Using cached https://files.pythonhosted.org/packages/b3/a9/e943f7b36f1a8afd8b234b9e999be8837ab2666c7e743a4d527e14d39053/docx2html-0.2.3.tar.gz
Collecting lxml==2.2.4 (from docx2html)
  Using cached https://files.pythonhosted.org/packages/91/85/2776a729f8ef1e2aca83e02393dbdfcdf2c0f7c5a1205a77bbf1f82230f9/lxml-2.2.4.tar.gz
Collecting pillow==1.7.7 (from docx2html)
  Using cached https://files.pythonhosted.org/packages/77/93/d6eabe91dda55ac924c95763568d596e3e6082950a04c24fccf32c12324c/Pillow-1.7.7.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/_y/g09fpxn13xq7z6ptmq3095dm0000gn/T/pip-install-9u3p45p6/pillow/setup.py", line 162
        print "--- using Tcl/Tk libraries at", TCL_ROOT
                                            ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("--- using Tcl/Tk libraries at", TCL_ROOT)?

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/_y/g09fpxn13xq7z6ptmq3095dm0000gn/T/pip-install-9u3p45p6/pillow/

I tried pip install --upgrade setuptools but setuptools are upto date.

A: I resolved the issue by using pypandoc instead of docx2html to convert docx to html.


text:
Q: Validation Rule in Property Sheet Not Doing Anything I am using MS Access 2016
I have two dates, a start date and an end date. I want to make sure that the end date occurs after the start date so I wrote a validation rule in the Property Sheet.
I wrote:
[End Date]>=[Start Date]

However it does not work. If I put an end date that occurs before the Start Date, the entry is still valid.
Any help will be appreciated.
Edit:

What I highlighted red is where I get the error:

"Invalid SQL Syntax - cannot use multiple columns in a column-level
  CHECK constraint"

A: Leave the validation rule for the field(s) empty. Then, for the table (your yellow marking), set validation rule to:
[End Date]>=[Start Date]

A: Don't reference [End Date] in the expression, just:
 >=[Start Date]

And if you want to allow Null:
 >=[Start Date] Or Is Null

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to determine status of lock file in the data directory I am trying to run multiple mongod instances on the same centos machine with different config files.
I am getting following error while running the instance as a service:
sudo service mongod1 start

/var/lib/mongo1: boost::filesystem::status: Permission denied: "/var/lib/mongo1/mongod.lock"

I have added the permissions for the /var/lib/mongo1 using:
sudo chmod -R 600 /var/lib/mongo1

I also tried with 700, 755 and 777 at the end but nothing seems to work.
mongod:mongod is the owner of the folder /var/lib/mongo1

Any help is appreciated.

A: I know this is really late but I was struggling with this for days and just now found the fix. That being said for future users running into this issue the solution if you're using SELinux is to check the context of the default mongodb path against your own to make sure they are the same by executing
ls -dZ /var/lib/mongo/

the output should look something like this
drwxr-xr-x. mongod mongod system_u:object_r:mongod_var_lib_t:s0 /var/lib/mongo/

if it's not then you can copy it by doing
chcon -R --reference=/var/lib/mongo /your/path

the source can be found here

A: Maybe the lock file is missing? Which might explain why chmod isn't having the desired effect...
Try:
 touch /var/mongo1/mongod.lock
 chown mongod:mongod
 chmod 600 /var/mongo1/mongod.lock

A: important :
Don't try to restart mongo using sudo as it tries to change the user to root where as /var/lib/mongodb owner is mongod:mongod

A: Please remember that Directories needs to have execute permission, but the files within the directories do not need to execute permission.
The following 2 commands worked for me
$ sudo chmod -R 770 /var/lib/mongo1
$ sudo find /var/lib/mongo1 -type f -exec chmod 660 {} \;

This will first give everything under /var/lib/mongo1 execute permission, and then return all the normal files to having only read and write, but not execute.


text:
Q: Unit Test with Express / Mocha / Mongodb Memory Server I would like to configure my project in order to run unit test for some API endpoints (that call the database). I'm using :

*

*ExpressJS

*MongoDB (no Mongoose)

*Mocha / Chai

*Mongodb Memory Server (to mock the DB)

// app.ts

export const app = express();

const port = process.env.PORT;

app.use("/my-route", myRoutes);

mongoConnect().then(() => {
  app.listen(port, () => {
    console.log(`Listening on port ${port}`);
  });
});

// database.ts

export const mongoConnect = async () => {
  try {
    let MONGODB_URI = process.env.MONGODB_URI;

    if (process.env.NODE_ENV === "test") {
      const mongoServer = await MongoMemoryServer.create();
      MONGODB_URI = mongoServer.getUri();
    }

    const client: MongoClient = await MongoClient.connect(MONGODB_URI);
    _db = client.db("dbName");
    _mongoClient = client;

    if (process.env.NODE_ENV === "test") {
      console.log("Connected to MongoDB Test");
    } else {
      console.log("Connected to MongoDB");
    }
  } catch (err) {
    console.log("Error connecting to MongoDB:", err);
    throw err;
  }
};

export const getMongoClient = () => {
  if (_mongoClient) {
    return _mongoClient;
  }
  throw "Mongo client doesn't exist";
};

export const getDb = () => {
  if (_db) {
    return _db;
  }
  throw "No database found!";
};

// test.ts

  let mongoClient: MongoClient;
  let db: Db;

  before(function (done) {
    mongoConnect()
      .then(() => {
        db = getDb();
        mongoClient = getMongoClient();
        return db.createCollection("wordsCollection");
      })
      .then(() => {
        db.collection("wordsCollection").insertMany(data);
      })
      .catch((err) => console.log(err))
      .finally(() => done());
  });

  after(function (done) {
    db.dropDatabase();
    mongoClient.close().then(() => {
      done();
    });
  });

  it("test", async function () {
    let res = await chai
      .request(app)
      .post("/my-route/hello")
      .send({ excludeIds: [] });

    expect(res.status).to.equal(200);
  });
});

But it's not working...
If I call mongoConnect() in test.ts it console.log twice Connected to MongoDB Test. But if I don't call the function it throws me error because MongoClient is undefined.
I think await chai.request(app) already calls the database and server but I need to create Collection and Documents before. So I need to connect to the DB before the test.
Any help would be greatly appreciated.

A: I found a solution, I don't know if it's best practice but it works and is pretty easy, thanks to this post : https://stackoverflow.com/a/70285190/10547153.
I needed to add a condition in app.ts before making the connection to the database and the server in order to launch them only if it's called by Node itself.
if (require.main === module) {
  mongoConnect().then(() => {
    app.listen(port, () => {
      console.log(`Listening on port ${port}`);
    });
  });
}

When a file is run directly from Node.js, require.main is set to its
module. That means that it is possible to determine whether a file has
been run directly by testing require.main === module.

Now I can connect to the mocked database from test.ts and only one connection will be triggered.


text:
Q: How to get Gltf data from a xeogl scene? I am trying to get specific Gltf-data such as the mesh name (as written in the .gltf file) when clicking on a mesh inside a 3D viewer in a React web application. For the viewer i am using Xeogl from xeolabs, which is able to display a gltf file in a html-canvas element. However, the only data I am able to extract from the interface is data from Xeogl-parameters (eg. scene, material, children,... see figure 2).
I seem to be unable to get any of the metadata found inside the .gltf file itself.
Does anybody know how the gltf-data is integrated in the Xeogl-model, or how I can find the respective gltf data from the .gltf file when clicking on a mesh?
Thanks in advance!
Figure 1: The Click Event

Figure 2: the outcome we get from event with xeogl data (left), the outcome we want from .gltf file (right)

A: You need to define a handleNode callback during loading of the gltf model. See: http://xeogl.org/docs/classes/GLTFModel.html and look for the handleNode function.
In that callback, you can define an actions.createObject object. Any parameter you define there will be merged into the final mesh object of xeogl, and you may than access that parameter later using the default xeogl tools.
For example, I have this code when loading the gltf model:
handleNode: (function () {
                let objectCount = 0
                return function (nodeInfo, actions) {
                  if (nodeInfo.mesh !== undefined) {
                    // Node has a mesh
                    actions.createObject = {
                      id: model.commit.hash + '.' + objectCount++,
                      guid: nodeInfo.name,
                      entityType: 'ifc'
                    }
                  }
                  return true
                }
              })()

Look at the entityType property. I populate that with a fixed value, but it can also be dynamic info from the gltf node. It becomes part of the xeogl object so I can access it later.


text:
Q: Master-Slave and Publish-Subscribe connections Assuming I have a Master-Slave deployment of Redis (1 master, 1 slave) and a client (webapp) that will manage Publish-Subscribe.

*

*Can I Publish messages to the slave and will they be "seen" by the master?

*Or should I use only the Master for Publish and the Slave for Subscribe commands?

I've been looking around but couldn't find the answer. Anyone knows?

A: EDIT: As @jameshfisher pointed out, the link below is regarding Redis Cluster. The comment from @lionello seems to be the correct answer:

Publishing to a slave will not propagate to the master, only the other way around.

The answer is on the cluster-spec docs:

Publish/Subscribe
In a Redis Cluster clients can subscribe to every node, and can also publish to every other node. The cluster will make sure that published messages are forwarded as needed.
The current implementation will simply broadcast each published message to all other nodes, but at some point this will be optimized either using Bloom filters or other algorithms.

A: For the typical data you store in Redis, you should only write to the master.
From http://redis.io/topics/replication:

...writes [to slaves] will be discarded if the slave and the master will [sic] resynchronize, or if the slave is restarted...

In fact, starting from v2.6, you can put slaves in slave-read-only mode which would prevent the mistake of writing data to a slave.
The documentation does go on to mention a potential use case for writing data to slaves:

...often there is ephemeral data that is unimportant that can be stored
  into slaves. For instance clients may take information about
  reachability of master in the slave instance to coordinate a fail over
  strategy.


text:
Q: Is it possible to run a Rails 4.2 app on Ruby 2.4? I want to try out a Rails 4.2 app on Ruby 2.4.
However, when I try doing it, I get errors about the json gem version 1.8.3 failing to install.
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator
/Users/agrimm/.rbenv/versions/2.4.0-rc1/bin/ruby -r ./siteconf20161223-91367-cql0ne.rb extconf.rb
creating Makefile

current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
generator.c:861:25: error: use of undeclared identifier 'rb_cFixnum'
    } else if (klass == rb_cFixnum) {
                        ^
generator.c:863:25: error: use of undeclared identifier 'rb_cBignum'
    } else if (klass == rb_cBignum) {
                        ^
2 errors generated.
make: *** [generator.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3 for inspection.
Results logged to /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-14/2.4.0-static/json-1.8.3/gem_make.out

An error occurred while installing json (1.8.3), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.3'` succeeds before bundling.

which I assume is due to the unification of Fixnum and Bignum into Integer.
If I add to the Gemfile a constraint that json has to be version 2.0.0, then it complains that Rails 4.2 requires json ~> 1.7, which forbids 2.0.0.
Am I out of luck unless the maintainers of Rails decide to make a change to a non-5.x version of Rails, or the maintainers of the json gem decide to make a new non-2.x version of their gem?

A: Upgrade rails to rails-4.2.8 .This is the first 4.2.x version that officially supports ruby-2.4

A: It looks like it won't be possible at the moment (Although it sounds odd).
See the Changelog for the JSON gem. Json 2.0.0 adds compatibility for ruby 2.4, but rails 4.2 restricts json to 1.x

A: The json gem has a fix on the 1.8 branch. Hopefully it'll be released as a gem soon, but in the meantime you can use it directly in your Gemfile:
gem 'json', github: 'flori/json', branch: 'v1.8'

Rails has also merged a fix to the 4-2-stable branch about a week after the latest official 4.2.x gem release. Hopefully they'll release a new gem soon too, but this might help in your Gemfile:
gem 'rails', github: 'rails/rails', branch: '4-2-stable'

Finally, you may need to load arel from a git source as well:
gem 'arel', github: 'rails/arel', branch: '6-0-stable'

With those three changes I was able to boot our app and query the database, but then ran into other Integer unification related issues. Seems like this change to going to cause some waves.

A: It is now possible with rails 4.2.8.rc1 (February 11th 2017)


text:
Q: Use Windows Forms in a .Net Core Class Library - .NET Core Control Library I am trying to create a .net core 3 class library that references the .net core 3 version of winform (so this assembly can itself be referenced by a .net core 3 WinForm assembly).
A new .net core WinForm project references Microsoft.WindowsDesktop.App.WindowsForms, however I can't find any nuget package with that name.
What do I need to do to reference the .net core 3 winform?

A: I had a core 3.1 web app referring to a Framework 4.5.2 project that had dependencies on System.Windows.Forms. The fix for me was to add the below line to web app csproj file:
FrameworkReference Include="Microsoft.WindowsDesktop.App.WindowsForms"
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFrameworks>netcoreapp3.1</TargetFrameworks>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WindowsForms" />
  </ItemGroup>

</Project>

A: The currently accepted answer appears to be somewhat outdated. The recent syntax requires the target to be specified in the TargetFramework tag, not in the Sdk tag:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Library</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
  </PropertyGroup>

</Project>

More info here

*

*https://learn.microsoft.com/en-us/dotnet/desktop/winforms/migration/?view=netdesktop-5.0

*https://learn.microsoft.com/en-us/dotnet/standard/frameworks

A: In alternative you can add a new project of Windows Form Type and than set the output type to Libray.
<OutputType>Library</OutputType>

A:
Update: In later versions of VS 2019 (I tried Version 16.8.2) there is a project template for Windows Forms Control Library for .NET Core.

Currently Windows Forms .NET Core is in Preview mode and I don't know any official Nuget package or Project template for Windows Forms Control Library in .NET Core in VS 2019 16.2.2.
But to create a Windows Forms Control Library, you can use the following instructions:

*

*Add a new project of type Class Library (.NET Core)

*After project created, right click on project file and choose Edit Project File

*Change the project SDK to <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

*Specify windows forms as UI technology by adding <UseWindowsForms>true</UseWindowsForms>.

Now the project file should be like the following:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
    <OutputType>Library</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
</Project>

Now you can add Windows forms elements like Form or UserControl to this project and build the project without any problem.

A: For me, with net5 I needed the following in my project
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
      <TargetFramework>net5.0-windows</TargetFramework>
      <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>


text:
Q: Introduce two strings in a "for" loop I have this dataframe:
a <- c(2,5,90,77,56,65,85,75,12,24,52,32)
b <- c(45,78,98,55,63,12,23,38,75,68,99,73)
c <- c(77,85,3,22,4,69,86,39,78,36,96,11)
d <- c(52,68,4,25,79,120,97,20,7,19,37,67)
e <- c(14,73,91,87,94,38,1,685,47,102,666,74)

df <- data.frame(a,b,c,d,e)

and this script:
R <- Map(`+`, list(1:3), 0:9)
cmin <- t(as.matrix(rep(NA, ncol(df))))

for (r in seq(R)) {
  for (f in seq(ncol(df))) {
    x <- df[R[[r]], f]
    y <- df[R[[r]], -f]
    dif_2 <- (x - y)^2
    cmin[f] <- which.min(colSums(dif_2))
  }
}

dif_3 <- as.matrix(dif_2[,cmin])
sq <- sqrt(dif_3)

How can I put the last two lines of the script into the "for" loop above?
Thanks everyone for helping me!

A: If the output of 'sq' should be a vector
sq <- c()
for (r in seq(R)) {
  for (f in seq(ncol(df))) {
    x <- df[R[[r]], f]
    y <- df[R[[r]], -f]
    dif_2 <- (x - y)^2
    cmin[f] <- which.min(colSums(dif_2))
    dif_3 <- as.matrix(dif_2[,cmin[f]])
    sq <- c(sq, sqrt(dif_3))
  }
}

-output
> sq
  [1]  12  68   1  31   5   7  25  17   1  25  17   1  31   5   7  68   1  10   5   7  32  17   1   3  17   1   3   5   7  32   8  22   7
 [34]   8  22   7   1   3  75   1   3  75   1  10  38  10  38  27  32  31  26  55  52   4  52  23  55  10  38  27  52   4   1  31  26  22
 [67]  52   4   1  23  55  12  31  26  22   4   1  36  57  63   1   4   1  36  51  11  19  27  84 610  12  55   5  63   1   3  63   1   3
[100]  12  55   5  84 610  35  55   5   5   1   3  32   1   3  32  55   5   5 610  35  78   5   5  15   3  32   3   3  32   3   5   5  15
[133]  28  34 567   5  15  35  32   3  62  12  44  21   5  15  35  34 567   1

If it should be a list
sq <- list()
for (r in seq(R)) {
  for (f in seq(ncol(df))) {
    x <- df[R[[r]], f]
    y <- df[R[[r]], -f]
    dif_2 <- (x - y)^2
    cmin[f] <- which.min(colSums(dif_2))
    dif_3 <- as.matrix(dif_2[,cmin[f]])
    sq <- c(sq, list(sqrt(dif_3)))
  }
}

sqmat <- do.call(cbind, sq)

A: If I understand correctly, you want the min distances for each row indices given in R. The code below creates two data structures, sq_list1 and sq_3d that store the same values but one o them is a list of matrices and the other is a 3d array with the 3rd index 1:length(R).
sq_list <- replicate(length(R),
                     matrix(nrow = length(R[[1]]), ncol = ncol(df)),
                     simplify = FALSE)
sq_3d <- replicate(length(R),
                      matrix(nrow = length(R[[1]]), ncol = ncol(df)))

for (r in seq(R)) {
  for (f in seq(ncol(df))) {
    x <- df[R[[r]], f]
    y <- df[R[[r]], -f]
    dif_2 <- (x - y)^2
    cmin <- which.min(colSums(dif_2))
    dif_3 <- dif_2[, cmin]
    sq_list[[r]][, f] <- sqrt(dif_3)
    sq_3d[, f, r] <- sqrt(dif_3)
  }
}

# output not shown
sq_list
sq_3d

Edit
This seems simpler.
faux <- function(r, df){
  sub_df <- df[r, ]
  sapply(seq(ncol(sub_df)), \(f){
    d <- (sub_df[, f] - sub_df[, -f])^2
    cmin <- which.min(colSums(d))
    sqrt(d[, cmin])
  })
}
sq_list2 <- lapply(R, faux, df = df)
identical(sq_list, sq_list2)
#[1] TRUE


text:
Q: Limit number of threads calling a method in Spring (Boot) We have a Spring Boot service like this:
@Service
public class XXXDataService {
    public XXXModel resolveData(){
    }
}

The resolveData method fetches data from a datasource and returns it. In general it can handle several threads asking for data at the same time. But not more then n threads at the same time.
Is there a Spring-build-in solution to restrict the number of threads accessing a method.
Something like @Synchronized(maxParallelAccesses=10).
Hint 1: It is important that all the other Spring interceptors are also not fired, for example a transaction should not be started until the method is not blocked anymore.
Hint 2: I don't wan't to restrict the overall number of threads of the application but only having some kind of method synchronization with size > 1.

A: I don't think Spring or even Java provides a build-in annotation to do that. But that logic can be implemented with a Semaphore:
@Service
public class XXXDataService {

    private Semaphore semaphore = new Semaphore(10);

    public XXXModel resolveData(){
        semaphore.acquire();
        //... logic accessible by max 10 threads concurrently
        semaphore.release();
    }
}


text:
Q: Build fails on vercel but succeeds on local I have a flutter application that I'm deploying on vercel.
My problem is that after updating a package I use, my build in vercel fails. When I build the exact same location manually, it works.
This indicates to me that there must something be wrong with the way I'm deploying but I have no idea what the differences to building locally are.
The error I get on vercel is:
../.pub-cache/hosted/pub.dev/audioplayers_web-2.1.0/lib/web_audio_js.dart:8:12:
Error: `@staticInterop` classes should not contain any generative constructors.
  external JsAudioContext();

My install command for Vercel is:
if cd flutter; then git pull && cd .. ; else git clone https://github.com/flutter/flutter.git; fi && ls && flutter/bin/flutter doctor && flutter/bin/flutter clean && flutter/bin/flutter config --enable-web
And my build command for vercel is
flutter/bin/flutter build web --profile -t lib/main.dart --web-renderer=canvaskit


text:
Q: thread(?) database locking(?) in rails Say I have this method:
def create_registration_unless_over_limit
  if Registration.count < 50
    Registration.create!
  else
    raise "too many registrations"
  end
end

How do I ensure that I never have >= 50 registrations considering that I have more than one rails process running?  Theoretically, isn't it possible that two requests come in virtually simultaneously, both run the if statement and see < 50 registrations is true and then both of them create a new registration?

A: For your particular case, just ignore the problem :) I'm 99.99% sure you don't really care if you have 50 or 51 registrations :)
In a more general case you need to employ some locking.
SELECT count(*) FROM registrations FOR UPDATE

the above query will block if another thread executed it and is still inside a transaction.
unfortunately 'count' method of ActiveRecord::Base doesn't support the :lock parameter (hmm, why?). So you need to use count_by_sql. Try the following in 2 separate terminal screens:
./script/runner 'Registration.transaction {puts "counting...";c = Registration.count_by_sql("select count(*) from registrations for update");puts "count = #{c}. press enter to continue";gets}'

while 1st one that runs will stop at the 'press enter' stage, the 2nd one should block at the 'counting...' stage until you release the 1st.

A: stored proc to create the row if < 50, or else return a fault code
Or!
Create a queue system that creates the accounts, ensuring one process is creating them at all times


text:
Q: What's the meaning of [1] in matplotlib's subplots()? Some time ago I've seen a usage of matplotlib's subplots() like this:
fig, ax1 = plt.subplots()[1]

and I've used it for some reason in my own script, but unfortunately I've entirely forgotten the meaning of [1] in it (I should have added a comment in my code!). Could someone tell me what it does?

A: I'll try to explain what the [1] is and why perhaps it's not what you actually intend to get, step-by-step. Also, I'm assuming you don't literally run fig, ax = plt.subplots()[1], as that should give an error, because there is nothing to unpack in the second element of this object. I'll use the example of 4 subplots, (2,2).
So, first of all, plt.figure() returns a tuple, with a figure and a collection of Axes (depending on how many rows and cols you pass as arguments). So:
a = plt.subplots(2,2)  # 2,2 is an example, it could also be empty, so same as (1,1); the below would still hold
type(a)
len(a)

this returns tuple of len = 2. If you now check what is the first element of the tuple, you'll see it's the actual empty figures (graphically depicted):
a[0]

while the second element is the array of Axes (an Axes` is the region of the image with the data space, or how I like to think about it "the actual representation of a set of data on a given figure").
a[1]

array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fe02397c650>,
    <matplotlib.axes._subplots.AxesSubplot object at 0x7fe022c1e4d0>],
   [<matplotlib.axes._subplots.AxesSubplot object at 0x7fe022deb210>,
    <matplotlib.axes._subplots.AxesSubplot object at 0x7fe0239b5ed0>]],
  dtype=object)

Now, if you are explicitly limiting your selection to the second element of the plt.subplots() tuple, that means you are only grabbing the Axes to unpack into fig and ax.
fig, ax = a[1]
fig

this returns:
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fe02397c650>,
   <matplotlib.axes._subplots.AxesSubplot object at 0x7fe022c1e4d0>],
  dtype=object)

ax

this returns:
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fe022deb210>,
   <matplotlib.axes._subplots.AxesSubplot object at 0x7fe0239b5ed0>],
  dtype=object)

So essentially you assigned the Axes of the first row to the fig object, and the Axes of the second row to the ax object. Depending on how your plotting function goes on next, it is possible that these subplots are either never used, or you somehow don't get an error because you chose a specific subplot size. Of course, if your goal is to actually only use the second element of plt.subplots(), i.e. the set of Axes, you can do that. But then fig will no longer actually be a figure. Just to demonstrate what happens when I use the whole plotting pipeline like you suggested (using the iris dataset for example):
fig, ax = plt.subplots(2,2)[1]
ax[0].scatter(x=iris.sepal_length, y=iris.sepal_width) # Filling in the first `Axes`
ax[1].scatter(x=iris.sepal_width, y=iris.sepal_length) # Filling in the second `Axes`
plt.show()

Finally, if you want to read more about it, the matplotlib documentation on subplots() has a few more examples, and also shows that plt.subplots(), regardless of the shape you pass into it, always returns a tuple of fig, ax (where "ax : axes.Axes object or array of Axes objects").


text:
Q: ensure layout in NSLayoutManager I have a UITextView with lots of text. The scrolling is mostly smooth on iPhones 4, 5, and 6, but on the 6 Plus there is lots of stuttering. (I believe this is because the 6 Plus is underpowered for the amount of pixels it has to push around). I notice that once I scroll past a region, if I scroll back over it, the scrolling is nice and smooth; layout has already been performed for the region and the processor doesn't have to do much. I want to force layout to occur before I get to the region. This is what I tried:
textView.layoutManager.ensureLayoutForTextContainer(textView.textContainer)

This doesn't appear to do anything at all. The scrolling is still not smooth on first pass over a region, and the before and after log statements have a difference of .00014 of a second. Just to make sure I was really getting the correct text container, I also tried:
textView.layoutManager.ensureLayoutForTextContainer(textView.layoutManager.textContainers[0] as NSTextContainer)

This also made no difference.
What do I need to do to force layout of all text in the text container?
Any help would be greatly appreciated.
Thanks.
EDITED TO ADD:
To answer TheCodingArt's question: I'm not doing anything exotic in terms of the layout manager. This is my set up code:
var textStorage = NSTextStorage()
var layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
var textContainer = NSTextContainer(size: textContainerSize)
layoutManager.addTextContainer(textContainer)

textView = UITextView(frame: CGRectMake(0, 0, textViewWidth, textViewHeight), textContainer: textContainer)

textView.showsHorizontalScrollIndicator = false
textView.showsVerticalScrollIndicator = false
textView.backgroundColor = UIColor.clearColor();
textView.editable = false;
textView.selectable = true;
textView.scrollsToTop = false
self.view.addSubview(textView)

Explicity instantiating and adding the text container and text storage is something I learned to do from the first answer to this question:
Scroll to bottom of UITextView erratic in iOS 7
...and which did help somewhat, but not enough for the 6 Plus.
Later, I add text to it:
textStorage.appendAttributedString(attribStr)


text:
Q: Implement builder method with arguments I have the following code:
ApiRequest request = ApiRequest.builder("test 55").clientName(SERVICE).build();

I implemented this code:
@Builder
@Getter
@Setter
public class ApiRequest {

    private String clientName;

    public static class builder{

        private String clientName;

        public builder(String bucketKey) {
            this.bucketKey = bucketKey;
        }

        public builder(String clientName, ......) {
            this.clientName= clientName;
            ....
        }

        public ApiRequest build(){
            return new ApiRequest (clientName, .....);
        }

    }
}

For build I get error Expected 0 arguments but found 1 Do you know what is the proper way to implement this code?

A: You can implement a builder in two different ways.
Plain java
In that case, you don't add any annotations and write all code with your hands:
public class ApiRequest {

    private String clientName;
    private String serviceName;

    public ApiRequest(final String clientName, final String serviceName) {
        this.clientName = clientName;
        this.serviceName = serviceName;
    }

    public static void main(String[] args) {
        String SERVICE = "Some service name";
        final String clientName = "test 55";
        ApiRequest request = ApiRequest.builder(bb).setServiceName(SERVICE).build();
    }

    private static Builder builder(final String clientName) {
        return new Builder(clientName);
    }

    private static class Builder {

        private final String clientName;
        private String serviceName;

        public Builder(final String clientName) {
            this.clientName = clientName;
        }

        public Builder setServiceName(final String serviceName) {
            this.serviceName = serviceName;
            return this;
        }

        public ApiRequest build() {
            return new ApiRequest(clientName, serviceName);
        }
    }
}

Moreover, it's better to set clientName using separate setter (not in the constructor).
Lombok
Since you are using Lombok, it becomes much easier, just use @Builder annotation without any other code:
@Builder
public class ApiRequest {

    private String clientName;
    private String serviceName;

    public ApiRequest(final String clientName, final String serviceName) {
        this.clientName = clientName;
        this.serviceName = serviceName;
    }

    public static void main(String[] args) {
        String SERVICE = "Some service name";
        final String clientName = "test 55";
        ApiRequest request = ApiRequest.builder().clientName(clientName).serviceName(SERVICE).build();
    }
}

A: Lombock provide you builder method without parameters.
If you want additional methods you can add
public static Builder builder(String bucketKey) {
return builder()
.setBucketKey(bucketKey);
}
Also you don't need builder inner class. It isn't used anyway. Lombock generate Builder inner class for you.


text:
Q: How do copy for UILabel? I have IBOutlet UILabel *label;
and I want to do  this
UILabel *label = [titleLabel copy];
label.text = @"Clone";
titleLabel.text = @"Original";
NSLog(@"label : %@, title : %@",label.text,titleLabel.text);

and this throw exception

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILabel copyWithZone:]: unrecognized selector sent to instance 0x6a4a450'
  * First throw call stack:
  (0x126f052 0x1823d0a 0x1270ced 0x11d5f00 0x11d5ce2 0x1271bd9 0x2ed6 0x1270e1a 0x2851 0x28264e 0x1e2a73 0x1e2ce2 0x1e2ea8 0x1e9d9a 0x24af 0x1ba9d6 0x1bb8a6 0x1ca743 0x1cb1f8 0x1beaa9 0x215cfa9 0x12431c5 0x11a8022 0x11a690a 0x11a5db4 0x11a5ccb 0x1bb2a7 0x1bca9b 0x21c2 0x2135)

A: Swift 3 Solution
I created it as an extension to the UILabel.
extension UILabel {
    func createCopy() -> UILabel {
        let archivedData = NSKeyedArchiver.archivedData(withRootObject: self)
        return NSKeyedUnarchiver.unarchiveObject(with: archivedData) as! UILabel
    }
}

How to use
let anotherNameLabel = nameLabel.createCopy()

Additional Info - How does this work?
NSKeyedArchiver will take an object from memory and convert it to text. "Keyed" means it uses words to describe the properties of this object, like "LabelFrame", "LabelText", etc. (These are fake keys.) This also called Serialization in other technologies.
NSKeyedUnarchiver does the opposite. It will take that text and build an object. Here we take that object (Any?) and convert it to a UILabel.

A: There is no public Apple API to deep copy a UILabel. Your best bet is to make a helper method which copies all the parts you care about.
- (UILabel *)deepLabelCopy:(UILabel *)label {
    UILabel *duplicateLabel = [[UILabel alloc] initWithFrame:label.frame];
    duplicateLabel.text = label.text;
    duplicateLabel.textColor = label.textColor;
    // etc... anything else which is important to your ULabel

    return [duplicateLabel autorelease];
}

If you want to use it all over your code base you can change it to a static method and put it in some sort of utility class. If you named the class LabelUtils you could do something like...
+ (UILabel *)deepLabelCopy(UILabel *)label {
    // ...
}

and would be called using UILabel *dupLabel = [LabelUtils deepLabelCopy:origLabel];

A: I recommend using a merged version of Answer 1 and Answer 2:
- (UILabel *)copyLabel:(UILabel *)label {
    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: label];
    UILabel* copy = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
    return copy;
}

Then simply use something like
UILabel* labelcopy = [self copyLabel:originalLabel];

in your code.

A: UILabel does not conform to NSCopying, so you cannot make a copy via -copy.
But it does conform to NSCoding, so you can archive the current instance, then unarchive a 'copy'.
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: label];
UILabel *labelCopy =   [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];

Afterwards, you'll have to assign any additional properties that weren't carried over in the archive (e.g. the delegate) as necessary.

A: I solved it this way and wanted to post it for easy copy and pasting if you were thinking of doing the same.
func makeCopy() -> UILabel {

  let label = UILabel(frame: frame)
  label.text = text
  label.font = font
  label.textColor = textColor
  label.shadowColor = shadowColor
  label.shadowOffset = shadowOffset
  label.textAlignment = textAlignment
  label.lineBreakMode = lineBreakMode
  label.attributedText = attributedText
  label.highlightedTextColor = highlightedTextColor
  label.isHighlighted = isHighlighted
  label.isUserInteractionEnabled = isUserInteractionEnabled
  label.isEnabled = isEnabled
  label.numberOfLines = numberOfLines
  label.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
  label.baselineAdjustment = baselineAdjustment
  label.minimumScaleFactor = minimumScaleFactor
  label.allowsDefaultTighteningForTruncation = allowsDefaultTighteningForTruncation
  label.preferredMaxLayoutWidth = preferredMaxLayoutWidth

  return label
}


text:
Q: Why does vim open network connections to a process owned by another user? I just noticed something really weird...
When I run lsof of my vim process I see connections to port 6013 of a process owned by another local user. I wonder where they might come from. I trust the system and that other user. I don't expect any form of attack. Rather a PEBKAC-style error on my behalf.
I've been looking through my vimrc, even grepped through my vimfiles looking for "6013" but could not find any matches.
I am at a loss to look where they might come from...
Something to note is that the "remote" process is the sshd process of that other user.
lsof output (in total 513 lines):
vim     25955 michel    3u  IPv6 106403503      0t0  TCP localhost:36886->localhost:6010 (ESTABLISHED)
vim     32539 michel    3u  IPv6 106429306      0t0  TCP localhost:42422->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    4u  IPv6 106429312      0t0  TCP localhost:42423->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    5u  IPv6 106429316      0t0  TCP localhost:42424->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    6u  IPv6 106429320      0t0  TCP localhost:42425->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    7u  IPv6 106429324      0t0  TCP localhost:42426->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    8u  IPv6 106429330      0t0  TCP localhost:42427->localhost:6013 (CLOSE_WAIT)
vim     32539 michel    9u  IPv6 106429334      0t0  TCP localhost:42428->localhost:6013 (CLOSE_WAIT)
vim     32539 michel   10u  IPv6 106429338      0t0  TCP localhost:42429->localhost:6013 (CLOSE_WAIT)
vim     32539 michel   11u  IPv6 106429344      0t0  TCP localhost:42430->localhost:6013 (CLOSE_WAIT)
vim     32539 michel   12u  IPv6 106451243      0t0  TCP localhost:42695->localhost:6013 (CLOSE_WAIT)
[snip]

Current list of plugins:
Plugin 'Jinja'
Plugin 'MarcWeber/vim-addon-mw-utils'
Plugin 'NrrwRgn'
Plugin 'SirVer/ultisnips'
Plugin 'ctrlp.vim'
Plugin 'ervandew/supertab'
Plugin 'gitv'
Plugin 'gmarik/Vundle.vim'
Plugin 'itchyny/lightline.vim'
Plugin 'jelera/vim-javascript-syntax'
Plugin 'mattn/emmet-vim'
Plugin 'molokai'
Plugin 'scrooloose/nerdtree'
Plugin 'tomtom/tlib_vim'
Plugin 'tpope/vim-fugitive'
Plugin 'tpope/vim-surround'
Plugin 'unimpaired.vim'
Plugin 'klen/python-mode'

Looking at the output of sudo netstat -ltpn | grep 6013, I see this:
tcp        0      0 127.0.0.1:6013          0.0.0.0:*               LISTEN      2285/sshd: franky@n
tcp6       0      0 ::1:6013                :::*                    LISTEN      2285/sshd: franky@n

So the process owned by me (michel), opens a TCP connection to a process owned by franky.
I also tried to run vim without vimrc, using vim -u NONE, but the network connections still appear...

A: In the mean-time, I came to the same comclusion as @Wumpus: Port 6013 is a port related to X11 forwarding. And in the end it turned out to be a problem with my ~/.Xauthority. I simply removed this file and re-connected to the remote host which solved the problem.
It might also have been a bad $DISPLAY variable. But I read @Wumpus's comment only after I removed my ~/.Xauthority file, so I cannot his theory.


text:
Q: Can I remove an enum value with if it has been save with a JDO entity? So I have saved a JDO entity that contains an value of MyEnum.
public enum MyEnum {
    MyValue1,
    MyValue2,
    MyValue3;
}

However now I need to remove at least one of the enum values. Will this crash JDO queries since a value that has been stored is no longer valid?
Thanks for the help.

A: JDO most probably uses Enum.valueOf(class, string) to instantiate enums. So in case of unsupported values it will produce IllegalArgumentException.

A: You cannot add or remove enums in runtime, that is a Java thing, not GAE.

A: Just like peter said, removing values from an enum will throw an error. However I just kept the old values and created a method getValues() which returns an array of current values and just use these. As users use the new version the old values will be automatically updated and can eventually be safely removed.


text:
Q: How to get the status of a list of VM in Azure using Powershell Get-Azvm I am trying to get a list of Azure vm statuses (Allocated,Deallocated). I am able to get it one at a time for a single vm. But when i have a list of VM's or when using wildcard's it fails to get the vm status. Any tips
$ResGrp= "resvmtest"
$action="start"

 $vmList = Get-AzVM -ResourceGroupName $ResGrp -Name *  -Status

       foreach($vm in ($vmList | Select-Object @batch)){
  Write-Host $vm.Statuses[1].DisplayStatus
         }

A: I see that you were trying to display the VMs in batches. Unless you have VMs in the thousands, that's not necessary. I also no longer see the Statuses property in Get-AzVM cmdlet. Just try this:
$vmList = Get-AzVM -ResourceGroupName $ResGrp -Status
$vmList | Select-Object Name, PowerState, ProvisioningState # or any other properties you want to display

Either that or I'm not understanding your question.

A: Just try this :
Get-AzVm -ResourceGroupName <rg name> -Status | Select-Object Name, PowerState

A: This behaviour appears to have changed. Using the Status parameter now creates an object named Status and within that object.
One way to show the output:
select Name, @{n='New';e={($_.Statuses | where Code -eq 'PowerState/running').DisplayStatus}}


text:
Q: PerformanceCounter extremely slow in connecting remote server I try to use PerformanceCounter to monitor remote server information in a domain environment, like:
var counter = new PerformanceCounter("PhysicalDisk", "Disk Bytes/sec", "_Total", "REMOTE_SERVER");

there is only 1 line of code, running the above code will wait at least 50 seconds.
I tried to impersonate the admin etc, still same time.
I also tried with PowerShell get-counter, still more or less speed.
I tried with windows native Performance Monitoring Tool in computer management, connect to remote server, takes a few second only.
Any idea how to improve the connection speed?

A: If you are monitoring your local computer, I've found if I try and monitor localhost I sometimes get 1 minute or greater waits when setting up my PerformanceCounter objects. If I instead use 127.0.0.1 it seems to help.
However, it still happens sometimes when monitoring remote machines. Will update if I find a solution, I believe there is an alternative library called PDH which I am about to look into.


text:
Q: How can I change svg icon color in BottomNavigationBar Flutter? I'm using SVG images in my BottomNavigationBar, but when I set selectedItemColor and unselectedItemColor doesn't work.
I'm trying using icons from Flutter framework and It's work.  The problem is with SVG images.
I can manage the state for item selected, but I want to know if there is a clean solution using SVG images in my BottomNavigationBar.
I'm using flutter_svg_provider packages for use SVG images in my app.
bottomNavigationBar: BottomNavigationBar(
    type: BottomNavigationBarType.fixed,
    backgroundColor: const Color.fromRGBO(
      27,
      58,
      44,
      1,
    ),
    items: <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Image(
          width: 30,
          height: 30,
          image: const Svg('assets/home.svg'),
          color: _selectedIndex == 0
              ? Colors.white
              : const Color.fromRGBO(
                  131,
                  247,
                  126,
                  1,
                ),
        ),
        label: 'Home',
      ),
      BottomNavigationBarItem(
        icon: Image(
          width: 30,
          height: 30,
          image: const Svg('assets/notifications.svg'),
          color: _selectedIndex == 1
              ? Colors.white
              : const Color.fromRGBO(
                  131,
                  247,
                  126,
                  1,
                ),
        ),
        label: 'Notifications',
      ),
    ],
    showSelectedLabels: false,
    showUnselectedLabels: false,
    currentIndex: _selectedIndex,
    unselectedItemColor: const Color.fromRGBO(
      131,
      247,
      126,
      1,
    ),
    selectedItemColor: Colors.white,
    onTap: _onItemTapped,
  ),


text:
Q: How install older OpenJDK 1.6 in Fedora 17? I want to install OpenJDK 1.6 in Fedora 17 however I only see OpenJDK 1.7 as an install option when I run yum search openjdk. How can I get OpenJDK 1.6 in Fedora 17?

A: You could use Openjdk 1.6 from Fedora 16. Use this command:
yum install java-1.6.0-openjdk --releasever=16 --nogpgcheck

(--nogpgcheck because yum complains of not having the key for Fedora 16, maybe there are better ways to solve this)
But this shows, that java-1.7.0-openjdk obsoletes java-1.6.0-openjdk and skips installation. And it shows that the package xorg-x11-fonts-Type1 is needed. So I did
yum install xorg-x11-fonts-Type1

and then I used the openjdk package which yum downloaded but refused to install because of the obsoletes warning
rpm --nodeps -ihv /var/cache/yum/x86_64/16/updates/packages/java-1.6.0-openjdk-1.6.0.0-68.1.11.5.fc16.x86_64.rpm

(--nodeps for overriding the obsoletes warning)
Now I have both java 1.6 and java 1.7 on my system. Java 1.7 is my default. And Java 1.6 is in /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java.
PS: There won't be any conflicts when you install both 1.7 and 1.6. The reason for removing 1.6 from Fedora 17 was, that OpenJDK6 will no longer get security updates after November 2012.

A: As scriptmonster stated, 1.6 rpm package is not supplied for fedora core 17. I had to download the rpm and install it that way.

A: For Fedora 26:
dnf install sudo dnf install xorg-x11-fonts-Type1
dnf --disablerepo=\* --enablerepo=updates --releasever=16  --nogpgcheck  install java-1.6.0-openjdk

and select jdk with command:
sudo /usr/sbin/alternatives --config java


text:
Q: C# Picturebox Image is null when I draw a shape in Paint event I drew a shape in Paint event of a Picturebox.
  private void pictureBox1_Paint(object sender, PaintEventArgs e)
  {
      e.Graphics.DrawEllipse(Pens.Black, 1, 1, 10, 10);
  }

And I tried to copy the image in Picture to Clipboard, but it failed because the pictureBox1.Image was null.
  private void copyToolStripMenuItem_Click(object sender, EventArgs e)
  {
      Clipboard.SetImage(pictureBox1.Image);
  }

The shape is drawn on screen but its Image property is empty.
How can I copy the content in a picturebox to Clipboard?


text:
Q: Buoyancy with Box2D on iPhone I was wondering if anyone can give me pointers on how to achieve the following using Box2D on the iphone:
1) I have a Box2D world with normal gravity of -9.8
2) The bottom half of the screen is a body of water
So when my sprite hits the body of water, I want him to react with buoyancy (similar to what's going on in this video: http://www.youtube.com/watch?v=0uX-1GXYIss)
Is the best way to achieve this to
1) simply calculate the y position of the main character sprite and then switch the gravity variable accordingly
or 2) is there a specific feature built into Box2D that will allow me to set my "water" sprite to behave as water in my world and "push" my main character sprite up (while still respecting the world gravity of 9.8)
Any info would be appreciated

A: The buoyant force is equal to the density of the fluid times the volume of the fluid displaced (which gives you the mass of the fluid displaced) times the acceleration due to gravity. The volume of fluid displaced can be costly to compute however. I would suggest making a simple estimate of the volume displaced based on the size of the object and how far it is submerged in the liquid.
Another very important force in fluid is the drag force. This is what makes it more difficult to move objects at high velocity through thick fluids. The drag force can easily be estimated by simply damping the velocity by some constant value: Force_drag = -b * v where b is your damping value and v is the object's velocity.


text:
Q: Fitting map bounds to raster layer I've ran across all fitbounds tutorials for Mapbox and still cannot figure out how refocus my map on a given raster layer. I have a menu that toggles a number of older maps and would like to refit the map at each turn.
Here's what I have so far. mapnumber is the string for my raster map.
      var coordinates = map.getBounds(mapnumber);
      var bounds = new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]);
      map.fitBounds({bounds});

The bounds are there, I just cannot use fitbounds on them. This is the error.
lng_lat.js:97 Uncaught Error: `LngLatLike` argument must be specified
as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array
of [<lng>, <lat>]

A:
Uncaught Error: LngLatLike argument must be specified
  as a LngLat instance

It looks like you're using mapboxgl.LngLatBounds incorrectly. You'll need to pass in two LngLat instances, rather than two coordinates. The API docs have an example that creates a point for the southwest and northeast corners of your bounding box:
var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
var llb = new mapboxgl.LngLatBounds(sw, ne);

Then you can use map.fitBounds() with the bounding box
map.fitBounds(llb);

UPDATE: answering follow up question

how can I extract the two sets (sw and ne) from the raster?

You can use the map.getSource() method. Pass in the source ID of your raster layer and that will return an object that has a bounds property. Use this bounds property to pass into map.fitBounds().
var bounds = map.getSource('mapbox://username.source-id').bounds;
map.fitBounds(bounds);

Here's a working example: https://codepen.io/mapsam/pen/RZvyBQ


text:
Q: How to fix XSS vulnerability to JavaScript I did a vulnerability analysis on the Veracode Platform and found an XSS vulnerability:
This is the code that has the vulnerability, I'm trying fix, but I need your help:
<po-widget>

      <kendo-treeview
        class="po-md-12 po-mt-1 po-mb-1"
        kendoTreeViewDragAndDrop
        kendoTreeViewDragAndDropEditing
        kendoTreeViewExpandable
        [expand by]="'id'"
        [(expandedKeys)]="expandedKeys"
        kendoTreeViewHierarchyBinding
        [childrenCampo]="'children'"
        [(nodes)]="treeviewItems"
        [textField]="'name'"
        kendoTreeViewSelectable
        [(selectedKeys)]="selectedKeys"
        (nodeDrop)="handleDrop($event)"
        (removeItem)="handleRemovedNode()"
        (selectionChange)="handleSelection($event)" // <==== XSS vulnerability here
        [selectBy]="'id'"
        [isSelected]="isItemSelected"
      >

The line (selectionChange)= "handleSelection($event)" is vulnerable by the Platform.
My suggestion to fix the vulnerability is:
(selectionChange)= XSSfix("handleSelection($event)")

 function XSSfix(inputXSS){

        return inputXSS.replace(/\&/g, '&').replace(/\</g, '<').replace(/\>/g, '>');
    }

What do you think? Is this solution correct? It's work to fix vulnerability?


text:
Q: Google webmaster tools HTML suggestions - duplicate meta descriptions When i look in my webmaster tools account i have hundreads of dupliacte meta descriptions. When i look at each one the duplicate urls's are like so:
/index.php?route=product/product&product_id=158?48efc520
/index.php?route=product/product&product_id=158?abc56c80

Where are these numbers coming from after my product id????
Thanks
Pjn

A: That means that the <meta name="description" content="..."> is the same for several pages.
Since you're not sure how the additional parameters are added to your URL, you could use the link tag to specify the canonical URL. This needs to be added to the head of each page.
<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish" />

For more information, have a look at http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.

A: Do you have a referral system or something in place? Those are querystrings, and without the name part of the usual name=value pair, they tend to look like those for referrals.
Is this in a system you build yourself, or are you using something?
Without more information about your setup, it will be tough to diagnose.

A: To resolve this, add code to 301 redirect Urls with extraneous parameters to the canonical Url.  For example, redirect /index.php?route=product/product&product_id=158?48efc520 to
/index.php?route=product/product&product_id=158
Assuming these extraneous parameters are indeed not being used.
Stackoverflow does this, see how this Url redirects:
Google webmaster tools HTML suggestions - duplicate meta descriptions

A: Hard to say where Google "learned" the names. You can some things in Webmaster Tools to avoid the reports.
One is the canonical like somebody mentioned. The other is in Webmaster Tools in Site Configuration/Settings. Click the Parameter Handling tab and enter your exceptions


text:
Q: Get arguments from commandline, then from file, then from default values I have a python program that runs depending on some parameters. Let's say, one of the parameters is C with a default value of 3. So when I run it without any arguments, it does
$ python parsing.py
C=3

When I load a file for my initial data, it can get some parameter values from that file. For example if my file MakeC5 says that the program should run with C=5, I will get
$ python parsing.py --file=MakeC5
C=5

On the other hand, if I specify a different value for C as optional argument, that value is taken, and has priority over the value in the file.
$ python parsing.py --C=4
C=4

$ python parsing.py --file=MakeC5 --C=4
C=4

Up to here, I can just check if the value specified on the command line is different from the default value and otherwise take the one from the file, as with
if parameters.C == parser.get_default('C'):
    parameters.C = load_file(parameters.file)["C"]

But this approach does not work if I give the default value for C on the command line as in
$ python parsing.py --file=MakeC5 --C=3
C=3

How do I get that case right? Is there a way that does not need to parse the command line twice as in
parameters = parser.parse_args()
parameters_from_file = load_file(parameters.file)
parser.set_defaults(**parameters_from_file)
parameters = parser.parse_args()

which does not look like "the obvious pythonic way to do this" to me? This is quasi reading a configuration file that can be specified as argument, so I expect there to be a good way.

A: Assuming you use the argparse module, simply don't set a default argument when you add the argument. Then the attribute will be None if the argument was not present, and you can check for that instead of parsing arguments twice:
parser.add_argument('--C'   , action='store', dest='C')
parser.add_argument('--file', action='store', dest='file')
# ...

args = parser.parse_args()
# ...

if args.C is None:
    # Argument `--C` not given on command line
    if args.file is not None:
        # Load the file, set `args.C` if the file contains the `C` option
        ...

if args.C is None:
    # `C` was neither specified on the command line argument given,
    # nor in the configuration file, set default value
    args.C = 3

print 'C =', args.C

A: Within argsparse there is fromfile-prefix-chars and it would seem to do some of what you wish if you can live with it's limitations.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', default="ABC")
args = parser.parse_args()
print '#1', args.foo

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', default="ABC")
args = parser.parse_args(['--foo', 'BAR' ])
print '#2', args.foo

import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('--foo', default="ABC")
args = parser.parse_args(['--foo', 'BAR', '@myargs' ])
print '#3', args.foo

import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('--foo', default="ABC")
args = parser.parse_args(['@myargs', '--foo', 'BAR' ])
print '#4', args.foo

myargs
--foo
FISH

Output
#1 ABC
#2 BAR
#3 FISH
#4 BAR

Notice how the position of @myargs on the command line affects the value of foo, when it's at the front it's valued if overriden by --foo  and vice versa.
This would seem to do what you want where:

default-value < config-file < cli-args

Although it relies on you remembering to put the config file in the right order, unless of course you take the args and reorder them so that they first in the args.
Hopefully food for thought.


text:
Q: indexing in elasticsearch using spark in standalone mode I want to index in elasticsearch from spark. It throws following exception...

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 1.0 failed 1 times, most recent failure: Lost task 0.0 in stage 1.0 (TID 1, localhost): java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(String.java:1967)
      at org.elasticsearch.hadoop.rest.RestClient.discoverNodes(RestClient.java:110)
      at org.elasticsearch.hadoop.rest.InitializationUtils.discoverNodesIfNeeded(InitializationUtils.java:58)
      at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:372)
      at org.elasticsearch.spark.rdd.EsRDDWriter.write(EsRDDWriter.scala:40)
      at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
      at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
      at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
      at org.apache.spark.scheduler.Task.run(Task.scala:88)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)
Driver stacktrace:
      at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1283)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1271)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1270)
      at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
      at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
      at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1270)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:697)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:697)
      at scala.Option.foreach(Option.scala:236)
      at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:697)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1496)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1458)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1447)
      at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
      at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:567)
      at org.apache.spark.SparkContext.runJob(SparkContext.scala:1822)
      at org.apache.spark.SparkContext.runJob(SparkContext.scala:1835)
      at org.apache.spark.SparkContext.runJob(SparkContext.scala:1912)
      at org.elasticsearch.spark.rdd.EsSpark$.saveToEs(EsSpark.scala:67)
      at org.elasticsearch.spark.rdd.EsSpark$.saveToEs(EsSpark.scala:52)
      at org.elasticsearch.spark.rdd.api.java.JavaEsSpark$.saveToEs(JavaEsSpark.scala:54)
      at org.elasticsearch.spark.rdd.api.java.JavaEsSpark.saveToEs(JavaEsSpark.scala)
      at com.tgt.search.metrics.es.bulk.Sparkimporter.main(Sparkimporter.java:88)
  Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(String.java:1967)
      at org.elasticsearch.hadoop.rest.RestClient.discoverNodes(RestClient.java:110)
      at org.elasticsearch.hadoop.rest.InitializationUtils.discoverNodesIfNeeded(InitializationUtils.java:58)
      at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:372)
      at org.elasticsearch.spark.rdd.EsRDDWriter.write(EsRDDWriter.scala:40)
      at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
      at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
      at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
      at org.apache.spark.scheduler.Task.run(Task.scala:88)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)

This is my code...
SparkConf conf = new SparkConf().setMaster("local")
            .setAppName("Indexer").set("spark.driver.maxResultSize", "2g");
    conf.set("es.index.auto.create", "true");
    conf.set("es.nodes", "localhost");
    conf.set("es.port", "9200");
    conf.set("es.write.operation", "index");
    JavaSparkContext sc = new JavaSparkContext(conf);
    Map<String, ?> numbers = ImmutableMap.of("one", 1, "two", 2);
    Map<String, ?> airports = ImmutableMap.of("OTP", "Otopeni", "SFO", "San Fran");

    JavaRDD<Map<String, ?>> javaRDD = jsc.parallelize(ImmutableList.of(doc1, doc2));
    JavaEsSpark.saveToEs(javaRDD, "spark/docs");

I tried to write the file in local which is working fine.... it might be a problem in configuration.
These are the dependencies in my pom.xml
<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>2.1.0</version>
    </dependency>
    <!-- <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId>
        <version>2.6.4</version> </dependency> -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.10</artifactId>
        <version>1.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch-spark_2.10</artifactId>
        <version>2.1.0</version>
    </dependency>

</dependencies>

A: The relevant lines in your stacktrace are:

java.lang.StringIndexOutOfBoundsException: String index out of range:
  -1 at java.lang.String.substring(String.java:1967) at ...

This error is not from your code. It is caused by the incompatibility between the elasticsearch version and the elasticsearch-hadoop adapter that you are using. The elasticsearch-hadoop adapters with versions 2.0.x and 2.1.x work with elasticsearch 1.x only. I faced the same error with elasticsearch 2.1.1, and had to downgrade my elasticsearch version to 1.4.4. And the error disappeared.
See the answer by costin here


text:
Q: tkinter not working in python 3(in linux) Error Message
import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: libtk8.6.so: cannot open shared object file: No such file or directory

from tkinter import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: libtk8.6.so: cannot open shared object file: No such file or directory

I have tried pip install tkinter but then this error comes up
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none)
ERROR: No matching distribution found for tkinter


text:
Q: How to redirect if login is successful? How to redirect from login page if login is successful? I'm using HTTPOnly Cookie for user authentication.
With the code below i'm able to redirect to home page if user logs in with their credentials. Nevertheless, if the user enters incorrect username or password, the page navigates to home page but user isn't logged in. How can I make page navigate only when credentials are correct and avoid navigating to home page if credentials are incorrect?
Login.jsx
function Login({ onUpdateUser }) {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });

  const navigate = useNavigate();

  function handleChange(e) {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  }

function handleSubmit(e) {
    e.preventDefault();
     fetch("http://localhost:3000/api/v1/login", {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    })
     .then((r) => {
        if (!r.ok) throw Error("Incorrect username or password!")
        .then(navigate('/login'))
      })
      .then((user) => onUpdateUser(user))
      .then(navigate('/'))
  }

A: if condition part in .then seems fishy.
I think it should be like
.then((r) => {
        if (!r.ok){
          throw Error("Incorrect username or password!")
        }else{
          // username and email are true and accepted so navigate to "/"
          navigate('/')
        }
      })
.then((user) => onUpdateUser(user))

A: your use of promise... then... doesn't seem right.
.then(navigate('/login'))

should be
.then(()=> navigate('/login'))

A: I think you can try this
.then(()=> navigate('Home'))

instead of
.then(navigate('/login'))


text:
Q: List preference showing selected value in summary This question has already been asked here it works like a charm. Application's minSdkVersion is 14, but now I have to provide support for sdkVersion 9 (Android 2.3.3 Gingerbread). The solution does not work for API Level 9. Documentation also recommends using '%s'. Is there any nice way of handling it in older/legacy version of android. Here is my ListPreference code.
<ListPreference
    android:defaultValue="option_1"
    android:dialogTitle="@string/options_dialog_title"
    android:entries="@array/option_entries"
    android:entryValues="@array/options_values"
    android:key="algo"
    android:title="@string/pref_title"
    android:summary="%s"/>

The output appears like this.

I am looking for something nice and easy. There exist a lengthy way of doing it by getting the preference.
Preference prefListOption = (Preference)findPreference("algo");

and calling setSummary function something like this
prefListOption.setSummary(value);//user selected value


text:
Q: Running a python program which uses concurrent.futures within a celery based web app I am working on a django application which uses celery for the distributed async processes. Now I have been tasked with integrating a process which was originally written with concurrent.futures in the code. So my question is, can this job with the concurrent futures processing work inside the celery task queue. Would it cause any problems ? If so what would be the best way to go forward. The concurrent process which was written earlier is resource intensive as it is able to avoid the GIL. Also, its very fast due to it. Not only that the process uses concurrent.futures.ProcessPoolExecutor and inside it another few (<5) concurrent.futures.ThreadPoolExecutor jobs.
So now the real question is should we extract all the core functions of the process and re-write them by breaking them as celery app tasks or just keep the original code and run it as one big piece of code within the celery queue.
As per the design of the system, a user of the system can submit several such celery tasks which would contain the concurrent futures code.
Any help will be appreciated.

A: Your library should work without modification. There's no harm in having threaded code running within Celery, unless you are mixing in gevent with non-gevent compatible code for example.
Reasons to break the code up would be for resource management (reduce memory/CPU overhead). With threading, the thing you want to monitor is CPU load. Once your concurrency causes enough load (e.g. threads doing CPU intensive work), the OS will start swapping between threads, and your processing gets slower, not faster.


text:
Q: Display of stacked column chart I'm rendering a stacked column chart. My "problem" is that the columns appear to be located one behind the other, instead of one on top of the other, add a "depth" to the column so to speak.
Is there a setting to get the column to appear in a "flat" manner, one on top of the other?
Thx..

A: You should set stacking parameter refer this link


text:
Q: SVG.js rotation animation does not work after move animation I use SVG.js. Here is my example:
var draw = SVG("svg");
var rect = draw.rect(100,100);

rect.animate(1000).move(100,100);
rect.animate(1000).rotate(50);

In second animation rectangular rotates around the initial center of the figure (50,50) but not around the new center after the first animation (150,150). Am I wrong in understanding these methods or is it a bug?


text:
Q: 3rd-libraries report errors during compile (using cocoaPods) After I updated my mac to MAC OS 10.13.4.
Some of pods that I installed using cocoaPods, now could not be compiled properly.
There are errors from these pods when I build my project.
for example:
one of the pods that i used(RaptureXML), keep giving me errors such as
semantic issues

*

*Unsupported: typedef changes linkage of anonymous type, but linkage was already computed

*Conflicting types for 'xmlTextReaderSetErrorHandler'

I'm sure that the there is nothing wrong with these pods, cocoaPods should be the root cause.
However, after searching online for solution whole day, I found  looks like the situation that I have.
I also tried remove and reinstall cocoaPods
But it doesn't work. These Pods still keep giving me errors.
So...is anyone have ideas? or should I reinstall my OS?

A: I can say that there is nothing fundamentally wrong with the OS version since it is working for me. Try a simpler project with different pods.
If that works, then the pods you are using may have some compatibility issues. If it doesn't, you may have to reinstall your Xcode and other developer components.


text:
Q: Distance between points in a sample follow normal distribution I am wondering if it is possible to create a data set of say p variables with m rows (mxp matrix) where the distance between any chosen point x (from the data set) to all other points in this data set follows a normal distribution.
Any help is greatly appreciated.


text:
Q: Swift NSURL giving error on valid urls Look at this code:
let url = NSURL(string: physicst.image as String)
        if let url = url {
            let request = NSMutableURLRequest(URL: url)
            let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                if let data = data {
                    cell.imageView?.image = UIImage(data: data)
                }
            })
            task.resume()
        }else {
            print ("nill URL \(physicst.image)")
        }

so I have a string, and that string is a url, and I want to load it.
that code is in a table view cells, so it is being called for each cell.
as you see, i am checking if the url is nil or not, and if not, i am making a print statement. almost all the urls are not nil, exception the following ones (which are complemetly valid)

http://commons.wikimedia.org/wiki/Special:FilePath/Kai_Manne_Börje_Siegbahn.jpg?width=300
http://commons.wikimedia.org/wiki/Special:FilePath/Виталий_Лазаревич_Гинзбург.jpg?width=300
http://commons.wikimedia.org/wiki/Special:FilePath/赤崎記念研究館.jpg?width=300
http://commons.wikimedia.org/wiki/Special:FilePath/Kai_Manne_Börje_Siegbahn.jpg?width=300
http://commons.wikimedia.org/wiki/Special:FilePath/赤崎記念研究館.jpg?width=300

The first thing you may argue is to encode the url, and that is what I did like this:
var image = oneBinding["p"]!!["value"] as! NSString
                        image = image.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

but then even the urls that were working, stopped working. what i am missing please ?
Update
Here is the whole code of my UITableViewController (it is easy)
class PhysicistTableViewController: UITableViewController {

    var physicsts : [Physicst]?

    @IBOutlet var physicstsTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        loadDataFromDBPedia()
    }

    func loadDataFromDBPedia()  {
        let session = NSURLSession.sharedSession()
        var url = "http://dbpedia.org/sparql/"
        let query = "http://dbpedia.org&query=select * {?o  dbo:thumbnail ?p . ?o dbo:award dbr:Nobel_Prize_in_Physics}"
        url = url + "?default-graph-uri=" + query.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
        url = url + "&format=JSON&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&debug=on"
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response ,error) in
            if let error = error {
                print ("\(error)")
            }
            if let response = response {
                let httpResponse = response as! NSHTTPURLResponse
                let statusCode = httpResponse.statusCode
                print("Status code = \(statusCode)")
            }
            if let data = data  {
                do {
                    let jsonResponse = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                    let binding = jsonResponse["results"]!!["bindings"] as! NSArray
                    for oneBinding in binding {
                        let name = oneBinding["o"]!!["value"] as! NSString
                        let image = oneBinding["p"]!!["value"] as! NSString
                        //image = image.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
                        let physicst = Physicst(image: image, name: name)
                        if self.physicsts == nil {
                            self.physicsts = [Physicst]()
                        }
                        self.physicsts!.append(physicst)
                    }
                    self.physicstsTableView.reloadData()
                }catch _ {
                    print ("not well json-formatted response")
                }
            }
        })
        task.resume()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.physicsts == nil {
            return 0
        }else {
            return self.physicsts!.count
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("physicstCell")! as UITableViewCell
        let row = indexPath.row
        let physicst = self.physicsts![row]
        cell.textLabel?.text = physicst.name as String
        if (physicst.imageData == nil) {
            let session = NSURLSession.sharedSession()
            let url = NSURL(string: physicst.image as String)
            if let url = url {
                let request = NSMutableURLRequest(URL: url)
                let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                    if let data = data {
                        let imageData = UIImage(data: data)
                        cell.imageView?.image = imageData
                        physicst.imageData = imageData
                        self.physicstsTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
                    }
                })
                task.resume()
            }else {
                print ("nill URL \(physicst.image)")
            }
        }else {
            cell.imageView?.image = physicst.imageData!
        }
        return cell
    }
}

A: The method you should use is
stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

Taken from the playground:
NSURL(string:"http://commons.wikimedia.org/wiki/Special:FilePath/Kai_Manne_Börje_Siegbahn.jpg?width=300".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)

Gives the result
http://commons.wikimedia.org/wiki/Special:FilePath/Kai_Manne_B%C3%B6rje_Siegbahn.jpg?width=300

Which is valid :)
Adapted to your code it gives:
let url = NSURL(string: (physicst.image as String).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()!)

Beware of the forced unwrapping tho !

A: URLHostAllowedCharacterSet only contains this "#%/<>?@\^{|}
And your URL string contains : .. So make custom set for this
 let yourString = "http://commons.wikimedia.org/wiki/Special:FilePath/Kai_Manne_Börje_Siegbahn.jpg?width=300"
 let customSet =  NSCharacterSet(charactersInString:"=\"#%/:<>?@\\^`{|}").invertedSet
 let finalString = yourString.stringByAddingPercentEncodingWithAllowedCharacters(customSet)

For more info. check this answer


text:
Q: Codeigniter Error when sending email to database records I am trying to send an email to multiple contacts in my database list from an input form, it works when i hard code a specific email address, but when i try to refer to my database, i get the error:
Message: mail(): SMTP server response: 503 5.0.0 Need RCPT (recipient)
Filename: libraries/Email.php
I also get another error, which i think may be just my email configuration in general and i am unsure of it to;
Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.
MY Controller:
public function sendmail() {
$this->load->library('email');
$this->load->model('Email_model');
$this->load->library('session');

$this->email->from($this->input->post('email'), $this->input->post('name'));

$sendTo['email'] = $this->Email_model->emailsend();

$this->email->to($sendTo);
$this->email->subject('Hello This is an email');

$this->email->message($this->input->post('message'));

if ($this->email->send()){
$this->session->set_flashdata('success','Email has been sent');
redirect('dashboard');
}else{

echo $this->email->print_debugger();

}

My Model
class Email_model extends CI_Model {

public function emailsend() {

  $query = $this->db->query("SELECT email from contacts");
  $sendTo=array();
  foreach ($query->result() as $row)
  {
      $sendTo['email']=$row->email;
  }

My View
<form action="<?php echo site_url('/Dashboard/sendmail');?>" method="post" accept-charset="utf-8">

<?php echo form_open('/Dashboard/sendmail');?>

  Your Name<input id="name" type="text" name="name">

  Your Email<input id="email" type="text" name="email">

  Your Message
  <textarea id="message" name="message" rows="8" cols="50"></textarea>

  <input id-"submit" type="submit" name="submit" value="submit">
<?php echo form_close(); ?>

<?php echo $flash;?>

Any help for either errpr will be massively appreciated

A: CodeIgniter's email module expects an array of email addresses in the to() function. Your model's emailsend() function adds an email index to that array that isn't expected. Also, you're overwriting that email index's value on every iteration of the foreach loop, meaning your array will only ever contain the last address from your database.
It also looks like your function doesn't actually return the array after filling it, but it could be that this part is simply truncated in your question.
public function emailsend() {

    $query = $this->db->query("SELECT email from contacts");
    $sendTo=array();
    foreach ($query->result() as $row)
    {
        $sendTo[] = $row->email;
        //     ^^ remove the 'email' index
    }

    return $sendTo; // <-- add this line if you don't have it
}

Then, from your controller, you don't need to store the result in a separate variable unless you want to perform some additional logic on it. You can simply do this:
$this->email->from($this->input->post('email'), $this->input->post('name'));
$this->email->to($this->Email_model->emailsend());
$this->email->subject('Hello This is an email');

A: public function emailsend() {
   $query = $this->db->query("SELECT email from contacts");
   $sendTo=array();
   foreach ($query->result() as $row)
   {
      //u are not changing the key
      $sendTo['email']=$row->email;
   }
   //iguess u are returning
   return $sendTo;

}
i mean a var dump on that array would be always one value, because u are reasigning the value always, then one email would be returned.
I suggest to build the array like this
foreach ($query->result() as $row)
   {

      $sendTo[]=$row->email;
   }

then the vardump will look like this
array(11) {
 [0]=>
 string(15) "email0@mail.com"
 [1]=>
 string(15) "email1@mail.com"
 [2]=>
 string(15) "email2@mail.com"
  [3]=>
  string(15) "email3@mail.com"
  [4]=>
  string(15) "email4@mail.com"
  [5]=>
  string(15) "email5@mail.com"
  [6]=>
  string(15) "email6@mail.com"
  [7]=>
  string(15) "email7@mail.com"
  [8]=>
  string(15) "email8@mail.com"
  [9]=>
  string(15) "email9@mail.com"
  [10]=>
  string(16) "email10@mail.com"
}


text:
Q: What is the most suitable language to make a copy-protected image web-interface I have my first professional assignment of making a website in which a photographer's artwork will be displayed for purchase or print. The protected image will likely be generated in Perl. But what I don't know is which language to implement such an application in. I know HTML, CSS and a bit of JavaScript and have a mainly free time for a period of 3-4 months in which to finish the project.
I am tossing up between learning JavaScript or ActionScript and Flash to do this project. Which would be most suitable taking into account the timeframe in which to learn the language?

A: The easiest thing to do is to educate the photographer to the fact that making their photos copy protected is never going to happen once they're on the web. Anyone can take a screen shot and copy them like that. If the photographer is still not convinced, use Flash to make a gallery. If you want another technique, look at how Flickr does it. They overlay "protected" images with a transparent image, so when you right-click to save, you only save that overlaid image.
The best thing to do is accept it, and only put up medium sized images. It's impossible to make a decent size print from these. Or to put a watermark on the image.

A: You cant make an image copy protected in terms of taking screenshots etc, however you can do the following:
1) Prevent right-clicks (which can be worked around)
2) Use watermarks
3) Use Low-res images
You will need to use a server side technology, the one you choose might depend on what type of infrastructure that hosts it.

A: You can't really copy-protect an image that appears online. If its online its possible to download it.
Pros of a javascript gallery:

*

*Minimal load times (don't have to wait for the flash component to download)

*can be SEO friendly if done properly

*visit stellaluca dot com/Great-Hair/ for a good example.

Cons of javascript:

*

*Even though you can can disable right-clicking in javascript, users can turn javascript off and right-click the images. To help deter this you can layer a transparent gif over the image.

*fading between images can be choppy in some browsers

Pros of flash:

*

*no right clicking

*smooth transitions between images when fading

Cons of flash:

*

*Longer loading times

*Very SEO unfreindly

*Requires the flash plugin

Ideally:

*

*You should layer a watermark on the images when uploading.

*Display images in the smallest resolution acceptable for the project.

*Disable right clicking on images (this should deter most image theft)

Additionally:

*

*You can provide a link for downloading the image directly. That way you can make sure you have a nice large and obvious water mark on the image and ensure that the downloaded image is not in a printable resolution.


text:
Q: How can I create a TextView for each element in a list in Android? I am trying to create a textview in Android for each element in a list. How can I dynamically generate a textview for each element in the list?
I have tried using a for loop to iterate through the list and create a new textview for each element, but I am having trouble implementing this. Any help would be greatly appreciated.

A: You will normally use a RecycleView for this, but in certain scenarios you will add list manually.
You can simply create the TextView and add the properties to it, it is important that you include the LayoutParams so that the view can be rendered.
        val food = listOf("apple", "pie", "banana", "cookie")
        val linearLayout = findViewById<LinearLayout>(R.id.myList)

        food.forEach {
            TextView(this).apply {
                layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
                text = it
                linearLayout.addView(this)
            }
        }

keep in mind that LayoutParams needs to be the nested class of the respective ViewGroup, so if the parent is a LinearLayout, you should use LinearLayout.LayoutParams
If it is not a TextView but a view that you defined in your own XML layout (res/layout/my_custom_row.xml) you can use binding for it:
MyCustomRowBinding.inflate(layoutInflater, containerLayout, true).apply {
     nameTextView.text = item.name
}

you don't need to use viewGroup.addView() because inflater already adds the view when last parameter is true.