Q: Splitting a Clojure namespace over multiple files Is it possible to split a Clojure namespace over multiple source files when doing ahead-of-time compilation with :gen-class? How do (:main true) and (defn- ...) come into play?

A: Overview
Certainly you can, in fact clojure.core namespace itself is split up this way and provides a good model which you can follow by looking in src/clj/clojure:
core.clj
core_deftype.clj
core_print.clj
core_proxy.clj
..etc..

All these files participate to build up the single clojure.core namespace.
Primary File
One of these is the primary file, named to match the namespace name so that it will be found when someone mentions it in a :use or :require.  In this case the main file is clojure/core.clj, and it starts with an ns form.  This is where you should put all your namespace configuration, regardless of which of your other files may need them.  This normally includes :gen-class as well, so something like:
(ns my.lib.of.excellence
  (:use [clojure.java.io :as io :only [reader]])
  (:gen-class :main true))

Then at appropriate places in your primary file (most commonly all at the end) use load to bring in your helper files.  In clojure.core it looks like this:
(load "core_proxy")
(load "core_print")
(load "genclass")
(load "core_deftype")
(load "core/protocols")
(load "gvec")

Note that you don't need the current directory as a prefix, nor do you need the .clj suffix.
Helper files
Each of the helper files should start by declaring which namespace they're helping, but should do so using the in-ns function.  So for the example namespace above, the helper files would all start with:
(in-ns 'my.lib.of.excellence)

That's all it takes.
gen-class
Because all these files are building a single namespace, each function you define can be in any of the primary or helper files.  This of course means you can define your gen-class functions in any file you'd like:
(defn -main [& args]
  ...)

Note that Clojure's normal order-of-definition rules still apply for all functions, so you need to make sure that whatever file defines a function is loaded before you try to use that function.
Private Vars
You also asked about the (defn- foo ...) form which defines a namespace-private function.  Functions defined like this as well as other :private vars are visible from within the namespace where they're defined, so the primary and all helper files will have access to private vars defined in any of the files loaded so far.


Q: How to access Entity Framework DbContext entities in Server-Side Blazor Components I'm new to .NET Core and Blazor, with mostly WebForms and MVC experience.
All the Blazor documentation and tutorials I've found use a separate API project and access data through HttpClient and Json serialization/deserialization. I see why this would be necessary for client-side Blazor using WebAssembly, but for Server-Side Blazor using SignalR what's the best way to access the database directly from the components' .razor files using an Entity Framework DbContext?
For example, in an MVC controller you can just do something like:
private ApplicationDbContext context = new ApplicationDbContext();

and then query the data by doing something like:
var things = context.Things.Where(t => t.ThingAttributes == something);

Is there an approach that is this clean and efficient when working with components in server-side Blazor?
Sorry for the broad nature of this question, feel free to point me to blogs, docs, or tutorials I should have already read. Thanks!

A: What you call a controller should be turned into a service class, that retrieves data from the database, and pass it to the calling methods. You should add this service to the DI container in the Startup class. To use this service in your components you should inject it like this:
@inject DataService myDataService

I think that the Blazor templates come with sample how to define such a service and use it in your components.
Here's a link to a sample by the Blazor team how to create a service and how to use it in your components. The service doesn't use Entity Framework, but this is something really minor I'm sure you'll cope with.


Q: How to pad strings inside curly braces with odd number of character with a single space? We have many \foo{something}. As the string inside the curly braces contains odd number of character, we want to add a space after the string. The result will be \foo{something }. We only want odd number of characters only. For example, in \foo{string} the string inside the curly braces has even number of character, then we do not add a space.
What I have tried:

*

*a dot means a character, two dots means two characters

*asterisk means repeat 0 or more times

*Then, [..]*. means 1, 3, 5 ... characters.

*Then, \foo{[..]*.} will be my matching sequence.

*Then, :%s/\foo{[..]*.}/\foo{[..]*. }/g will add the space we want.

But we failed.

A: This cmd should do:
:%s/\\foo{\zs[^}]\+\ze}/\=substitute(submatch(0), '$', len(submatch(0))%2?' ':'','g')/

A: :%s/\\\w\+{\([^}]\{2}\)*[^}]\zs\ze}/ /g

Explanation:
Find pairs of characters (\([^}]\{2}\)*) followed by another character ([^}]) in between a macro \\\w\+{...}. Then do a substitution adding an additional space.
Glory of details:

*

*\\\w\+{...} find macros of the pattern \foo{...}

*Look for character that does not match an ending curly brace, [^}]

*Look for pairs of non-}'s, \([^}]\{2}\)*

*Find an odd length string by finding pairs and then finding one more, \([^}]\{2}\)*[^}]

*Use \zs and \ze to set where the start and end of the match

*Use a space in the replacement portion of the substitution to add additional space and thereby making the string even in length

Fore more help see:
:h :s
:h :range
:h /\[]
:h /\(
:h /\zs
:h /\w
:h /star
:h /\+

A: This should work
:%s/\v[(\{(\w{2})*) ]@<!}/ }/g

break down:
%s           " run substitute on every line
\v           " very magic mode
[(\{(\w{2})*) ] " matches every `{` followed by an equal number of word
characters and space, since you don't want to add a space again everytime
you run it.
@<!}         " negative lookahead, matches all } not following the pattern before

Update
To solve the precise problem as you can read in the comments, the following command helps.
g/^\\foo/s/\v(\{([^}]{2})*)@<!}/ }/g

Changes:
 g/^\\foo/...    " only run it on lines starting with \foo
 [^}]            " it does now match all characters between { and } not only word
 characters.

Pitfalls: won't work correct with multiple braces on the line ( \foo{"hello{}"} and \foo{string} {here it would also match} f.e. will fail). if one of these is a problem. just tell me


Q: Catching errors at the end of a chain of promises I am using a factory to query data from Parse.com, this occurs many times in my ionic app and would like to apply a little more DRY to my code.
To call data I am using:
ParseFactory.provider('Clients', query).getAll().success(function(data) {
    $localStorage.Clients = data.results;
}).error(function(response) {
    errorFactory.checkError(response);
});

And often run many of these back to back to get data from different classes on the loading of a page.
Is it possible to use one error block at the end of all of these? like this:
ParseFactory.provider('Favourites', query).getAll().success(function(data) {
    $localStorage.Favourites = data.results;
})
ParseFactory.provider('Somethings/', query).getAll().success(function(data) {
    $localStorage.Programmes = data.results;
})
ParseFactory.provider('UserItems', query).getAll().success(function(data) {
    $localStorage.UserExercises = data.results;
})
ParseFactory.provider('Customers', query).getAll().success(function(data) {
    $localStorage.Clients = data.results;
}).error(function(response) {
    errorFactory.checkError(response);
});

A: You could create helper method:
function query(resource, query) {
  function querySucceeded(data) {
    $localStorage[resource] = data.results;
  }

  function queryFailed() {}

  ParseFactory.provider(resource,  query)
     .getAll()
     .success(querySucceeded)
     .error(queryFailed);
}

and, then just call:
query('Favourites', query);
query('Customers', query);

and so on.
Alternatively, you could factor queryFailed out, as such:
function query(resource, query) {
  function querySucceeded(data) {
    $localStorage[resource] = data.results;
  }

  return ParseFactory.provider(resource,  query)
     .getAll()
     .success(querySucceeded);
}

function queryFailed() {

}

$q.all([
    query('Favourites', query1),
    query('UserItems', query2)])
    .error(queryFailed);

A: $q.all takes an array (or object) of promises, and returns a single one.
The returned promise is resolved when all the original promises are resolved. It's rejected as soon as one of the original promises is rejected.
So, what you can simply do is something like
var request = function(path) {
    return ParseFactory.provider(path, query).getAll();
};

var promises = {
    favourites: request('Favourites'),
    programmes: request('Somethings/'),
    exercises: request('UserItems'),
    customers: request('Customers')
};
$q.all(promises).then(function(results) {
    $localStorage.Favourites = results.favourites.data.results;
    // ...
}).catch(function() {
    // ...
});


Q: Discord Bot will not login to server I will start this off by saying I'm a bit new to discord bot making. I'm just trying to get the bot online at this point and I keep getting the error:

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:544:13)
at new Client (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:73:10)
at Object. (C:\Users\levan\Desktop\Discordbot\main.js:3:16) ←[90m
at Module._compile (node:internal/modules/cjs/loader:1101:14)←[39m

←[90m

at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)←[39m

←[90m

at Module.load (node:internal/modules/cjs/loader:981:32)←[39m

`←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39`m

←[90m    at Function.executeUserEntryPoint [as runMain] ``(node:internal/modules/run_main:79:12)←[39m
←[90m    at node:internal/main/run_main_module:17:47←[39m {

  [←[32mSymbol(code)←[39m]: ←[32m'CLIENT_MISSING_INTENTS'←[39m

}

thus far this is what I have

const Discord = require('discord.js');

const client = new Discord.Client();

client.once('ready', () => {
console.log('Tec Control Bot is online!');
});

client.login('redacted sign in key');

A: So, you are using discord.js v13 which is a lot different from the previous version which is v12. In v13, it is compulsory to add intents.
You can read this for more information: here

A: new Discord version V13 requires you to set the intents your bot will use.
First, you can go to https://ziad87.net/intents/ where you can choose the intents you want and gives you a number, you should use that number like this:
const intents = new Discord.Intents(INTENTS NUMBER);
const client = new Discord.Client({ intents });

For example, if you want all the intents, you will have:
const intents = new Discord.Intents(32767);
const client = new Discord.Client({ intents });


Q: Re-read environment variables from VBScript I'm running a VBScript from a MSI installer (created using WiX toolset). This script checks using the PATH environment variable whether another software
is installed or not. The installer also offers a retry button which runs the script again.
Now the problem is this: If the PATH environment variable is changed while my installer is running, my script will not detect that change. My script only uses the new value of the PATH environmental variable after a re-start of the installer.
So the question is this: How can I force the installer process to update its copy of the environment variables using VBScript?
Edit:
It looks like this article explains how to solve the problem with PowerScript. But I need a solution for VBScript.

A: With WScript.CreateObject("WScript.Shell")
    .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _
        .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _
    ))
End With

This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables.
note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment).

A: Alternately, from jscript (still the cscript interpreter, but the jscript language)
// Re-read PATH vars in case they've changed
var shell = new ActiveXObject("WScript.shell");
var newPath = (shell.Environment("USER")("PATH") + ";" + shell.Environment("SYSTEM")("PATH")).replace(/;;/g, ";");
// Expand any %STRINGS% inside path and set to the new running process
shell.Environment("PROCESS")("PATH") = shell.ExpandEnvironmentStrings(newPath);

shell.Exec('myprocess.exe'); // throws exception if not found


Q: Determine number of row spans given a start index and a length I have a matrix start index of my data and the number of elements of my data
and I need to find the number of rows that the data span.
e.g. the matrix

 0              5
-------------------
|  |  |  |  |x |x |
-------------------
|x |x |x |x |x |x |
-------------------
|  |  |  |  |  |  |
-------------------
|  |  |  |  |  |  |
-------------------

My data is marked with x. I know the start index 4, the length of the data 8.
And I need to determine the number of rows this data spans, 2 in this case. (just doing length/6 is off by one in many cases, surely there have to be a simple formula for this..)

A: If you only know offset (i.e. index of the starting column), size (i.e. how many data), cols (i.e. maximum number of colums), and you want to calculate how many rows your data will span, you can do
int get_spanned_rows(int offset, int size, int cols) {
  int spanned_rows = (offset + size) / cols
  if ( ( (offset + size ) % cols) != 0 )
    spanned_rows++
  return spanned_rows
}

where % is the modulus (or reminder) operator

A: int calc_rows(int start,int length){
    int rows = 0;
    int x= 0;
    if (start != 0){
        x = 6%start;
        rows+=1;
    }
    if ((start+length) % 6 != 0){
        x +=(start+length) % 6;
        rows+=1;
    }
    rows+= (length - x)/6;
    return rows;
}

calculates number of rows by dividing by 6 but after subtracting partially filled rows count

A: In case you only want the number of rows you can calculate
num_rows = (offset + size + cols - 1) / cols

which in this case is
num_rows = (4 + 8 + 6 - 1) / 6 = 17 / 6 = 2


Q: Fortify- spring-boot-starter-actuator deserialization vulnerability with latest spring boot version I am facing Dynamic Code Evaluation: Unsafe Deserialization in fortify scan with latest spring boot version 2.2.4 Release. can you anyone help to resolve this issue?


Q: javascript syntax reader is wrong? i have this code , don't get me wrong it all work fine
var w = "window" ,
  gg = "gg" ,
  pr = "prototype" ,
  al = "alert" ,
  pi = "parseInt" ,
  st = String ,
  ts = "toString";

st[pr][gg] = function(){return window[this[ts]()];};
w = w[gg]();
w[al](w[pi]("0"));

the problem starts when i replace this piece of code
w = w[gg]();
w[al](w[pi]("0"));

with this one
w[gg]()[al](w[pi]("0"));

now it's not working.
i don't get it , it suppose to get the same result , what is wrong here?

A: There are two places that w is used:
w[al](w[pi]("0"));
^     ^

So you need to substitute in w[gg]() twice:
w[gg]()[al](w[gg]()[pi]("0"));
^^^^^^^     ^^^^^^^

Note also that this transformation might still not equivalent, for example if w[gg]() has side-effects or is non-deterministic.


Q: Mysql rollBack error from different database try{
   $SQL=$user_db->prepare("INSERT INTO user (...");
   $SQL->execute();
   $id=$user->lastInsertId('user');//Need this id for next query

   //connect to 2nd db
   //$SQL2=$message_db->prepare("UPDATE....");
}catch{...}

I have 2 queries from 2 different db
is any way to roll back the error & stop process if there is any error?
because its from 2 different db so I couldn't use transaction.
ps.1st db is innodb, but my 2nd db is mysqlISAM (not support transaction)


Q: Dynamic Route Matching -- how to bind an object key that contains a space? I am trying to use Vue Router dynamic route matching and have an object key of NAS ID with a space.
How would I bind that to the router path?
{
    path: '/:NAS ID',
    component: DataDetail
  }

The above path value gives me an error in console:
Expected "NAS" to be defined

A: Route matching is powered by https://github.com/pillarjs/path-to-regexp .  You can use their documentation to look for a similar case.
My first guess would be to try escaping the space: path: '/:NAS\ ID'


Q: Javascript: on click change button text color Hey I have the below javascript code with accompanying HTML.  I am trying to get each button when clicked to change the text color to blue and then when the next button is clicked it changes text of the previously clicked button back to green. basically only the most recently clicked button has blue text.  I have tried this code but with this it changes all button text to blue on the first button click.  Any help is appreciated.  Javascript, HTML, and CSS below.
function swapIphoneImage( tmpIPhoneImage ) {
    var el = document.getElementById('my-link');
    var el1 = document.getElementById('my-link1');
    var el2 = document.getElementById('my-link2');
    var el3 = document.getElementById('my-link3');
    var el4 = document.getElementById('my-link4');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;
    el.className = 'clicked-class';
    el1.className = 'clicked-class1';
    el2.className = 'clicked-class2';
    el3.className = 'clicked-class3';
    el4.className = 'clicked-class4';

}

html

HaPPPs Calendar

Weekend Events

Places & People

Customize Events

Interaction

css

a#my-link.clicked-class {
    color: #71a1ff !important;
}
a#my-link1.clicked-class1 {
    color: #71a1ff !important;
}
a#my-link2.clicked-class2 {
    color: #71a1ff !important;
}
a#my-link3.clicked-class3 {
    color: #71a1ff !important;
}
a#my-link4.clicked-class4 {
    color: #71a1ff !important;
}

Where am I failing?

A: Try using JavaScript to change the classes then you only need one class to determine which one is clicked.
Here is an example:
JS:
   $("UL.features LI A").click(function(){
      $("UL.features LI A").removeClass('clicked');
      $(this).addClass('clicked');
   });

CSS:
A.clicked {
    color:#71a1ff !important;
}

Here it is in jsfiddle:
 http://jsfiddle.net/57PBm/
EDIT: This solution uses JQuery which will I would definitely suggest using if you are not already

A: Rewrite JS code to:
function swapIphoneImage( elThis, tmpIPhoneImage ) {
    var el = document.getElementByClassName('clicked-class');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;

    el.className = '';
    elThis.className = 'clicked-class';
}

and each button to:

HaPPPs Calendar

You don't need to set up 5 CSS classes for the same thing.

A: You are changing every element to a clicked class. Just pass in a number to the function that identifies which button to color blue, then color that one blue and all the others green via JS.


Q: Mongo C# Driver - How to apply ToLower() to a DistinctAsyc I am retrieving a list of strings from MongoDB using DistinctAsync. The problem is that the results are distinct except that I get some values all in uppercase and some are in lower case which count as distinct of course.
How could I apply a .ToLower() to this query?
public async Task<List<string>> GetAllAuthorsUserNames()
{
    var filter = Builders<Episode>.Filter.Where(x => x.CreatedBy != null);

    var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy, filter);

    return cursor.ToList();
}

I have tried this but it doesn't work:
var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy.ToLower(), filter);

A: There are various approaches you can take to yield the result you want. Some are:

*

*Store the authors's names in lowercase only (or at least in a consistent manner such that you do not have to transform their names to yield distinct ones among them in the first place) and in that case a distinct query alone is enough to get you the desired result.

*After you fetch the distinct authors's names from the current data, map their names to their respective lowercase version in-memory and then apply another distinct function on it to get all authors's names in lowercase and distinct form. That will look like:
var filter = ...
var cursor = await GetCollection().DistinctAsync(v => v.CreatedBy, filter);
var list = await cursor.ToListAsync();

var names = list.Select(v => v.ToLower()).Distinct().ToList();

*Use aggregation. Basically, you can project all authors's names to their respective lowercase form (see: toLower) and then group all the projected lowercase names to a set (see: addToSet). That set will be your result which you can extract from the aggregated result.

My opinion is that you should consider altering your data so as to not add unnecessary computational complexity which takes up valuable resources. If that is not possible, but the names themselves are relatively few, you can use the second approach. Use the third approach with the understanding that it is not the ideal and it will add to more processing on the part of your DBMS.


Q: Add previous load count using the the present count and the timestamp column I have a table with the following columns
id, timestamp, current load count, previous load count

and it has many rows. I have values for all the first three columns, but for the "previous load count", I need to get the count of the date one day before the count of the current load count.
See the below image (table example) to view the sample table
For example: previous load count of id:4 is the count same as the current load count of id:5.
Is there anyway to write a SQL statement to update the previous load count?

A: Can you try this?
SELECT [id]
      ,[timestamp]
      ,[current load count]
      ,LAG([current load count]) OVER (ORDER BY [timestamp] ASC, [id]) AS [previous load count]
FROM [table]

The LAG function can be used to access data from a previous row in the same result set without the use of a self-join.
It is available after SQL Server 2012.
In the example I added ordering by id, too - in case you have records with same date, but you can remove it if you like.

A: If you need exactly one day before, consider a join:
select t.*, tprev.load_count as prev_load_count
from t left join
     t tprev
     on tprev.timestamp = dateadd(day, -1, t.timestamp);

(Note:  If the timestamp has a time component, you will need to convert to a date.)
lag() gives you the data from the previous row.  If you know you have no gaps, then these are equivalent.  However, if there are gaps, then this returns NULL on the days after the gap.  That appears to be what you are asking for.
You can incorporate either this or lag() into an update:
update t
    set prev_load_count = tprev.load_count
from t join
     t tprev
     on tprev.timestamp = dateadd(day, -1, t.timestamp);


Q: Qt. Is connection name valuable to connect to the MySQL server? Is connection name valuable to connect to the MySQL server?
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "conectionName");

A: No it is not, If you don't provide then a default name will be given but you can use that name to get that connection some where else.
QSqlDatabase db = QSqlDatabase::database("connectionName");

Here's what documentation says.

If connectionName is not specified, the new connection becomes the
  default connection for the application, and subsequent calls to
  database() without the connection name argument will return the
  default connection. If a connectionName is provided here, use
  database(connectionName) to retrieve the connection.

So if you don't provide any name, then whenever the below will return you that connection.
QSqlDatabase db = QSqlDatabase::database();


Q: How can we check whether empty partitions are present in Athena using lambda function code or query I am trying to fetch whether partition is added or not to Athena table using lambda function code. But when I use
Select * from "table $partitions" where batch date ='yyyymmdd'
It is showing error because in lambda function " is not taking.
But with out " my code is not working.
Can someone suggest anything on this


Q: Cyclomatic Complexity - Delphi API I am searching for a Cyclomatic Complexity Api in Delphi (2010). I need to create a program that will analize a source code and report the Cyclomatic Complexity of all methods in all classes (just like SourceMonitor does).
I cant use other softwares, I really need to build one.
Does anyone knows an API for delphi 2010 that does that?

A: You'll need a language parser from which you can generate a control flow graph. Then you need to calculate the CC using this formula.
I know of no library that will do this for you.
You may be able to use the free pascal source to generate the control flow graph (its a common technique used in compilers to eliminate unreachable code).
Unfortunately, Delphi hasn't shipped with a complete formal definition(bnf grammar) of the language in its documentation since Delphi 6 I believe. (even then it wasn't completely accurate) So all third party parsers are shooting in the dark.


Q: Need to redirect to 403 if / is not supplied by included conf I should say that i'm very new to Nginx so i'm sorry if this is a stupid question.
In my Nginx configuration I use includes to determine wether or not I export a webpage.
If export the web page I do I want the http://hostname/ to redirect to http://hostname/ui/.
If not I would like to return 403 error code.
The code in my included ui.conf contains this location block:
location = / {
  return 302 " /ui";
}

I want to define default behaviour when this is not included but when I add a location / in my regular nginx.conf I get an error saying I can't define the same location twice.
what should I do?

A: So what ended up working is using
location = / {
}

in my ui.conf file
and
location / {
}

In my main conf file.


Q: PF 11.0.0: which mojarra versions are supported? PF 11.0.0: which mojarra versions are supported?
It is not specified in pom.xml. The showcase used to show the mojarra version, but not now.

A: Based on documentation PrimeFaces 11 has dependency JSF with ver. 2.0, 2.1, 2.2, 2.3, 3.0, 4.0. Where JSF can be Apache MyFaces or Eclipse (former Oracle) Mojarra.


Q: Add multiple users to multiple groups from one import csv I have a csv with 2 columns, one column is AD group names and one is user account names. I am trying to read the csv and import the users into their corresponding group.
Here is what i have to so far. It's saying both arguments(identity,member) are null, which makes no sense since the headers are correctly specified.
import-module activedirectory
$list = import-csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv"

Foreach($user in $list){
    add-adgroupmember -identity $_.Group -member $_.Accountname
}

Heres whats in the csv file
Group             Accountname
group1            user1
group1            user2
group1            user3
group2            user4
group2            user5
group3            user6
group3            user7
group3            user8
group4            user9
group5            user10

EDIT Command and error
Here is my script, error i receive and csv.
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups.csv" |
ForEach { get-aduser $_.Accountname | add-adgroupmember $_.Group}

A: Change this:
add-adgroupmember -identity $_.Group -member $_.Accountname

To this:
add-adgroupmember -identity $user.Group -member (Get-ADUser $user.Accountname)

A: @EBGreen has answered what's wrong with your code. Just coming up with an alternative here. Instead of running the command once per member, you can try to add all members of a group at the same time. The Member parameter supports an array, so try this:
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser $_.Accountname }
    Add-ADGroupMember -Identity $_.Name -Member $users
}

EDIT I've sucessfully tested this on 2012 DC with following content in test.csv (values represent existing group name and existing samaccountname/username):
Group,Accountname
"Mytestgroup","kim_akers"
"Mytestgroup","user1"

EDIT2 It shouldn't have any problems with deeper level OUs. I tested with an OU that was 7 levels deep and it had no problem. If you have all the user inside one OU (or find the closest OU that contains all the sub-OUs), see if this script helps. Remember to replace DN for "base OU" in -Searchbase parameter.
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser -Searchbase "OU=mybaseou,OU=test,OU=users,OU=contoso,DC=Contoso,DC=com" -Filter { samaccountname -eq $_.Accountname } }
    Add-ADGroupMember -Identity $_.Name -Member $users
}


Q: Can't dissasemble function in Linux kdb I have kdb launched in my crashed Linux. And for some reason there is no id instruction in list of instructions (? command). So I can't disassemble any code.
But here is some cheat-sheet, where we can see the id command in common list.
So how could I disassemble any known function in Linux kernel with kdb?


Q: How to get a string variable in sql Postgresql Can someone help-me set up an SQL command that retrieves only the value of the first occurrence of "cost" in a string like the example below.
See below two results returned from a table where I store sql query execution plan. I use Postgres. The word cost always comes at the beginning, but it does not always come in the same position, so you can not simply do substring (...). I think you should find the initial and final position every time, to be able to extract only the cost value. If anyone can help me, the expected result for the example below is:
select (.... )
-----------------
cost=399301  (only this)

----------------------SAMPLE STRING SOURCE ------------------
Sort  (cost=399301.55..399301.57 rows=6 width=36)
  Sort Key: l_returnflag, l_linestatus
  ->  HashAggregate  (cost=399301.21..399301.48 rows=6 width=36)
        ->  Seq Scan on h_lineitem  (cost=0.00..250095.98 rows=5968209 width=36)
              Filter: (l_shipdate <= (to_date('1998/12/01'::text, 'YYYY/MM/DD'::text) - '10 days'::interval day))

-------------------- SECOND SAMPLE --------------------------------
Aggregate  (cost=7922058.70..7922058.71 rows=1 width=16)"
  ->  Hash Join  (cost=1899763.92..7922058.69 rows=1 width=16)"
        Hash Cond: (h_lineitem.l_partkey = h_part.p_partkey)"
        Join Filter: (((h_part.p_brand = 'Brand#13'::bpchar) AND (h_part.p_container = ANY ('{"SM CASE","SM BOX","SM PACK","SM PKG"}'::bpchar[])) AND (h_lineitem.l_quantity >= 4::double precision) AND (h_lineitem.l_quantity <= 14::double precision) AND (h_ (...)"
        ->  Seq Scan on h_lineitem  (cost=0.00..235156.84 rows=211094 width=32)"
              Filter: ((l_shipmode = ANY ('{AIR,"AIR REG"}'::bpchar[])) AND (l_shipinstruct = 'DELIVER IN PERSON'::bpchar))"
        ->  Hash  (cost=1183158.46..1183158.46 rows=35278997 width=33)
->  Seq Scan on h_part  (cost=0.00..1183158.46 rows=35278997 width=33) Filter: (p_size >= 1)"

Best Regards

A: Assuming the plans are stored in a table named plan_table in a column named execution_plan you can use the following:
select replace(substring(execution_plan from '\(cost=[0-9]+'), '(cost=', '')
from plan_table;

The substring(...) returns the first occurrence of (cost= and the replace is then used to remove that prefix.

A: I get successful and the solution, the obcjetive was get the value 27726324.41, the Expression Regular final developted is:
select substring('Aggregate (cost=27726324.40..27726324.41 Rows' from '[.]Y*([0-9]+.?[0-9]{2})')

RESULT 27726324.41
Thanks a_horse_with_no_name and anothers that help-me.


Q: maven assembly dir with a jar dependency from project I am trying to use maven to assemble a directory for a install package.  The install package requires several things: configuration files, dependency libraries and an executable jar of my class files.  I am having trouble figuring out how to add the executable jar.
Here is what I have so far:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myproject</groupId>
  <artifactId>myproject</artifactId>
  <version>8.1.1</version>
  <name>my project</name>
  <packaging>pom</packaging>
  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-2</version>
            <configuration>
                <descriptor>${basedir}/src/main/assembly/client.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <id>create-client</id>
                    <configuration>
                        <descriptor>${basedir}/src/main/assembly/client.xml</descriptor>
                    </configuration>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>

  <dependencies>
      .
      .
      .
  </dependencies>
</project>

Then my assembly descriptor looks like this:
<assembly>
  <id>client</id>
  <formats>
    <format>dir</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>

  <fileSets>
    <fileSet>
        <directory>${basedir}/src/main/reports</directory>
        <outputDirectory>/reports</outputDirectory>
    </fileSet>
    <fileSet>
        <directory>${basedir}/src/main/resources/audio</directory>
        <outputDirectory>/audio</outputDirectory>
    </fileSet>
    <fileSet>
        <directory>${basedir}/src/main/client</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
  </fileSets>
  <dependencySets>
    <dependencySet>
        <scope>runtime</scope>
        <useProjectArtifact>false</useProjectArtifact>
        <outputDirectory>lib</outputDirectory>
        <unpack>false</unpack>
    </dependencySet>
  </dependencySets>
</assembly>

If i call mvn assembly:assembly I get a directory with all the libraries and configuration files.   Works great.
But now I want to add an executable jar of all my compiled code.  I can create this jar alone by adding this to my pom and calling mvn jar:jar
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <finalName>run</finalName>
                <archive>
                    <manifest>
                        <mainClass>com.myproject.main.StartProcess</mainClass>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

The question is, how can I get that jar into my assembly automatically?
I have tried a couple things but I have no idea where to start.  Can I somehow call the jar execution from my assembly?
Any help appreciated.

A: I think you should turn your useProjectArtifact to true (this is the default value).
It determines whether the artifact produced during the current project's build should be included in this dependency set.


Q: Why Index object is not shared across different pandas objects that are reindexed with it? As per pandas docs, Index objects can be shared between different series and dataframes.
So let's say I have the following:
df = pd.DataFrame(np.random.randn(5, 2), index=list("abcde"), columns=["x", "y"])

s = pd.Series(np.random.randn(5), index=list("abcde"))

It's also clearly stated that passing an Index object directly to reindex() is preferable to passing an array-like object, since it avoids duplicating data.
So I'm assuming that:
rs = s.reindex(df.index)

would use the same Index object for s as for df. However:
rs.index is df.index

is False, and I cannot understand why. Am I missing or misunderstanding something, or I'm reading an outdated section in docs?


Q: Create large amount of user accounts in OS X Lion Server's Server App/Server Admin/Workgroup Manager I'm trying to managing iOS devices by OS X Lion Server on Mac Mini.
Now I need to create more than 100 user accounts in Server App. If there's any way to do this without creating each account one by one? Writing script?
http://manuals.info.apple.com/en_US/UserMgmt_v10.6.pdf
According to this document, the exported file of accounts is a XML file. But I find no where to create or edit this file in a efficient way.

A: If you are using Open Directory (which you probably should with that amount of users) one option is to use dscl which is probably a little easier to automate. There's a thread at Apple Discussions describing how to add users to a group.

A: Workgroup Manager (part of the Server Admin Tools package) can import tab-delimited text files with a little work.  When you do the import, you'll need to tell it the file's format -- what the record and field delimiters are (generally newline and tab), then what data each field contains.  See this video for an example of the process.
If you need to set attributes that aren't in the file, you can either select all of the imported accounts and set the attribute for all of them at once (the video shows doing this for the home directory location), or (if you think of it before doing the import) create a template account with the relevant settings, save it as a preset (there's a pop-up menu at the bottom of WGM's window), then select that preset in the import dialog box.

A: Try using Passenger http://macinmind.com/?area=app&app=passenger&pg=info
If you have more than 20 users you might want to buy it for $60 or do what I do and group them by 20 users and run it 5 times.


Q: How to delete published branch without creating pull request on github console Is there any way to delete the published branch without creating a pull request and merging it into the default branch on the GitHub console.
One way I know is to create a pull request and then close it, then I am able to delete that branch.
Edit :-
I could not find exisiting question on SO with below conditions -

*

*How to delete branch without raising pull request.

*How to do it on GitHub website.

Thanks.

A: Just found a solution for this.
Click on the branches tab shown below -

Delete your published banch from the list -


Q: cant able to print first 20 even and odd numbers in assemble language I am using procedures for printing even and odd numbers but it is not working
what is wrong with my code? since I am new to assembly language
This is my main funtion:
.data
S BYTE ?
.code
main proc
call ven
MOV AH,4ch
INT 21h
main endp

this is my procedure:
ven proc
MOV S,0  \\ S is a variable
L1:
JE ter
MOV AX,S
MOV bl,2
DIV bl
CMP AH,0
JE EVE
JNE ODD
EVE:
MOV AH,2
MOV DL,AL
INT 21h
jmp L1
ODD:
MOV AH,2
MOV DL,AL
INT 21h
jmp L1
ter:
RET
ven ENDP
END MAIN

is there is something with my ven procedure aur I am linking it with main with a wrong manner.

A: there are some little errors in you code, I fixed them and pointed them with arrows (◄■■■) :
.stack 100h       ;◄■■■ PROCEDURES REQUIERE STACK.
.data
S dw ?            ;◄■■■ DW, NOT BYTE, BECAUSE AX IS TYPE DW.
.code
main proc
call ven
;call outdec
MOV AH,4ch
INT 21h
main endp

ven proc
MOV S,0
L1:
INC S             ;◄■■■ S+1
CMP S,20          ;◄■■■ IF S > 20...
JA ter            ;◄■■■ ...JUMP TO TER.
MOV AX,S
MOV bl,2
DIV bl
CMP AH,0
JE EVE
JNE ODD
EVE:
MOV AH,2
MOV DL,AL         ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h           ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ODD:
MOV AH,2
MOV DL,AL         ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h           ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ter:
RET
ven ENDP
END MAIN


Q: Android google maps API 2 got JSONException:org.json.JSONException: Index 0 out of range [0..0) at org.json.JSONArray.get(JSONArray.java:263) I am drawing route between 18 locations to draw the google map v2.When i start fetching routes it draws route but some times it is not drawing route and it gives JSONException :org.json.JSONException: Index 0 out of range [0..0)  at org.json.JSONArray.get(JSONArray.java:263)
and also it gives "error_message" : "You have exceeded your daily request quota for this API."
"routes" : []
"status" : "OVER_QUERY_LIMIT"
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        Log.d("JSON_RUTA", json);
        return json;

    }
}

private String makeURL(double sourcelat, double sourcelog, double destlat,
        double destlog, String mode)
{
    StringBuilder urlString = new StringBuilder();

    if (mode == null)
        mode = "driving";

    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=false&mode=" + mode + "&units=metric");
    return urlString.toString();
}

private List<LatLng> decodePoly(String encoded)
{

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len)
    {
        int b, shift = 0, result = 0;
        do
        {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do
        {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

try
    {
        // Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        encodedString = overviewPolylines.getString("points");

               List<LatLng> list = decodePoly(encodedString);
    } catch (JSONException e)
    {
        e.printStackTrace();
    }

for (int z = 0; z < list.size() - 1; z++)
{
 LatLng src = list.get(z);
 LatLng dest = list.get(z + 1);

 Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
 new LatLng(dest.latitude, dest.longitude)).width(4)
.color(Color.BLUE).geodesic(true));
 line.isVisible();
 }

Can any one suggest me what ll be the solutions for this?
Thanks in advance.

A: I faced the same problem before, and it was not because of Json. It was because of sending too much requests to google in a period. So I just slow down the frequency of sending post to Google, and never seen this message again.

A: what @ohyes means is that you send multiple (too much) requests to google using your API key in too short of a time (for example, over 100 in a minute - just an example).
for that you are receiving the OVER_QUERY_LIMIT and the empty JSON array
while you should consider changing the time between the requests, you should also verify that the array received in fact has any elements
try
{
    // Tranform the string into a json object
    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray("routes");
    if(routeArray.size() > 0) {
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        encodedString = overviewPolylines.getString("points");

        List<LatLng> list = decodePoly(encodedString);
    }
} catch (JSONException e)
{
    e.printStackTrace();
}

That would solve the exception being thrown, but it won't solve the fact that you are getting no result, probably because of the too much requests
EDIT:
The OVER_QUERY_LIMIT thing happens (probably) because of too fast calls to getJSONFromUrl() function. Please add the code that makes these calls so we could try and be more helpful on that.
Probably 500 ms delay is not enough (I'm assuming you're doing this on a background thread and not Sleeping the UI thread as this is a bad habbit). try increasing the delay to something very high, such as a minute (60000 ms) and see if this helps. If it does, lower that number to the lowest one that works.
And add the code please.


Q: WPF UI to Screenshots I have a WPF application which has a toolbox with items same as Visual Studio. These items can be dragged on to the gird and configured. Each item has its own configuration i.e., different textboxes, dropdowns etc. Similar to Visio user will connects items if required (two or more). We call this as a Playlist (collections of items with different configurations).
I have a requirement to present the configuration of a playlist in a report.  The customer will be using this playlist report to recreate the playlist.
All configurations are saved in XML. I am able to deserialise the XML and show it in the report but ideally the customer would like screenshots of each item in the report or some other format.
How can i achieve it? Sorry if it is a very wide question.
Thanks in advance.


Q: Unknown register name "r0" in asm I'm in the process of converting an iOS 32-bit app to a 64-bit binary. I was able to build and test the app fine on the simulator and device however when I build for distribution to the App Store I get an error:
Unknown register name "r0" in asm

The debugger points to this line:
    VFP_VECTOR_LENGTH_ZERO
                          : "=r" (result), "=r" (m2)
                          : "r" (m1), "0" (result), "1" (m2)
                          : "r0", "cc", "memory", VFP_CLOBBER_S0_S31
                          );

I saw a similar post here however i'm unsure what the solution is.
Any assistance would be much appreciated.


Q: How to copy multiple element values from XML value into a table? I have following script, and I want to fill AddOnFeatureEnum values in #rewardscusts table :
    DECLARE @AddOnFeatures AS VARCHAR(1500)

    DECLARE @AddOnFeaturesXML AS XML

   SET @AddOnFeatures =
    '<p1:Addons
xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>'

SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML)

SELECT @AddOnFeaturesXML

CREATE TABLE #rewardscusts (AddOnFeature VARCHAR(100) primary key)

-- I want to fill AddOnFeatureEnum values in #rewardscusts table please

DROP TABLE #rewardscusts

A: This is one possible way by shredding the XML on p1:AddOnFeatureEnum elements (reference nodes() method for this part), then use value() method on the shredded elements to extract the varchar(100) values :
;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO #rewardscusts
SELECT enum.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(enum)

This is full working demo codes :
DECLARE @AddOnFeatures AS VARCHAR(1500)
DECLARE @AddOnFeaturesXML AS XML

SET @AddOnFeatures =
'<p1:Addons
xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>'

SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML)

DECLARE @rewardscusts TABLE(AddOnFeature VARCHAR(100) primary key)

;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO @rewardscusts
SELECT x.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(x)

SELECT * FROM @rewardscusts

output :
|      AddOnFeature |
|-------------------|
| EnterpriseNotices |
|    WeatherToPanel |


Q: List emailAddress how to replace value in a particular string I have the following method
/// <summary>
    /// Replaces SemiColons with commas because SMTP client does not accept semi colons
    /// </summary>
    /// <param name="emailAddresses"></param>
    public static List<string> ReplaceSemiColon(List<string> emailAddresses) // Note only one string in the list...
    {
        foreach (string email in emailAddresses)
        {
            email.Replace(";", ",");
        }

        //emailAddresses.Select(x => x.Replace(";", ","));  // Not working either

        return emailAddresses;
    }

However the email string is not replacing the ";" with the ",".   What am I missing?

A: I think you should try setting it back to itself email = email.Replace(";", ",");

A: String.Replace method returns new string. It doesn't change existing one.

Returns a new string in which all occurrences of a specified Unicode
  character or String in the current string are replaced with another
  specified Unicode character or String.

As Habib mentioned, using foreach with the current list gets a foreach iteration variable error. It is a read-only iteration. Create a new list and then add replaced values to it instead.
Also you can use for loop for modifying existing list which keyboardP explained on his answer.
List<string> newemailAddresses = new List<string>();
foreach (string email in emailAddresses)
{
     newemailAddresses.Add(email.Replace(";", ","));
}
return newemailAddresses;

Be aware since strings are immutable types, you can't change them. Even if you think you change them, you actually create new strings object.

A: As others have already mentioned that strings are immutable (string.Replace would return a new string, it will not modify the existing one) and you can't modify the list inside a foreach loop. You can either use a for loop to modify an existing list or use LINQ to create a new list and assign it back to existing one. Like:
emailAddresses = emailAddresses.Select(r => r.Replace(";", ",")).ToList();

Remember to include using System.Linq;

A: Strings are immutable so another string is returned. Try
for(int i = 0; i < emailAddress.Count; i++)
{
   emailAddress[i] = emailAddress[i].Replace(";", ",");
}

A foreach loop would not compile here because you're trying to change the iteration variable. You'd run into this issue.

A: You should use somthing like:
var tmpList = new List();
add each modified email address to the tmplist
and when you are done, return the TmpList.
In .NET strings are inmutable, that's why your code doesnt work.


Q: how can i avoid asking username and password for facebook in my UIWebView? in my app i need a facebook like button. when user will click that button it ll like a facebook group. i used a UIWebView and used iframe in that. now i have a local html document which is loaded when user click on the webView. but when i click on the webView it asks for facebook user name and password. i also have a publish button which uses facebook api. once its loged in it doesn't ask username and password again. but webView asks always. how can i get auto login in webView?

A: This may help you http://forum.developers.facebook.net/viewtopic.php?id=37430


Q: Rails / Dalli: expire fragment from another namespace I have two apps connecting to memcached servers on different namespaces, for example's sake we'll call them "admin" and "users".
Every now and then I want to expire some fragments in the "users" namespace from the admin application.
Note: I am not caching/expiring actions as per the other several questions/answers I found here. I want to expire keys such as "abcde". I cache all sorts of things, AR results, JSON, and so on.
Already tried things like:
Rails.cache.delete("abcd")
Rails.cache.delete("users/abcd")
Rails.cache.delete("/users/abcd")

Digests are off.
How do I do this?

A: If your rails cache is configured with a namespace, that namespace will be prepended to the cache key automatically. So, when you Rails.cache.write("FOO", "BAR") the key will actually be $NAMESPACE:FOO. Keys are just strings and can't be navigated like a file system or anything fancy (AFAIK).
I think your best option is instantiate a separate instance of a dalli client for your alternative namespace to delete the key.


Q: how to get aggs count/buctuks from Flux I'm trying the Elasticsearch aggregations in spring webflux.
I what to know how to get the buckets values (inside buckets count) from  Flux<AggregationContainer<?>> in Java API and total records in elasticsearch.
Request:
order/_search
{
  "size": 0,
          "aggs": {  "status":
 { "terms":
 { "field":"order_status" , "size": 100}}}}

Response:
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    .....
  },
  "aggregations" : {
    "status" : {

      "buckets" : [
        {
          "key" : "CREATED",
          "doc_count" : 34
        },
        .....
        {
          "key" : "CANCELLED",
          "doc_count" : 2
        },
        {
          "key" : "COMPLETED",
          "doc_count" : 1
        }
      ]
    }
  }
}

Java imp:
  @Autowired
    private ReactiveElasticsearchOperations operations;
Flux<AggregationContainer<?>> result = operations.aggregate(searchQuery, Count.class, "indexs");


Q: Passing data from one screen to another screen in iPhone using phone gap I have just started to look into the phone gap.I have created one basic form which taking the data of the employee.I have table view in another screen .I want to pass the employee details to the second screen .I was googling for this purpose.I have found that there are some ways to do this like:
  1.Server side post back

  2. Client side URL examination

  3.What's in a window.name = local cross-page session

  4.HTML5 local storage

  5. Cookies

But will my phone gap application be 100% native by using these ways? Is there any alternate way or tutorial to pass the data between the screens?

A: What you actually mean by "a screen"? If you're talking about a pop-up dialog box or page by jQuery Mobile you can probably serialize the form with jQuery and assign it to a JavaSCript variable.
But if you're changing your "screen" by changing UIView to a different url you can use either:

*

*File API to store serialized form in a file and load it on the 2nd "screen"

*Storage API to ... actually do the same

I'd go for number one, as it's easier to implement than using SQL and writing loads of additional code.
Search for:

*

*jQuery.serialize()

*PhoneGap File API


Q: How to validate forms when a user changes the name of an input element in firebug? I realize it's impossible to prevent someone from changing the names of input elements in firebug.
How should I approach this problem?  A user changes the name of the input element "firstname" to "month" and visa versa.
<form action="example.php" method="post" enctype="multipart/form-data">

                First name: <input type="text" name="firstname" />

                Last name: <input type="text" name="lastname" />

            Birth Month:
                <select name="month">
                    <option value="01">January</option>
                    <option value="02">February</option>
                    <option value="03">March</option>
                    <option value="04">April</option>
                    <option value="05">May</option>
                    <option value="06">June</option>
                    <option value="07">July</option>
                    <option value="08">August</option>
                    <option value="09">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>

            <input type="submit" name="Submit" value="Sign Up!" />

</form>

My best idea so far is:
<?php
$month= $_POST['month'];
if($month!= 01 || $month!= 02 ... $month!= 12)
    echo 'wrong month';
?>

However this won't be clean for the year of birth... Facebook does a great job of preventing this when you sign up but I wasn't able to figure out what they did.  A non-javascript solution would be much appreciated.
EDIT: Lawrence, what do you recommend for a location form?

A: Going through each month in a condition is unneeded, php has functions for that.
<?php
$firstname= (string)$_POST['firstname'];
$lastname = (string)$_POST['lastname'];
$month    = $_POST['month'];

if(in_array($month,range(01,12))===true){
    $cont = TRUE;
}else{
    $cont = FALSE;
}
//If set, not empty, not swapped for month & greater or equals to 6 chars
if(isset($firstname) && $firstname!="" && strlen($firstname) >=6 && in_array($month,range(01,12))===false){
    $cont = TRUE;
}
//If set, not empty, not swapped for month & greater or equals to 6 chars
if(isset($lastname) && $lastname!="" && strlen($lastname) >=6 && in_array($month,range(01,12))===false){
    $cont = TRUE;
}
?>


Q: Windows OpenFileDialog with more than one file type I want to open a Windows OpenFileDialog with two possible selections:
foo*bar.xml
*.xml

The file name wildcard is specified with the FileName property but it applies to every file selection specified with the Filter property.
With the Filter property, users can select more than one set of file types, but is there a way to specify different file names in one dialog?
Paul

A:
The file name wildcard is specified with the FileName property

That doesn't work, only the Filter property can be used to filter files.  Furthermore, a wildcard like foo*bar.xml does do what you hope it does, anything past the * is ignored.  A wildcard doesn't behave like a regular expression at all.  This goes way, way back to early operating systems that didn't have the horsepower to implement regex.  Definitely at CP/M, probably as far back as RSX.
Options are very limited, you can specify multiple wildcards by separating them with a ; semicolon.  Like "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*".  But that's as far as you can push it.


Q: WSO2 Enterprise Integrator (6.5) - how to Store and retrieve Registry data using dynamic registry path I have a sequence to utilise an API which issues time-constrained bearer tokens from an authorization endpoint based on client ID and Secret. The Bearer Token remains valid for 1 hour and so I'm storing the bearer token and its expiry time in the registry whenever I renew the token and on subsequent calls will use the stored token rather than request a new one - unless it's expired.
This is all working as expected - however - it is feasible that this Sequence could be called from processes that have different client IDs - so for scalability I would like to modify the process so the Token and expiry are held under a registry branch for each client_id.
I'm unable to find a way to dynamically create the registry entries to incorporate the client_id in the registry path.
I can Read from a dynamic path successfully as follows:
<property expression="get-property('registry', fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" name="RegBearerExpiryStr" scope="default" type="STRING"/>
but I cannot work out how to successfully Write a registry entry in a similar fashion.
I have tried the following with no success - I can see from the wire logs that everything in the key name is being interpreted literally :
 <property expression="json-eval($.access_token)" name="fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" scope="registry" type="STRING"/>
and
 <property expression="json-eval($.access_token)" name="conf:/resource/MyApplication/{$ctx:client_id}/TokenExpiry" scope="registry" type="STRING"/>
I'm running EI 6.4 and 6.5
Any brilliant ideas - there must surely be a way to create a dynamic path for writing as well as reading ?

A: I personally use jsonObject XML and use OM type for storing complex types as WSO2 has better xml type support.
<property expression="//jsonObject" name="token" scope="default" type="OM"/>
<property name="conf:/storage/SampleToken.xml" scope="registry" expression="$ctx:token" type="OM"/>

But, there is one "pitfall", as WSO2 are cacheing the registry entries for default 15seconds. So you will read old values for some time. If that is a problem i use workaround. I use script mediator for better handling that, and with checking if that resource exist or not. I tested it on EI 6.5
<script language="js"><![CDATA[
 var regUrl = mc.getProperty('regUrl');
 var registry = mc.getConfiguration().getRegistry();

 if(registry.isResourceExists(regUrl) == false) {
    registry.newResource(regUrl, false);
 }
 registry.updateResource(regUrl,mc.getProperty('token'));

 var regEntry = registry.getRegistryEntry(regUrl);
 regEntry.setCachableDuration(0);
 registry.updateRegistryEntry(regEntry);]]>
</script>

I also made some blog post, may be also useful::
Reading, modifying and writing data in WSO2 Enterprise Integrator registry on an example


Q: excel how to use index and match to match the data Morning,
My fault, let me converted to English.

My concern is that I do not know how to connect table_1's category with the table_2's column and then found the correct color

A: You need to use either the VLOOKUP or HLOOKUP feature when structuring your results table.  For instance in cell C3 (color for head/set1) you would type =HLOOKUP(a2,e2:h5,2,FALSE). It will look horizontally in the first row for whatever is in cell A2 (HEAD)  and return the value from the 2nd row (RED).  Of flip it around to use HLOOKUP.
https://support.office.com/en-us/article/hlookup-function-a3034eec-b719-4ba3-bb65-e1ad662ed95f

A: Please try this formula, to be entered in row 3 where columns A and B are "category" and "Sets" respectively.
=VLOOKUP(B3,E1:H4,MATCH(A3,E1:H1,0),FALSE)
E1:H4 represents your entire table2 incl captions. You can exclude the caption row - probably better. E1:H4 is the first row of that same range. There is presumed to be only one caption row which is needed, and must be 1 only. If you prefer a neater solution take the data column captions only and adjust the result. Then your formula might look like this.
=VLOOKUP(B2,E2:H4,MATCH(A2,F1:H1,0)+1,FALSE)


Q: Squarespace Code Block Alignment Issues We have custom coded animate flipping cards on our website. There is an issue with the alignment and sizing of them. The issue only occurs when there are multiple cards on the page (they are made using code blocks). You can see the issue on the link below.
Any help would be appreciated!
LINK TO SITE
JSFIDDLE (ONLY 1 CARD...ISSUE DOESN'T SHOW UP)
HTML:

Brian Perry

CEO

CSS:
.back {
    -webkit-transform: rotateY(180deg);
    -moz-transform: rotateY(180deg);
  -o-transform: rotateY(180deg);
    transform: rotateY(180deg);

    background: #bd2d2c;
}

.flip-container {
  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -o-perspective: 1000;
  perspective: 1000;

}

.flip-container:hover .flipper,
  .flip-container.hover .flipper {
        -webkit-transform: rotateY(180deg);
        -moz-transform: rotateY(180deg);
    -o-transform: rotateY(180deg);
        transform: rotateY(180deg);
    }

.flip-container, .front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back {
  width:6000px;
  min-height:100%;
  max-width:100%;
  max-height: 10000px;
   height:0;
   padding-bottom: 70%;

}

.flipper {
    -webkit-transition: 0.6s;
    -webkit-transform-style: preserve-3d;

    -moz-transition: 0.6s;
    -moz-transform-style: preserve-3d;

  -o-transition: 0.6s;
    -o-transform-style: preserve-3d;

    transition: 0.6s;
    transform-style: preserve-3d;

    position: relative;
}

.front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back {
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
  -o-backface-visibility: hidden;
    backface-visibility: hidden;

    position: absolute;
    top: 0;
    left: 100;
}

.front-brian{
    background: url(http://static1.squarespace.com/static/573e762945bf219b6da541d1/t/57a5d191e3df28ea3c3f9bfb/1470484886737/Brian+Headshots-29.jpg);

    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

.back-title {
    color: #fff;
    font-size: 2em;
    position: absolute;
    top: 14%;
    left: 0%;
    right: 0%;
    text-align: center;
}

.role {
    color: #fff;
    font-size: 1.5em;
    position: absolute;
    top: 30%;
    left: 0%;
    right: 0%;
    text-align: center;
}

A: This appears to be occurring because you have nested blocks. That is, each code-block ( .code-block ) is nested within the previous one, so each image is slightly more padded than the one before.
See the attached image.
Nested Squarespace Code Blocks - Dev. Tools Screenshot
I'm not sure how this problem was created. Did you copy and paste code containing sqs-block code-block sqs-block-code elements? It appears that you did, at least at first glance.
To fix this, you're going to need to remove all of the Squarespace-specific divs that wrap each of your flip-container divs. Within the code block, all you should have is a series of flip-container divs, one after another. Like this:

etc

etc

etc

etc


Q: PHP code is rendered as text I'm using Ubuntu 16.04 and I want to run php files.
I installed Php 7 on it using:
sudo mkdir -p /var/www/html
sudo chown -R $USER:$USER /var/www/html
sudo apt install php
sudo apt install apache2

I created a php file (e.g. test.php) in /var/www/html. I can access it in the browser (e.g. http://localhost/test.php). Instead of executing the <?php ... ?> code, it is displayed as plain text:
I tried to turn short_open_tag to On. So I edited the /etc/php/7.0/fpm/php.ini and enabled it.
Then I ran sudo service php7.0-fpm restart. This didn't make any change in the browser. The php code is still displayed as plain text.
How can I fix this?

A: You didn't install apache properly, doing an apt-get on apache2 does not install everything.
what @newman stated is correct you can follow that guide, or here is a digitalocean link that is usuable for production server (since you would do this on a droplet). Note this is full stack LAMP, which I would assume you would get to eventually when you want to dab with mysql
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04


Q: How convert a Photoshop made logo into CSS properly? I am trying to convert a logo made into Photoshop in CSS.
As i am no master of both, i've tried but greatly failed by using the Photoshop build in "copy css" function.
I've tried to redo the CSS via my limited knowledge, but failed miserably.

.Group_5 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 1920px;
  height: 1080px;
  z-index: 47;
}
.Group_4 {
  position: absolute;
  left: -2px;
  top: -2px;
  width: 1924px;
  height: 1084px;
  z-index: 46;
}
.Ellipse_3 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1119px;
  top: 486px;
  width: 168.5px;
  height: 174.5px;
  z-index: 45;
}
.Ellipse_2 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1122px;
  top: 505px;
  width: 139.5px;
  height: 139.5px;
  z-index: 44;
}
.Ellipse_1_copy {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1109px;
  top: 512px;
  width: 139.5px;
  height: 139.5px;
  z-index: 43;
}
.Ellipse_1 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1091px;
  top: 492px;
  width: 176.5px;
  height: 176.5px;
  z-index: 42;
}
.Shape_26 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1358px;
  top: 409px;
  width: 10px;
  height: 7px;
  z-index: 41;
}
.Shape_25 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1347px;
  top: 409px;
  width: 18px;
  height: 17px;
  z-index: 40;
}
.Shape_24 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1394px;
  top: 409px;
  width: 11px;
  height: 7px;
  z-index: 39;
}
.Shape_23 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1385px;
  top: 408px;
  width: 21px;
  height: 20px;
  z-index: 38;
}
.Shape_22 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1386px;
  top: 430px;
  width: 20px;
  height: 20px;
  z-index: 37;
}
.Group_2 {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 1920px;
  height: 1080px;
  z-index: 36;
}
.Shape_16_copy_2 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1395px;
  top: 410px;
  width: 8px;
  height: 26px;
  z-index: 35;
}
.Shape_16_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1384px;
  top: 419px;
  width: 8px;
  height: 25px;
  z-index: 34;
}
.Shape_16 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 419px;
  width: 8px;
  height: 25px;
  z-index: 33;
}
.Shape_15 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 439px;
  width: 46px;
  height: 8px;
  z-index: 32;
}
.Shape_19 {
  border-width: 4.167px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  position: absolute;
  left: 1357px;
  top: 407px;
  width: 37.666px;
  height: 0;
  z-index: 31;
}
.Shape_21_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1344px;
  top: 407px;
  width: 19px;
  height: 18px;
  z-index: 30;
}
.Shape_21 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1383px;
  top: 407px;
  width: 20px;
  height: 18px;
  z-index: 29;
}
.Shape_20 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1395px;
  top: 409px;
  width: 8px;
  height: 7px;
  z-index: 28;
}
.Shape_18 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 417px;
  width: 46px;
  height: 8px;
  z-index: 27;
}
.Shape_17_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1381px;
  top: 408px;
  width: 20px;
  height: 19px;
  z-index: 26;
}
.Shape_17 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1384px;
  top: 428px;
  width: 19px;
  height: 19px;
  z-index: 25;
}
.Group_1 {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 1920px;
  height: 1080px;
  z-index: 23;
}
.Rectangle_1 {
  border-width: 4.167px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  position: absolute;
  left: 1325px;
  top: 472px;
  width: 48.666px;
  height: 19.666px;
  z-index: 22;
}
.Shape_10 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 656px;
  width: 11px;
  height: 8px;
  z-index: 21;
}
.Shape_9 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1394px;
  top: 423px;
  width: 41px;
  height: 242px;
  z-index: 20;
}
.Shape_8 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 451px;
  width: 271px;
  height: 213px;
  z-index: 19;
}
.Shape_11 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 450px;
  width: 17px;
  height: 8px;
  z-index: 18;
}
.Shape_7 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 416px;
  width: 64px;
  height: 41px;
  z-index: 17;
}
.Shape_14 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1427px;
  top: 417px;
  width: 8px;
  height: 215px;
  z-index: 16;
}
.Shape_13 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1393px;
  top: 415px;
  width: 44px;
  height: 44px;
  z-index: 15;
}
.Shape_12 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1144px;
  top: 416px;
  width: 302px;
  height: 42px;
  z-index: 14;
}
.Group_3 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 1920px;
  height: 1080px;
  z-index: 11;
}
.Shape_3 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 577px;
  top: 684px;
  width: 710px;
  height: 12px;
  z-index: 10;
}
.Shape_2 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 571px;
  top: 301px;
  width: 137px;
  height: 403px;
  z-index: 9;
}
.I {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pr6N";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1,0,0,0.76592618857706,0,0);
  -webkit-transform: matrix( 1,0,0,0.76592618857706,0,0);
  -ms-transform: matrix( 1,0,0,0.76592618857706,0,0);
  position: absolute;
  left: 1043.001px;
  top: 406px;
  z-index: 7;
}
.C_copy_2 {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pro";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  position: absolute;
  left: 869.507px;
  top: 406.5px;
  z-index: 6;
}
.C {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pro";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  position: absolute;
  left: 711.507px;
  top: 406.5px;
  z-index: 5;
}
.Shape_4 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 685px;
  top: 289px;
  width: 98px;
  height: 212px;
  z-index: 4;
}
.Shape_1 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 693px;
  top: 309px;
  width: 89px;
  height: 191px;
  z-index: 3;
}

I might be just missplacing something, or the given CSS result is not working properly, as anything i do and/or try results into a blank page.
I am not exactly sure how i could get this logo converted, as mentioned above i am no master in both.
The logo is made of circiles/lines and the 2"C" texts.
Some of the layers have masks on them for transparency (where they overlap)
It's not the best made, as it was supposed to have the same thickness overall, but i would like a way to get into CSS form.


Q: How to pass a different argument conditionally I want to be able to change an argument to a function when a condition is met.
Currently I am doing this which works, but I am repeating the first argument, is there a way to just change the second argument?
credential = './credentials.json'

if os.path.exists(credential):
  account = authenticate(client_config=secrets, credentials=credential)
else:
  account = authenticate(client_config=secrets, serialize=credential)

A: An elegant way is to use kwargs:
credential = './credentials.json'
key = "credentials" if os.path.exists(credentials) else "serialize"
auth_kwargs = {"client_config": secrets, key: credential}

account = authenticate(**auth_kwargs)

A: I think your way is fine too, but you can do this
credential = './credentials.json'
params = {'serialize': credential}
if os.path.exists(credentials):
  params['credentials'] = params.pop('serialize')

account = authenticate(client_config=secrets, **params)

A: You can pass an (unpacked) dictionary to a function:
credential = './credentials.json'
arguments = {'client_config': secrets, 'serialize': credential}  # default

if os.path.exists(credentials):
    arguments.pop('serialize')
    arguments['credentials'] = credential

account = authenticate(**arguments)

A: There is functools.partial for this:
from functools import partial

credential = './credentials.json'

auth = partial(authenticate, client_config=secrets)

if os.path.exists(credential):
  account = auth(credentials=credential)
else:
  account = auth(serialize=credential)


Q: Pickle multiple machine learning model I have multilayer model consist of two models, kmeans and random forest classifier; that work inside single function.
My question is how to pickle both and keep them work in sequence???
Thanks in advance


Q: Can I generate numbers in series using IntegerField in Django I have created a model where Integer field is among the field in my model, when each post is added I want to have number that will be generated in series in each post. Can I achieve by just using Integer field, Please help!!!
models.py
class Documents(models.Model):
    docs_name = models.CharField(max_length=200,verbose_name="Jina la Nyaraka")

    item_type = models.CharField(default="", max_length=100,verbose_name="Aina ya nyaraka" )

    police_station = models.CharField(max_length=255, verbose_name="Kituo cha polisi")

    phone_no = models.CharField(verbose_name="Namba yako ya simu", max_length=10, blank=False,
validators=[int_list_validator(sep=''),MinLengthValidator(10),])

    date = models.DateTimeField(default=timezone.now,verbose_name="Date")

    Description = models.TextField(blank=True, null=True,verbose_name="Maelezo zaidi")

    pay_no = models.IntegerField(default=0,verbose_name="Namba ya malipo")

    publish = models.BooleanField(default=False)

    image = models.ImageField(upload_to="Documents",blank=False, verbose_name="Picha ya nyaraka")

    """docstring for Documents"""
    def __str__(self):
        return self.docs_name

views.py
@login_required
def PostNew(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('loststuffapp:IndexView')
    else:
        form = PostForm()
    return render(request, 'loststuffapp/form.html', {'form': form})

A: well as far i can get it, you need to make some kind of sequence for your IntegerField.
while it's not and id field, you can emmulate it by taking max value of that field among all objects:
max_val = YourModelClass.objects.all().aggregate(Max('that_field_in_question'))
# then just make new object, and assign max+1 to 'that_field_in_question'
new_obj = YourModelClass('that_field_in_question'=max_val + 1)
new_obj.save()


Q: Using UIRefreshControl in UIViewController with UITableView I wonder how i can use UIRefreshController for a UITableView inside a UIViewController.
I want to implement pull-to-refresh functionality to TableView but i don't have a TableViewController.
Is there a way to do this in xcode 6 (swift)

A: Of course you can do this. Initiate a RefreshControl and simply put it as subview of your tableview. You don't necessarily  need a UITableViewController for this.
EDIT:
Try something like this:
let control = UIRefreshControl()
control.addTarget(self, action: "action", forControlEvents: .ValueChanged)
tableView.addSubview(control)

A: Here's the Objective-C version that worked for me in case anyone needs it. I added it to viewDidLoad:
UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
[refresh addTarget: self action: @selector(didPullToRefresh:) forControlEvents: UIControlEventValueChanged];
[self.tableView addSubview: refresh];

Not a fan of UITableViewController...


Q: Flutter paint(): is this legit? Rendering Renderobject in different context I try to render the child of a listitem (somewhere up) to a different place (widget) in the tree;
In the approach below, BlendMask is the "target" widget that checks for and paints "source" widgets that got themself an GlobalKey which is stored in blendKeys.
This works somewhat. And I'm not quite sure if I might fight the framework, or just missing some points...
The problems are two:

*

*The minor one: This approach doesn't play nice with the debugger. It compiles and runs fine but every hot-reload (on save f.e.) throws an "can't findRenderObject() of inactive element". Maybe I miss some debug flag?

*the real problem, that brought me here questioning the idea en gros: As mentioned, the Source-Widget is somewhere in the subtree of the child of a Scrollable (from a ListView.build f.e.): How can I update the Òffset for the srcChild.paint() when the list is scrolled? - without accessing the lists scrolController?! I tried listening via WidgetsBindingObservers didChangeMetrics on the state of the Source widget, but as feared no update on scroll. Maybe a strategically set RepaintBounderyis all it needs? *hope* :D
Anyway, every tip much appreciated. Btw the is an extend of this question which itself extends this...
class BlendMask extends SingleChildRenderObjectWidget {
  [...]
  @override
  RenderObject createRenderObject(context) {
    return RenderBlendMask();
  }
}

class RenderBlendMask extends RenderProxyBox {
[...]
@override
void paint(PaintingContext context, offset) {    <-- the target where we want to render a widget
  [...]                                              from somewhere else in the tree!
  for (GlobalKey key in blendKeys) {
    if (key.currentContext != null) {
      RenderObject? srcChild                     <-- the source we want to render in this sibling widget!
       = key.currentContext!.findRenderObject();
      if (srcChild != null) {
        Matrix4 mOffset = srcChild.getTransformTo(null);
        context.pushTransform(true, offset, mOffset, (context, offset) {
          srcChild.paint(context, offset);
        });
      }
    }
  }
}
} //RenderBlendMask


Q: Difficulty screen scraping http://www.momondo.com using nokogiri I have some difficulty to extract the total price (css selector = '.total') from the flight result.
http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false

I get the error "undefined method `text' for nil:NilClass nokogiri ".
My code
desc "Fetch product prices"
task :fetch_details => :environment do
  require 'nokogiri'
  require 'open-uri'
  include ERB::Util

  OneWayFlight.find_all_by_money(nil).each do |flight|
    url = "http://www.momondo.com/multicity/Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false"
    doc = Nokogiri::HTML(open(url))
    price = doc.at_css(".total").text[/[0-9\.]+/]
    flight.update_attribute(:price, price)
  end
end

A: The content you're attempting to scrape appears to be populated by JS after the page loads. To see for yourself, inspect the content of div#flight_results of the document you're currently parsing:
url = 'http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false'

doc = Nokogiri::HTML(open(url))
doc.at_css('div#flight_results').to_html #=> '

'

Though it is outside of the scope of this question, you can generally reconstruct the JS requests used to populate the content you're after.


Q: C++ Function pointers vs Switch
*

*What is faster: Function pointers or switch?

The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30.
I could do the following:
class myType
{
    FunctionEnum func;
    string argv[123];
    int someOtherValue;
};
// In another file:
myType current;
// Iterate through a vector containing lots of myTypes
 // ... for ( i=0; i < myVecSize; i ++ )
    switch ( current.func )
    {
           case 1:
            //...
            break;
           // ........
           case 30:
             // blah
            break;
    }

And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions.
Or I could do that (not so sure with that):
class myType
{
    myReturnType (*func)(int all, int of, int my, int args );
    string argv[123];
    int someOtherValue;
};

I'd have 30 different functions then, at the beginning a pointer to one of them is assigned to myType.

*

*What is probably faster: Switch statement or function pointer?

Calls per second: Around 10 million.
I can't just test it out - that would require me to rewrite the whole thing. Currently using switch.
I'm building an interpreter which I want to be faster than Python & Ruby - every clock cycle matters!

A: I think the difference is negligible in most cases - your case might be an exception. Why don't you put together a simple prototype app to explicitly measure the performance of each solution? My guess is that it would not take more than an hour of work...
However, think about clarity and maintainability of the code as well. IMHO it is obvious that the function pointer solution wins hands down in this respect.
Update: Note also that even if one solution is, let's say, twice as fast as the other as it is, it still may not necessarily justify rewriting your code. You should profile your app first of all to determine how much of the execution time is actually spent in those switches. If it is 50% of total time, there is a reason to optimize it. If it is a couple of percents only, optimizing it would be a waste of effort.

A: Péter Török has the right idea about trying both and timing them.  You may not like it, but unfortunately this is the reality of the situation.  The "premature optimization" chant happens for a reason.
I'm always in favour of using performance best-practices right from the start as long as it doesn't sacrifice clarity.  But in this kind of case it's not a clear win for either of the options you mentioned.  In most cases, this kind of minor change will have no measurable effect.  There will be a few major bottlenecks that completely govern the speed of the whole system.  On modern computers a few instructions here and there will be basically invisible because the system is blocked by memory cache misses or by pipeline stalls and those can be hard to predict.  For instance in your case, a single extra cache miss would likely decide which method would be slower.
The real-world solution is to evaluate the performance of the whole system with a profiler.  That will show you where your "hot spots" are in the code.  The usual next step is to make algorithmic changes to reduce the need for that many calls into the hot code either through better algorithms or through caching.  Only if a very tiny section of code is lighting up the profiler is it worth getting down to small micro-optimizations like this.  At that point, you have to try different things and test the effect on speed.  Without measuring the effect of the changes, you're just as likely to make it worse, even for an expert.
All that being said, I would guess that function calls in your case might be very slightly faster if they have very few parameters, especially if the body of each case would be large.  If the switch statement doesn't use a jump table, that likely be slower.  But it would probably vary a lot by compiler and machine architecture, so I wouldn't spend much time on it unless you have hard evidence later on that it is a bottleneck to your system.  Programming is as much about re factoring as it is about writing fresh code.

A: Switch statements are typically implemented with a jump table.  I think the assembly can go down to a single instruction, which would make it pretty fast.
The only way to be sure is to try it both ways.  If you can't modify your existing code, why not just make a test app and try it there?

A: Writing interpreters is fun, isn't it?  I can guess that the function pointer might be quicker, but when you're optimizing, guesses won't take you very far.
If you really want to suck every cycle out of that beast, it's going to take multiple passes, and guesses aren't going to tell you what to fix. Here's an example of what I mean.


Q: How to give strokes a specific width based on base64 i'm trying to build a stroked line, based on a svg file, cause of the color and the corner shapes that it has. Each stroke is 15px wide and has a gap between each line from also 15px. The problem is that when i try to include it via background-image it always makes the line longer than it actually should be.

.stroke-dotted {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTVweCIgaGVpZ2h0PSI0cHgiIHZpZXdCb3g9IjAgMCAxNSA0IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPGcgaWQ9IldlYnNpdGUiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJEZXNrdG9wIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQyLjAwMDAwMCwgLTE5NDAuMDAwMDAwKSIgc3Ryb2tlPSIjMTZDREM3IiBzdHJva2Utd2lkdGg9IjMiPgogICAgICAgICAgICA8ZyBpZD0iU2VydmljZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDE0ODguMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iV2ViZGVzaWduIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg2MC4wMDAwMDAsIDQzOC4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIsMTYgTDk3LDE2IiBpZD0ibGluZSI+PC9wYXRoPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
  width: 100%;
  background-repeat: repeat-x;
}

Thats how it should look like:

And that's how it looks now:

Is there a way to give the lines a specific width of 15px and also an gap of 15px? I also tried to fix it with the background-size attribute, but it didn't worked out.

A: First things first: don't encode your SVG as a base64, it is much longer than the original code and its unnecessary as you can just add the code to the url. You might need to URL encode it for IE11 and earlier, but otherwise all browsers support it.
Now, to control your sizing in SVG tags, ommit the viewBox and simply give it a width and height of 100% and express all other values in percentage. Now you can control the size of the line by defining its pixel size, even though the points are defined in percentage:

div {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0%;
  top: 0%;
  background: url('data:image/svg+xml;charset=utf8,<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">\
    <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="cyan" stroke-width="1px" stroke-dasharray="15px 15px" />\
  </svg>') no-repeat 50% 50% / cover;
}
body {
  /* A reference grid */
  background: url('data:image/svg+xml;charset=utf8,<svg width="15px" height="15px" xmlns="http://www.w3.org/2000/svg">\
    <rect x="0" y="0" width="100%" height="100%" stroke="#222" stroke-width="1px" fill="black" />\
  </svg>');
}

Once your SVG is correctly set up, it is as simple as defining the stroke-dasharray property with the pixel values:
<line x1="0%" y1="50%" x2="100%" y2="50%" stroke="black" stroke-width="1px" stroke-dasharray="15px 15px" />

Now you can use CSS to change your box, or even SVG to change the offsets within the SVG background.


Q: PHP Notice: Undefined index errors I have been creating some code in PHP and the logs of my server keep showing the following errors. The code are handlers for a game that I have been creating.  I have tried to fix them by researching and applying the ''fixes'' but it didn't go well.

Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 160
Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 161
Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 167
Undefined index: a#lt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 227
Trying to get property of non-object in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 302

This is the code for them:
function handleJoinTable(Array $arrData, Client $objClient) {
    $intPlayer = $arrData[4];
    $tableId = $arrData[2];
    $strUsername = $this->objDatabase->getUsername($intPlayer);
    $seatId = count($this->tablePopulationById[$tableId]) - 1; // Line 160
    if($this->gamesByTableId[$tableId] === null) { // Line 161
        $findFourGame = new FindFour();
        $this->gamesByTableId[$tableId] = $findFourGame;
    }
    $this->tablePopulationById[$tableId][$strUsername]; // Line 167
    $seatId += 1;
    $objClient->sendXt('jt', $objClient->getIntRoom(), $tableId, $seatId);
    $objClient->sendXt('ut', $objClient->getIntRoom(), $tableId, $seatId);
    $this->playersByTableId[$tableId][] = $intPlayer;
    $this->tableId = $tableId;
}

function handleLeaveTable(Array $arrData, Client $objClient) {
        $intPlayer = $arrData[2];
        $tableId = $arrData[3];
        $strUsername = $this->arrClientsByID[$intPlayer]; // Line 227
        unset($objClient->arrPlayer[$intPlayer]);
        $objClient->sendXt('lt', $objClient->getIntRoom(), $strUsername);
    }

function handleGetGame(Array $arrData, Client $objClient) {
    $intPlayer = $arrData[3];
    if($objClient->getExtRoom() == 802) {
        $puckData = $this->rinkPuck;
        $objClient->sendXt('gz', $objClient->getIntRoom(), $puckData);
    } elseif($intPlayer->tableId !== null) { // Line 302
        $tableId = $intPlayer->tableId;
        $playerUsernames = array_keys($this->tablePopulationById[$tableId]);
        @list($firstPlayer, $secondPlayer) = $playerUsernames;
        $boardString = $this->gamesByTableId[$tableId]->convertToString();
        $objClient->sendXt('gz', -1, $firstPlayer, $secondPlayer, $boardString);
    }
}

What's going on here?

A: $this->tablePopulationById[$tableId]
tablePopulationById is an array that DOES NOT contain a key of index $tableId.
$arrData[3]; DOES NOT contain an object of whatever class you were expecting!
In both cases, var_dump them to see what you DO have!
var_dump($this->tablePopulationById);
var_dump($arrData);


Q: Javascript: Testing form submit with sinon spy and chai Hi im trying to test a form submit using sinon spy and chai, however I am not sure if I am doing the right thing. Whenever i run the test, seconds comes back as undefined. Not sure why this is happening. I'm new to sinon, chai. Here is the code
This is the test file:
describe('CountdownForm', () => {
  it('should exist', () => {
    expect(CountdownForm).to.exist;
  });
  it('should call onSetCountdown if valid seconds entered', () => {
    const spy = sinon.spy();
    const countDownForm = shallow(<CountdownForm onSetCountdown={spy}/>)

    countDownForm.refs.seconds.value = '109';
    countDownForm.find('form').simulate('submit', { preventDefault(){} })

    expect(spy.called).to.be.true;
  });
});

This is the jsx file:
class CountdownForm extends Component {

  onSubmit = (e) => {
  e.preventDefault();
  const stringSeconds = this.refs.seconds.value;

  if (stringSeconds.match(/^[0-9]*$/)) {
    this.refs.seconds.value = '';
    this.props.onSetCountdown(parseInt(stringSeconds, 10));
    }
  }
  render() {
    return (
      <div>
        <form ref="form" onSubmit={this.onSubmit} className='countdown-form'>
          <input type="text" ref="seconds" placeholder="Enter time in seconds"/>
          <button className="button expanded">Start</button>
        </form>
      </div>
    );
  }
}


Q: ssh reverse port forwarding from local to remote2 by using remote1 I need port forwarding and also reverse port forwarding betwwen my localhost and remote2 pc using remote1 pc. My local pc can not connect directly remote2.
Design looks like:
local  ----------------> remote1 -----------------> remote2

5037  ---(ssh -L 5037:remote2:7385 user@remote1)--->  7385  //working

27183  <-----------( I can not achieve )------------ 27183  //need

I used ssh -L 5037:remote2:7385 -R remote2:27183:localhost:27183 user@remote1
But it forwards my local 27183 port to remote1's 27183 port.
How to use ssh tunnelling to forward my local 27183 port to remote2's 27183 port?