text:
Q: POCO's, DTO's, DLL's and Anaemic Domain Models I was looking at the differences between POCO and DTO (It appears that POCO's are dto's with behaviour (methods?))and came across this article by Martin Fowler on the anaemic domain model.
Through lack of understanding, I think I have created one of these anaemic domain models.
In one of my applications I have my business domain entities defined in a 'dto' dll. They have a lot of properties with getter's and setter's and not much else. My business logic code (populate, calculate) is in another 'bll' dll, and my data access code is in a 'dal' dll. 'Best practice' I thought.
So typically I create a dto like so:
dto.BusinessObject bo = new dto.BusinessObject(...)

and pass it to the bll layer like so:
bll.BusinessObject.Populate(bo);

which in turn, performs some logic and passes it to the dal layer like so:
dal.BusinessObject.Populate(bo);

From my understanding, to make my dto's into POCO's I need to make the business logic and behaviour (methods) part of the object. So instead of the code above it is more like:
poco.BusinessObject bo = new poco.BusinessObject(...)
bo.Populate();

ie. I am calling the method on the object rather than passing the object to the method.
My question is - how can I do this and still retain the 'best practice' layering of concerns (separate dll's etc...). Doesn't calling the method on the object mean that the method must be defined in the object?
Please help my confusion.

A: Personally I don't find those Anaemic Domain Models so bad; I really like the idea of having domain objects that represent only data, not behaviour. I think the major downside with this approach is discoverability of the code; you need to know which actions that are available to use them. One way to get around that and still keep the behaviour code decoupled from the model is to introduce interfaces for the behaviour:
interface ISomeDomainObjectBehaviour
{
    SomeDomainObject Get(int Id);
    void Save(SomeDomainObject data);
    void Delete(int Id);
}

class SomeDomainObjectSqlBehaviour : ISomeDomainObjectBehaviour
{
    SomeDomainObject ISomeDomainObjectBehaviour.Get(int Id)
    {
        // code to get object from database
    }

    void ISomeDomainObjectBehaviour.Save(SomeDomainObject data)
    {
        // code to store object in database
    }

    void ISomeDomainObjectBehaviour.Delete(int Id)
    {
        // code to remove object from database
    }
}
class SomeDomainObject
{
    private ISomeDomainObjectBehaviour _behaviour = null;
    public SomeDomainObject(ISomeDomainObjectBehaviour behaviour)
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int Size { get; set; }

    public void Save()
    {
        if (_behaviour != null)
        {
            _behaviour.Save(this);
        }
    }

    // add methods for getting, deleting, ...

}

That way you can keep the behaviour implementation separated from the model. The use of interface implementations that are injected into the model also makes the code rather easy to test, since you can easily mock the behaviour.

A: Typically, you don't want to introduce persistence into your domain objects, since it is not part of that business model (an airplane does not construct itself, it flies passengers/cargo from one location to another).  You should use the repository pattern, an ORM framework, or some other data access pattern to manage the persistent storage and retreival of an object's state.
Where the anemic domain model comes in to play is when you're doing things like this:
IAirplaneService service = ...;
Airplane plane = ...;
service.FlyAirplaneToAirport(plane, "IAD");

In this case, the management of the airplane's state (whether it's flying, where it's at, what's the departure time/airport, what's the arrival time/airport, what's the flight plan, etc) is delegated to something external to the plane... the AirplaneService instance.
A POCO way of implementing this would be to design your interface this way:
Airplane plane = ...;
plane.FlyToAirport("IAD");

This is more discoverable, since developers know where to look to make an airplane fly (just tell the airplane to do it).  It also allows you to ensure that state is only managed internally.  You can then make things like current location read-only, and ensure that it's only changed in one place.  With an anemic domain object, since state is set externally, discovering where state is changed becomes increasingly difficult as the scale of your domain increases.

A: I think the best way to clarify this is by definition:
DTO: Data Transfer Objects:
They only serve for data transportation typically between presentation layer and service layer. Nothing less or more. Generally it is implemented as class with gets and sets.
public class ClientDTO
{
    public long Id {get;set;}
    public string Name {get;set;}
}

BO: Business Objects:
Business objects represents the business elements and naturally the best practice says they should contain business logic also. As said by Michael Meadows, it is also good practice to isolate data access from this objects.
public class Client
{
    private long _id;
    public long Id
    {
        get { return _id; }
        protected set { _id = value; }
    }
    protected Client() { }
    public Client(string name)
    {
        this.Name = name;
    }
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {   // Notice that there is business logic inside (name existence checking)
            // Persistence is isolated through the IClientDAO interface and a factory
            IClientDAO clientDAO = DAOFactory.Instance.Get<IClientDAO>();
            if (clientDAO.ExistsClientByName(value))
            {
                throw new ApplicationException("Another client with same name exists.");
            }
            _name = value;
        }
    }
    public void CheckIfCanBeRemoved()
    {
        // Check if there are sales associated to client
        if ( DAOFactory.Instance.GetDAO<ISaleDAO>().ExistsSalesFor(this) )
        {
            string msg = "Client can not be removed, there are sales associated to him/her.";
            throw new ApplicationException(msg);
        }
    }
}

Service or Application Class
These classes represent the interaction between User and the System and they will make use of both ClientDTO and Client.
public class ClientRegistration
{
    public void Insert(ClientDTO dto)
    {
        Client client = new Client(dto.Id,dto.Name); /// <-- Business logic inside the constructor
        DAOFactory.Instance.Save(client);
    }
    public void Modify(ClientDTO dto)
    {
        Client client = DAOFactory.Instance.Get<Client>(dto.Id);
        client.Name = dto.Name;  // <--- Business logic inside the Name property
        DAOFactory.Instance.Save(client);
    }
    public void Remove(ClientDTO dto)
    {
        Client client = DAOFactory.Instance.Get<Client>(dto.Id);
        client.CheckIfCanBeRemoved() // <--- Business logic here
        DAOFactory.Instance.Remove(client);
    }
    public ClientDTO Retrieve(string name)
    {
        Client client = DAOFactory.Instance.Get<IClientDAO>().FindByName(name);
        if (client == null) { throw new ApplicationException("Client not found."); }
        ClientDTO dto = new ClientDTO()
        {
            Id = client.Id,
            Name = client.Name
        }
    }
}


text:
Q: what is wrong with this code of login validate form using php In this code login page is going to validate form and if password is correct then its working correct but if not then its not working else code why?
Here is code
<?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
            else{
                echo "<script> alert('incorrect user name or password')</script>";
                echo "<script> window.location.assign('login.php'); </script>";
            }
        }
    }
?>

if condition  part is working correctly but not else condition  part .help me please.

A: The answer of your question is because you have the alert js inside the if statement where it will be executed only if there is more than 0 rows returned.
Please hash your users passwords.
Please use prepared statements to use with users input on DB query.
Echoing JS like that aint cool but its up to you if you want use it.

A: Your else is in your first if(mysqli_num_rows($run)>0) condition.
That's why this is not working
correct code is
<?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
        }
        else{
            echo "<script> alert('incorrect user name or password')</script>";
            echo "<script> window.location.assign('login.php'); </script>";
        }
    }
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get BitmapSource from BitmapImage? How to get BitmapSource from BitmapImage? Or how to convert BitmapImage to BitmapFrame directly?
It seems to me that if I have BitmapSource I could use BitmapFrame.Create and finally get BitmapFrame object from given BitmapImage

A: A BitmapImage inherits from  BitmapSource so no conversion is needed

A: The BitmapImage inherits from BitmapSource as parapura said.
Example:
BitmapSource bitmapSource = new BitmapImage();
BitmapImage bitmapImage = bitmapSource as BitmapImage;

Source: BitmapSource MSDN


text:
Q: Any way to get java path used by tomcat/glassfish in web application Title is pretty clear for my question, suppose I deployed an java application in tomcat/glassfish now for some reason I need java path used by respective server so is there any way to get java path which is used by server?

A: You can get the java.home System Property, which should be exactly what you want:
System.getProperty("java.home");


text:
Q: Mysql Query problem in searching record Query:
SELECT t1.id,
       t1.ads_city,
       t1.ads_title,
       t1.ads_description,
       t1.ads_type,
       t2.ads_activate,
       t2.postads_id,
       t2.ads_id
  FROM table_1 t1
  JOIN nextpostads t2 ON t1.id = t2.postads_id
 WHERE MATCH(t1.ads_title,t1.ads_description) AGAINST ('LCD  projector ,' IN BOOLEAN MODE)
   AND t2.ads_activate='Yes'
   AND t1.ads_type='offering'

I have 2 record first record title is
" LCD projector,plasma display,recording speaker products"

and second record title is
" Interactive products(projection screen,projectors,touch panel,network camera)"

But from the above query I am not related result what is problem with it ?

A: My guess is the t2.ads_activate value isn't "Yes" and/or the t1.ads_type value isn't "offering".  Try:
SELECT t1.id,
       t1.ads_city,
       t1.ads_title,
       t1.ads_description,
       t1.ads_type,
       t2.ads_activate,
       t2.postads_id,
       t2.ads_id
  FROM table_1 t1
  JOIN nextpostads t2 ON t1.id = t2.postads_id
 WHERE MATCH(t1.ads_title,t1.ads_description) AGAINST ('LCD  projector ,' IN BOOLEAN MODE)

If the records you expect are returned, add the missing WHERE clauses , testing them one at a time.  Otherwise, there's something with your JOIN...


text:
Q: Image processing: counting individual number pixel in an mask image using Pillow and 3D Numpy Please help me. I need some opinion on this problem.
I am trying to count individual number of R,G,B value of an mask image.
I have an image which is masked filled background with green and it mask a human with red and an object with blue.
The image size and data type are
(1536, 2048, 3)
uint8
I have tried to access the numpy array of pixels
img_path = "sample.png"
i = Image.open(img_path, 'r')
data = asarray(i)
array = np.array(i)

But the array only show the background green. Something like below.
[[[ 0, 255, 0
    0, 255,0]]]

It does not show red and blue color of an image
I have tried getpixel()
i = Image.open(img_path, 'r')
r, g, b = i.getpixel((0, 0))
print("Red: {}, Green: {}, Blue: {}".format(r, g, b))

It does not count the red and and blue color of mask image.
How to count the number of R,G,B pixel in mask image?
Where can I find read more about accessing and counting total number of pixels with numpy and pillow?
Please tell me anything related to this.

A: from PIL import Image
with Image.open('hopper.jpg') as im:
    px = im.load()

r, g, b = px[x, y]
print(r, g, b)

This code worked for me. x and y pixel cordinates.
You can get full info from this


text:
Q: Dual Windows 7/Ubuntu machine no longer sees Ubuntu partition after uninstalling Wubi Until today I had successfully followed instructions from this site to install Ubuntu 12.04 via Wubi, and then move it to a new partition (on a second hard disk). Everything was working beautifully.
However, after misreading some instructions on a related site, I uninstalled Wubi via Windows 7's Programs and Features control panel. I knew I was in trouble when the uninstaller displayed a message about removing a boot record; now my machine boots straight into Windows 7 with no option for using Ubuntu.
I do know that Ubuntu is still there and will become usable again once I fix up my machine's boot options. However, after reading many similar pages on this and related sites I still have no idea how to do this.
If I have learned anything, it is that this process seems incredibly complex and frankly very confusing, not to mention risky in terms of buggering things up and bricking my machine.
Can someone PLEASE post some simple (and foolproof) instructions on how to get Ubuntu booting again when I only have access to Windows? All I can tell you about my lost Ubuntu partition is that it was on /sdb-something-or-other (the second disk).

A: I finally ended up with a regular Ubuntu installation instead of Wubi.
The problem may have been somehow related to my CD/DVD drive. I made a bootable USB medium and everything worked perfectly. Now I only see GRUB (listing both Ubuntu and Windows 7) so this is more streamlined than the previous setup using the Windows boot leader followed by GRUB. Both OSs load properly and any Windows apps that use networked licensing systems still run.


text:
Q: How to make javascript interact with .aspx page? I wish to run some asp.net code on a page generated by Wordpress. Is there a way using XMLHttpRequest() to make JavaScript interact with .aspx page just like a Servlet?
For example, I hope that I can do this in JavaScript:
xmlHttpRequest.open("POST", "http ://some.aspx", true);
send_request("request=add,1,2");
function getReadyStateHandler(xmlHttpRequest) {
    //handle_response
}

How to write and configure such an asp page? Does someone know a good tutorial?
Thanks a lot!

A: You are better of using JQuery for this task.
It is Javascipt library that has exactly functionality that you re looking for
You can call your backend methods to invoke serverside action that would return JSON object. and then in done function process the result.
$.ajax({
  url: "test.html",
  context: document.body
}).done(function(result) {
var dataFromTheSreverside = result;
  $( this ).addClass( "done" );
});

Here you can find a lot of examples


text:
Q: GIF animation changing background unexpectedly I have the following animation that I wish to export as GIF
     ac = Table[Graphics[{EdgeForm[Black], LightGray, Polygon[{{0, 0}, {1/\[Lambda], 0},{1/[Lambda],\[Lambda]}, {0, \[Lambda]}} /. \[Lambda] -> t]}], {t, 1, 4,0.1}];
    Export["gif.gif", ac, "GIF","DisplayDurations" -> 0.25]

but suddenly at the end a black background starts to appear, as shown below. What may be the flaw  ?

A: *

*One workaround is using  ListAnimate
output = ListAnimate[ac];
Export["gif-1.gif", output, "DisplayDurations" -> 0.25,
 "ControlAppearance" -> None]

*

*I also recommend to set PlotRange.

ac = Table[
   Graphics[{EdgeForm[Black], LightGray,
     Polygon[{{0, 0}, {1/λ,
         0}, {1/λ, λ}, {0, λ}} /. λ ->
         t]}, PlotRange -> {{0, 2}, {0, 4.5}}, Axes -> True], {t, 1,
    4, 0.1}];
Export["gif-2.gif", ac, "GIF", "DisplayDurations" -> 0.25]


text:
Q: Trigger REST adapter to push records to store I have the following setup:

*

*The ember frontend is connected to a websocket server

*The backend pushes records (real-time data) via websocket to the clients, as stringified JSON

*The client receives the data, and must now update the store with this new data received

The problem that I have is that I do not know to process the raw JSON data to make it compatible to  what is in the store. I can of course parse the json (JSON.parse), but this is just a part of what the REST adapter is doing.
When doing a normal REST request, more or less what happens is that:
server generates reply -> REST adapter converts it -> it gets pushed to the store

But now, since I am not using the REST adapter to process this data (because this is not a request triggered in the client side, but a notification coming from the server side), I do not know how to trigger the normal processing that the REST adapter performs.

*

*How can I trigger the REST adapter programmatically? Can I pass it the stringified JSON coming from the websockets server?

*Is it possible to hook the REST adapter to a generic websockets callback, where the only thing I have is the stringified JSON coming from the websockets server?

This is the code that I have (inspired in web2py)
function connect_websocket() {
    console.log('connect_websocket > connecting to server');
    var callback = function(e) {
        var data = JSON.parse(e.data);
        console.log('Data received > data=%o', data);
        // TODO;
        //  - process the data as the REST adapter would do, and push new / updated records to the store.
        //  - handle record deletes too (how?)
    };
    if(!$.web2py.web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup', callback)) {
        alert('html5 websocket not supported by your browser, try Google Chrome');
    }
}

I have taken a look at EmberSockets, but as far as I understand that does not offer a generic method of updating records in the store, but just a very specialized way of updating properties in the controllers (which requires a lot of configuration too).
What I am looking for is a generic method of triggering the ember REST adapter from a websockets server. Is there such a thing?


text:
Q: NX Server lower-case d minimizes from OS X Client? I've installed NX Server on Ubuntu Maverick Meerkat (10.10) using the instructions found here: https://help.ubuntu.com/community/FreeNX
I have a problem using the default NX Client for OS X (10.6) downloaded from the nomachine website.
When using the OS X client, every time I hit the lowercase d key in the NX session window whatever remote window I'm using minimizes. This only happens in OS X, from the Windows client I have no such problem. This happens from two different OS X machines, so it's unlikely to be a local setting.

A: Solved it. NX client seems to assign it's own shortcuts - but only on Ubuntu 10.10 does it assign minimize all windows to the 'd' character. Change it server side when logged in via the NX Client and the problem is fixed.
Under Settings > Key Mappings > Minimize All Windows. It won't let you disable it, so just choose a key combo you'll never use (I chose Ctrl + D.)

A: You can disable it by 'assgining' Backspace as the new shortcut.

A: I had this problem in Ubuntu 10.10 too.  Whenever I pressed d on the keyboard it minimized all the windows.  I fixed it by going into System --> Preferences --> Keyboard Shortcuts and disabling the shortcut that was setup to use the D key press.

A: The setting I had to disable d for in Ubuntu 10.10 was "Hide all normal windows and set focus to the Desktop"
As Kyle said in another reply, use Backspace to disable the shortcut

A: The above didn't work for me but the tip here did for Ubuntu 11.10.  After I made the change, I had to restart.


text:
Q: Geotools & Natural Earth finding lat/lon not always accurate I am trying to take a lat/lon and find which country the lat/lon is located in.
Below is a boilerplate of code I found to accomplish this, which was found in this post (Reverse Geocode latitude longitude with Geotools using Natural Earth Shapefiles in Java
)
SpatialIndexFeatureCollection countries;
final static FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
final static public String countryFile ="/data/natural_earth/10m_cultural/10m_admin_0_countries.shp";

public SimpleGeoCoder() throws IOException {
  // load the country shapefile
  URL countryURL = DataUtilities.fileToURL(new File(countryFile));
  HashMap<String, Object> params = new HashMap<>();
  params.put("url", countryURL);
  DataStore ds = DataStoreFinder.getDataStore(params);
  if (ds == null) {
    throw new IOException("couldn't open " + params.get("url"));
  }
  Name name = ds.getNames().get(0);
  countries = new SpatialIndexFeatureCollection(ds.getFeatureSource(name).getFeatures());
}

GeometryFactory gf = new GeometryFactory();
Point london = gf.createPoint(new Coordinate(0.0, 51.0));

public SimpleFeatureCollection lookup(Point p) {
  Filter f = ff.contains(ff.property("the_geom"), ff.literal(p));
  return countries.subCollection(f);
 }

SimpleFeatureIterator itr = features.features();
try {
  while (itr.hasNext()) {
    SimpleFeature f = itr.next();
    System.out.println(f.getAttribute("NAME"));
  }
} finally {
  itr.close();
}

Most of the time this solution works, however there seems to be cases where a lat/lon will not be found within the Natural Earth shapefiles.  A perfect example would be for the city of Miami Florida (25.761681, -80.191788) when using the shapefile "10m_cultural/10m_admin_0_countries.shp".
My original solution was to use the shapefile "110m_cultural/110m_admin_0_countries.shp" the Miami example will be fine.  However I have found a few other examples which occur within the 110m shapefile and I don't know what the solution is.  Do I use both the 10m and the 110m shapefiles?  Or is there some setting or something else I need to do to accurately solve this issue?

A: This is nothing to do with the code and everything to do with the "accuracy" (or generalisation) of the data.
As you can see here the coastline is placed in very different places depending on the level of generalisation applied, this is because the Natural Earth files are designed to look good at scales of 1:110M, 1:50M & 1:10M but this image is at 1:500K.
Also you will see that the location of Miami from Natural Earth (the red dot) has been adjusted to fall within the US polygon to make it look cartographically good, whereas your Miami location is a little further south and east and so falls outside some of the polygons.
Depending on your area of interest you will be able to find "better" coastlines (and country boundaries) by looking for national and regional mapping agencies.


text:
Q: In javascript why this reduce method of an array gives this output in below code?

var check = [1,2,3,4,5];

var check1 = check.reduce((accumulator,element,index,array) => element )

console.log(check1);
//output :5. Why?

A: This is intended! It's because your reducer here is returning every item (your element parameter) in the array and once we reach the end, we are returning the last item (which happens to be 5).


text:
Q: Transformar ciclo em função de ordem superior Boa tarde, tenho esta função contendo um ciclo:
def ciclo(x,y):
    lista = []
    for i in x:
        if i[0]==y:
            lista.append(i[3])
    return sorted(lista)

E eu queria transformá-la numa linha de código, usando a função map do python.
Já tenho isto: sorted(map(lambda i: i[3], x))
Mas isto contém só o ciclo, o if i[0]==y eu não sei como fazer para metê-lo ai dentro da função map.

A: Em Python isso ai é uma linha:
sorted(i[3] for i in x if i[0] == y)

Esqueça o uso de "map"  em geral ele é mais complicado do que os "generator expressions" e "list comprehensions" que temos embutidos na linguagem -
esses nomes chiques são para uso do comando "for" em uma expressão inline, como fiz acima -  e permitem, sem o uso das funções "map", "filter", ou da palavra chave "lambda"  o mapeamento e filtragem de qualquer conjunto de dados:
Basicamente, você escreve "<expressão>  for item in <iterador> if <expressão-de-filtro>" em qualquer lugar onde a linguagem espere um iterador - ele vai te dar todos os items do iterador, e para cada um, vai processar a < Expressão> se a expressão-de-filtro for verdadeira.
Ou seja, a expressão inicial faz o papel do "map", e a expressão depois do "if" faz o papel do "filter".
Se quiser o resultado final numa lista, ponha essa sintaxe entre colchetes.
([<expressão>  for item in <iterador> if <expressão-de-filtro>])  - no caso, como você quer os resultados ordenados, em vez disso, passei o iterador para uma chamada a sorted que retorna um objeto list  já ordenado.
A expressão que dei como resposta acima seria o equivalente a:
map((lambda i: i[3]), filter((lambda i: i[0] == y), x) )

(ou seja, o iterador retornado pela chamada ao  filter é o parâmetro de sequência para a chamada ao map - fica bem mais difícil de ler)
(tambem note que é melhor proteger os lambdas com parênteses para evitar ambiguidade, para leitores humanos, se a "," indica o fim do lambda, ou indica que o lambda vai retornar uma tupla, em vez de um único resultado)

A: Você poderia usar expressões condicionais (meio que um ternário exótico) e retornar None caso [0] seja diferente de y e depois aplicar um filter para remover os Nones:
def higherOrderCycle(x, y):
    return sorted(
        filter(
            lambda v: v != None,
            map(lambda v: v[3] if v[0] == y else None, x)
        )
    )

Veja que caso você esteja esperando None em v[3] seria necessário adaptar essa função. Também embora a implementação com funções de ordem superior seja muito bonita e dentro do paradigma funcional ela é bem mais obscura que a que você postou, então fora o aprendizado não vejo motivo para usá-la no lugar da outra.


text:
Q: My program needs to count the number of occurences of letters in a word, but it seems to count only the occurence of letter 'a' I need to accept a String and check how many letters of the alphabet appeared on it. However, it seems to only count how many times 'a' appears and concatenate that count to all the letters. I can't find where the error is. Any help will be appreciated. Thanks in advance! Here's my code and output.
package javaPackage;
public class Counter {
    public static void main(String[] args) {
        String letter="abcdefghijklmnopqrstuvwxyz";
        String word="banana";
        char letterArray[]=letter.toCharArray();
        int length = word.length();
        int count = 0;
        int index = 0;
        for (int i=0;i<26;i++) {
        while (index < length) {
            if (word.charAt(index) == letterArray[i]) {
                count++;
            }
            index++;
        }
        System.out.println("Letter " + letterArray[i]+ " appeared "
                + count+ " times");
    }
   }
 }

Output:
Letter a appeared 3 times
Letter b appeared 3 times
Letter c appeared 3 times
Letter d appeared 3 times
Letter e appeared 3 times
Letter f appeared 3 times
Letter g appeared 3 times
Letter h appeared 3 times
Letter i appeared 3 times
Letter j appeared 3 times
Letter k appeared 3 times
Letter l appeared 3 times
Letter m appeared 3 times
Letter n appeared 3 times
Letter o appeared 3 times
Letter p appeared 3 times
Letter q appeared 3 times
Letter r appeared 3 times
Letter s appeared 3 times
Letter t appeared 3 times
Letter u appeared 3 times
Letter v appeared 3 times
Letter w appeared 3 times
Letter x appeared 3 times
Letter y appeared 3 times
Letter z appeared 3 times

A: You never reset your counter and index variables :
for (int i=0;i<26;i++) {
  index = 0; // added
  counter = 0; // added
  while (index < length)  {
      if (word.charAt(index) == letterArray[i]) {
          count++;
      }
      index++;
  }
}

That said, this implementation is very inefficient. You can count all occurrences in a single for loop.
countArray[0] will count the occurrences of 'a', countArray[1] will count the 'b's, and so on.
String word="banana";
int countArray[]=new int[26];

for (int i = 0; i < word.length(); i++) {
    countArray[word.charAt(i) - 'a']++;
}
for (int i = 0; i < countArray; i++) {
    System.out.println("Letter " + (char)('a' + i) + " appeared " + countArray[i] + " times");
}

A: You are not resetting index and count.So it is showing results obtained for a only.

A: You have to reset index to 0 once you left the inner loop. Same with count. Otherwise he only runs the inner loop once for the letter A and then never again, because the condition in the while isn't fulfilled.
Edit: efficient solution
int[] letterOccurences = new int[26];
for (int i = 0; i < letterOccurences.length; i++) {
     letterOccurences[i] = 0;
}
for (int i = 0; i < word.length(); i++) {
     letterOccurences[letter.charAt(i) % 97]++;
     // 'a' % 97 will return 0, 'b' % 97 will return 1 and so on.
     //Thus, in 0 the count of 'a's, in 1 the count of 'b's and so on will be tracked.
}


text:
Q: Is it possible to release memory before starting an Activity? I have an activity that some times OutOfMemory exception occurs in some parts of it when data is large. It occurs some times in decryption. Some times in decompress and some times in calling web service method.
Is it possible to release Activity's memory or application's memory before doing my operations?

A: When using bitmaps, you can recycle them. Set objects to null, so the chance they get recycled is larger. Try and call System.gc() . All these methods might result in freeing up some memory. I hope this helps.

A: It is not completely clear what you mean by "release"ing an "Activity's memory", but the answer is probably no.  Instead if you are using bitmaps for instance you should be displaying them efficiently.  Check out this guide from Google on how to display bitmaps efficiently.


text:
Q: Python как постоянно выводить текст/выполнять действия Пусть мне необходимо, чтобы основная часть кода выполнялась постоянно
while 1==1:
    print (int(input ('square: '))**2)

Но при этом код также выводил на экран текст/делал какое-то действие каждые 3 секунды
Как это осуществить?
Пример выводимого результата:
>>>square:2
>>>4
>>>square:
>>>do_something
>>>square:
>>>do_something #"do_something" должно выводиться каждые 3 секунды
>>>square:6
>>>36
>>>square:
>>>do_something

Заранее спасибо

A: Как я понял, вам необходимо параллельно при работе главной программы ещё что-то выводить. В таком случае решение:
from multiprocessing import Process
import time

def printer():
    while True:
        print("Working...")
        time.sleep(3)

def main():
    while True:
        print (int(input ('square: '))**2)

if __name__ == "__main__":
    subproc = Process(target=printer)
    subproc.start()
    main()

Обратите внимание, что для использования multiprocessing.Process конструкция if __name__ == "__main__": обязательна. Если же вам необходимо выводить значение какой-то переменной, которая меняется со временем в главной программе, то необходимо почитать обмен объектами между процессами.

A: Простой способ просто печатать раз в 3 секунды
import time
last_time = time.time() # вернет unixtime, то есть секунды
interval = 3
while True:
#     ... тут ваш основной код
# ...

# дальше код того, что выводится раз в 3 секунды
    current_time = round(time.time())
    if current_time > last_time + interval:
        print ("do_something")
        last_time = current_time

A: Всё-таки да. Меня убедили, что конкретно для этой задачи лучше использовать потоки
from threading import Thread
import time

def printer():
    while True:
        print("Working...")
        time.sleep(3)

def main()
    while True:
        print (int(input ('square: '))**2)

if __name__ == "__main__":
    #daemon=True чтобы поток завершился вместе с программой
    thread = Thread(target=printer, daemon=True)
    thread.start()
    main()


text:
Q: Type bound is not inferred via constructor when using a Class parameter? Trying to understand why Java behaves differently in inferring the type and checking the type bounds when passing in type information using Class parameter.
With this code as an example:
public class TypeTest<T extends Number> {
    Class<T> type;

    TypeTest(Class<T> type) { this.type = type; }

    static <S extends Number> void sMethod(Class<S> type) {}

    <S extends Number>  void method(Class<S> type) {}

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        // 1.
        TypeTest<Integer> obj = new TypeTest(Object.class);  // compiles, unchecked call and assignment warnings

        // 2.
        obj.method(Object.class); // compile-time error, S not within bound

        TypeTest obj1 = new TypeTest(Object.class);  // compiles, unchecked call and assignment warnings

        // 3.
        obj1.method(Object.class); // compiles, unchecked call warning .

        // 4.
        TypeTest.sMethod(Object.class); // compile time error, Object not within bounds

        // 5.
        new TypeTest<Object>(Object.class); // compile time error, Object not within bounds
    }

}

With static method (4.) we cannot pass in anything that is not a Number which seems the most natural behavior with the bounds provided.
However with a constructor (1., 5.) we have to specify the type parameter explicitely to get the same behavior as 4. Otherwise it seems T type parameter value is not inferred automatically from the Object.class variable.
Where does this difference comes from for constructor and static methods?
Another case which I do not understand completely is the difference between 2. and 3. Why the same operation compiles or does not compile only depending on the way of construction of the TypeTest object, while class type parameter T has no relation whatsoever to the method type parameter S?

A: new TypeTest(Object.class) is an expression of the raw type TypeTest, that's how it is designed. So of course, no type inference is done as there is no type to infer.

A: When you omit a type parameter for a generic type -- that is, any time you type TypeTest without a <Something> -- Java ignores all generic checking for all of that type.
See http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html for details.

A: Only generic types declared for a method or constructor can be inferred. So
<S> void method() {}
 ^ this can be inferred

<S> TypeTest() {}
 ^ this can be inferred

The generic type of a generic class cannot be inferred when constructing it:
class TypeTest<T> {}
               ^ this must be specified explicitly when using "new TypeTest"
                 or in Java 7 you can explicitly specify the diamond operator

As others have mentioned, when you use new TypeTest() without any angle brackets, you are using a raw type. Raw types must work the same way that they worked prior to Generics, to preserve compatibility with old code. So the expression new TypeTest() will have type TypeTest (the raw type), not TypeTest<something>.


text:
Q: How OpenCL memory transfer functions work? I have a couple of questions, related to OpenCL memory transfer functions. I faced many questions, related to this, but to none of them extended answers were given. Probably we can collect here the overall answer.
This is my current view on three current ways of moving data:
1) enqueueReadBuffer/enqueueWriteBuffer - these two functions always copy the content of the buffer, created on the host, to the device, and from the device. No pinned memory and no DMA mechanism are used here.
2) enqueueMigrateMemObjects -  this is sometimes described as an alternative to enqueueRead/Write, but in this case, memory is copied exactly at the time of this function call. No pinned memory and no DMA mechanism are used here.
3) enqueueMapBuffer/enqueueUnmapBuffer - here always pinned memory and DMA mechanism are used.
This function uses two types of buffers: created with CL_MEM_USE_HOST_PTR flag or CL_MEM_ALLOC_HOST_PTR flag. With the first one, we map an array, created on the host, to the array, created on the device. With the second array is allocated on the device and maps it to the newly created array on the host.
This is what I can state according to the documentation. I ran several tests but only saw that migration function is faster than reading/writing.
Regarding these three paragraphs I have some questions:
1) If these functions do only copying, then why here https://software.intel.com/en-us/forums/opencl/topic/509406 people talk about pinning/unpinning memory during reading/writing? Under which conditions do these functions use pinned memory? Or this is just the feature of intel implementation, where ALL memory transfer related functions use pinned memory and DMA?
Also, does it mean, that if I use pinned memory, then the DMA mechanism will work? And vice versa - if I want to have DMA working, I need pinned memory?
2) Is this migration function - exactly what happens inside enqueueRead/WriteBuffer functions without some additional overhead, which these enqueuRead/writeBuffer functions give? Does it always just copy or also does DMA transfer?
For some reasons, some sources when talking about DMA transfer, use "copy", "memory", "migration" word for transferring the data between two buffers ( on the host and on the device). However, there cannot be any copy, we just write directly to the buffer without any copy at all. How should I treat this write during DMA?
What will happen, if I will use enqueueMigrateMemOjects with buffers, created with flag CL_MEM_USE_HOST_PTR?
3) With these two functions, there is total confusion. How the mapping and reading/writing will happen, if I use: a) existing host pointer or b) newly allocated host pointer?
Also here I do not properly understand how the DMA works. If I mapped my buffer on the host side to the buffer on the device side, with the help of which functions the memory is transferred between them? Should I always unmap my buffer after?
There is no explanation anywhere for this, like:" When we create a new buffer with this flag and use this memory function transfer, the data is transferred this way and such features as... are used. If the memory is created as read-only, this happens, if the memory if write only - this".
Maybe there is already a good guide for this, but from the OpenCL specification, I cannot answer my questions.

A: 1) DMA is used in all data transfer commands, but it works only on pinned memory regions. Otherwise OS would just page it out and give false data.
In enqueueReadBuffer/enqueueWriteBuffer, data first goes to an internal buffer which is already pinned (or pinned just in time, I don't know) then it goes to GPU memory using DMA. Because GPU can send or receive data in pages like sizes of integer-multiple of 4096 with starting address of multiple of 4096 etc (depends on vendor's alignment rules). ReadBuffer and WriteBuffer can be slower since it does two copies, one from host array to internal array then internal pinned array to gpu buffer.
In enqueueMapBuffer/enqueueUnmapBuffer, it can directly do DMA transfers efficiently because it flushes pages that are only used from host side (where you write to your host array but since it is mapped, it is uploaded to a gpu buffer) because it temporarily pins the region, only once.
Using CL_MEM_ALLOC_HOST_PTR or CL_MEM_USE_HOST_PTR can only be an optimization to skip the internal (pinned)array copying step but make sure they fit the requirements. It is not guaranteed to get pinned array always, they are a rather scarce resource. Pinned means that OS will not page it out anytime. You may also just "touch" to first byte of a page(4kB?) region of a buffer to fake "pinning" (before calling data transfer functions) but it is not legal and may not always work. But I observed speedups in my OpenCL applications with just giving a good offset and a good size to copy(like 4k aligned and 64k sized) on USE_HOST_PTR flagged buffers. (tried only on AMD, NVIDIA GPUs and Intel IGPU but can't say anything about a Xeon Phi device)
You need pinned memory only to skip extra copy overheads. You need map/unmap to optimize pinning.
2) Migration function migrates a GPU buffer's ownership to another GPU. If you use it on same GPU, it shouldn't be making anything useful besides copying itself to RAM then copying itself back again. If you use CL_MIGRATE_MEM_OBJECT_- CONTENT_UNDEFINED  then it doesn't copy data. Just moves the ownership to other device. Then you can do the data copying yourself(if you mean the wanted data is on the host, not the source device)
Some implementations copy its data through directly pci-e (I don't know if this uses GPU1 DMA to GPU2 DMA but I guess yes) and some implementations go through RAM using double DMA operations (but it can be optimized by pipelining to some extent?)

What will happen, if I will use enqueueMigrateMemOjects with buffers,
  created with flag CL_MEM_USE_HOST_PTR?

I didn't try but guess that it will move only the ownership since data is only on host. Also the Intel link you gave includes someone saying that "migration triggers DMA operation". Maybe two Intel Xeon Phi's, by default, communicate with DMAs rather than going through system RAM, when migration between two Phis is used.
3) CL_MEM_USE_HOST_PTR is meant to work with your application's pointers. They can be anything, even a pinned one(but outside of OpenCL's internal rules, which may be not good always). CL_MEM_ALLOC_HOST_PTR is meant to use OpenCL implementation's pinned memory, if it can. If you use only CL_MEM_READ_WRITE then it is on the device memory. Working with CL_MEM_USE_HOST_PTR and CL_MEM_ALLOC_HOST_PTR means OpenCL kernel will do zero-copy access if it is sharing RAM directly with CPU(if device is iGPU, for example).  Without pinning, extra copy. With pinning, iGPU does no copy. Very big difference. But for a discrete GPU(or a compute card like Xeon Phi), it could be somewhere between 1.0x and 2.0x the speed of extra copy version (considering host-to-host and host-to-device copies have similar bandwidths).
Mapping means host-side mapping. Host sees device memory "mapped" to its own. So device can't access it(by kernel for example). Writing means host-side writing. Host writes to GPU memory. Reading means host reading. Host reads from GPU memory. So, map unmap happens like this:
CL_MAP_WRITE_INVALIDATE_REGION version:

*

*you map a host pointer (returned by map command) to device buffer

*

*now buffer ownership is on host

*use a GPU buffer as if it is this host pointer

*unmap the region so it flushes latest bits to GPU memory (or, no-op if it is iGPU!!)

*

*now buffer ownership is on device

there is also another (CL_MAP_WRITE) usage

*

*you prepare the data beforehand

*map (with initial copy enabled) (gets all data) // extra overhead

*optional element "updates"

*unmap

*now data (with optional updated) is on GPU memory

*so that OpenCL kernel function can use it as a parameter

Between map and unmap, it can flush any host input you feed there into GPU memory because it pins whole region at once. Otherwise it would (as in enqueueWriteBuffer) need to pin-unpin any current data(like a single integer) (with its whole page) being sent to GPU and it would be slow.
When you copy a 1GB buffer, memory consumption doesn't reach up to 2GB. It handles the pin-unpin-extra-copy operations on a smaller internal array, something like 64kB but depends on vendor implementation of OpenCL.
But on enqueueWriteBuffer, it uses an inner-buffer to do necessary copying and also pinning. Both pinning and unpinning and doing extra copying makes enqueueWriteBuffer slower but you can still try giving it a properly aligned host pointer and properly sized region to do the copy faster. At least this would let it do the pinning only once for whole array in the background. Perhaps even skips the extra copy if implementation has the optimization.


text:
Q: Does it make sense to write the complex plane as the cartesian product between $\mathbb{R}$ and $i\mathbb{R}$? Note: this question is inspired by someone (a teacher long time ago) who drew and labeled the two axes of the standard complex plane as $\mathbb{R}$ and $i\mathbb{R}$.
Let $i\mathbb{R} = \{iy| y\in \mathbb{R}, i \text{ is the imaginary unit}\}$
Does it make sense to write the complex plane $\mathbb{C}$ as:
$\mathbb{C} = \mathbb{R} \times i\mathbb{R}$?
Doing so, gives me that,
$\mathbb{C} = \{(x,iy)| x \in \mathbb{R}, iy \in i\mathbb{R}\}$
But then again, the complex plane is usually defined as:
$\mathbb{C} = \{z| z = x+iy, x \in \mathbb{R}, y \in \mathbb{R}\}$
How to resolve these two seemingly different definitions?

A: It makes perfect sense to define $\mathbb{C}$ in terms of $\mathbb{R} \times \mathbb{R}$, with addition defined by
$$(a, b) + (c, d) = (a + c, b + d)$$
and multiplication defined by
$$(a, b)(c, d) = (ac - bd, ad + bc).$$
Structurally, this is absolutely identical to any of the other definitions of complex numbers. If you're happy to abuse notations and notate such pairs of the form $(a, 0)$ by the real number $a$, and denote by $i$ the element $(0, 1)$, then $(a, b) = a + ib$ for any $a, b \in \mathbb{R}$.
So, how do we resolve the difference between this and other definitions? Well, we take the view that it doesn't matter. Whether you view complex numbers as matrices of the form $\begin{pmatrix} x & -y \\ y & x \end{pmatrix}$, or as elements of the splitting field $\mathbb{R}[x]/\langle x^2 + 1 \rangle$, or as ordered pairs from the definition above, the fact is that all of them produce an identical structure, and it is very simple to change between them in a way that respects addition and multiplication.
(FYI, I didn't define $\mathbb{R} \times i\mathbb{R}$, because, before defining complex numbers, it's not clear what $i$ actually is. Sure, you can say it's the square root of $-1$, but that only shows the property it's supposed to satisfy, not what it really is, or what context it can be well-defined.)

A: As points, it makes sense. As additive groups, it makes sense. But there is no natural multiplication on $\Bbb R\times i\Bbb R$ because the multiplication on $i\Bbb R$ isn't closed (it is not a ring, at least not with the standard multiplication). And even if there were, the multiplication in $\Bbb C$ is not isomorphic to the natural multiplication of any (non-trivial) direct product of rings.
As for how to reconcile the seemingly different definitions where they do make sense, you apply the "obvious" bijections / isomorphisms.


text:
Q: Existence of conformal equivalence between doubly connected domain and annulus The following math overflow post
https://mathoverflow.net/questions/261535/mapping-the-doubly-connected-domain-to-an-annulus
provides a sketch proof of the fact that any (non-degenerate) doubly connected domain is conformally equivalent to an annulus (with outer radius 1).
To construct the holomorphic bijection the proof apparently uses (in the last lines) the logarithm as a multivalued function ( no holomorphic branch can be defined on the doubly connected region).
I can convince myself that the candidate conformal equivalence is indeed a function but find it difficult to verify holomorphy ( as one is composing with a set valued function). Any ideas on how to proceed? Many thanks!


text:
Q: When add a column to a data.table, what's then best way to add if else conditions? For example, I would like to do something like:
 dt[isFlag, newCol:= A]
 dt[!isFlag, newCol:=B]

Or should I do this?
 dt[, newCol:= B]
 dt[isFlag, newCol:=A]

Or this?
 dt[, newCol:= if (isFlag) then A else B] # this only works if isFlag is a scalar

Or
dt[, newCol:= ifelse(isFlag, A, B)] # this only works if isFlag is a vector

What is the best way?


text:
Q: How to get cookies from a c++ code I'm trying to make my MFC application access a login screen from a website (like Spotify does), the idea is that after the user log in the site will redirect him to another page with a cookie.
I'm using a derived CDHtmlDialog class and "getting" the redirect inside the OnNavigateComplete method but the IHtmlDocument2Ptr (m_spHtmlDoc)is always null.
void CDHtmlDlgPersonalizado::OnNavigateComplete(LPDISPATCH pDisp, LPCTSTR szUrl)
{
    this->GetDHtmlDocument(&this->m_spHtmlDoc);

    if (this->m_spHtmlDoc != nullptr)
        this->m_spHtmlDoc->get_cookie(bstr);
}

How can i get a cookie from my c++ code?
EDIT: The GetDHtmlDocument returns E_NOINTERFACE inside the OnNavigateComplete and OnDocumentComplete.
The navigation to the login screen is made inside the OnInitDialog method:
BOOL CDHtmlDlgPersonalizado::OnInitDialog()
{
    CDHtmlDialog::OnInitDialog();

    CString str(_T("http://www.MyLoginScreen.com/"));
    this->Navigate(str);

    return TRUE;
}

This code is called inside a CDialogEx derived class:
BOOL CDlgMsgBoxHtml::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    VERIFY(this->m_HtmlCtrl.SubclassDlgItem(IDC_HTML, this));

    /*m_HtmlCtrl is the object to the CDHtmlDialog derived class*/

    this->m_HtmlCtrl.OnInitDialog();

    /*I also tried calling the navigate here*/
    //CString str3(_T("http://www.MyLoginScreen.com/"));
    //this->m_HtmlCtrl.Navigate(str3);

    /*But got the same results*/

    //IHTMLDocument2Ptr spHtmlDoc = nullptr;
    //this->m_HtmlCtrl.GetDHtmlDocument(&spHtmlDoc);

    return TRUE;
}

Thanks in advance and sorry for my bad English.


text:
Q: Working with Git, Svn and Eclipse Together I am trying to find the right way to do this. My firm is using SVN as we are working on the projects to do checkin and checkouts. But I am thinking about using Git to backup all my work as I got home.. here is why
From Home I don't have access to my firms SVN Repo so I was thinking about setting up a Git Repo on the internet to checkin all my work into git before I leave work so I can access it from home.
I would like to hear if others are doing this and if you think this is a good practice.
How would I do this?  I been using SVN and Eclipse for sometime now but I hear GIT would be better for cloning my workstation...

A: The solution to this for many people is 'git svn'. It allows you to create a local git repo as a clone of a tree in svn, work locally, and commit your work back to svn.
You can run git svn while at work, copy the resulting repo to a disk you carry home, and then commit back to svn when you get back to work. Always assuming, of course, that your employer's policies permit this. If you can't get to svn from home, perhaps they don't like anything about this idea.


text:
Q: What do packed_to_unpacked blocks do in GNU RADIO? Could somebody give me an example(e.g. input->output) of what this block does? Explanation is also appreciated.

A: From the official documentation (which, if your GNU Radio build is intact, you can also access from the documentation tab of your block properties in GRC):

Convert a stream of packed bytes or shorts to stream of unpacked bytes or shorts.
input: stream of unsigned char; output: stream of unsigned char
This is the inverse of gr::blocks::unpacked_to_packed_XX.
The bits in the bytes or shorts input stream are grouped into chunks of bits_per_chunk bits and each resulting chunk is written right- justified to the output stream of bytes or shorts. All b or 16 bits of the each input bytes or short are processed. The right thing is done if bits_per_chunk is not a power of two.
The combination of gr::blocks::packed_to_unpacked_XX_ followed by gr_chunks_to_symbols_Xf or gr_chunks_to_symbols_Xc handles the general case of mapping from a stream of bytes or shorts into arbitrary float or complex symbols.

so, you get a byte in, consisting of 8 bits, and you produce bytes, each of one with bits_per_chunk bits set according to the input. Example (let bits_per_chunk=1, MSB first):
in 0b11110000
out 0b00000001 0b00000001 0b00000001 0b00000001 0b00000000 0b00000000 0b00000000 0b00000000


text:
Q: How do I profile using jprofiler on remote linux server while my GUI in on windows OS? I am trying to profile my remote linux server using JProfiler. I am trying to seek for a line of code which I need maybe to implement it inside my startup.sh script of this app.
any help would be great!
Erez

A: In your local JProfiler GUI, invoke
Session->Integration Wizards->New Remote Integration
and follow the steps in the wizard.


text:
Q: Change image route to external link I have a route that returns a FileResult with an image.
View:
<img src="@Url.RouteUrl("HomeProductImage", new { id = Model.ProductId })" />

Route to the action:
routes.MapRouteLowercase("HomeProductImage", "{id}.jpg", new { controller = "Home",
    action = "ProductImage", id = "" }, new { id = @"\d+" });

public FileResult ProductImage(int id)
{
     // ...
     return File(filename, "image/jpeg");
}

How can I change the route, to get an image from another domain, without changing the View?
Eg. instead of domain.com/product/123.jpg -> otherDoamin.com/product/123.jpg

A: It's not possible, you should instead write a helper method that returns the full url for your image.
public static MvcHtmlString ImageUrl(this HtmlHelper html, string imageName)
{
    return String.Format("http://somedomain.com/path/to/image/{0}", imageName);
}


text:
Q: String array getter Method with for loop I got a simple getter Method for a String Array. The Problem is, that the method return just one element instead of all 6.
Here is the Code:
    public String names() {

   String[] strings = new String[]{

            "name 1",
            "name 2",
            "name 3",
            "name 4",
            "name 5",
            "name 6"

    };

    for (int i = 0; i < strings.length; i++) {
        return strings[i];

    }
    return null;
}

The returned element is always the first one.. Can somebody explain me, why is doesn't return the whole array?

A: Issue is over here :
for (int i = 0; i < strings.length; i++) {
    return strings[i];
}

For when for loop starts, it initialises i to 0 and i < your length of string array so it enters loop and returns strings[0].

A: At the first iteration of the loop, when i equals 0, the method exits executing return strings[0], which is name1.
If you want to return the whole array, you do not need a loop, simply do return strings.

A: because you are return first element.you can't return all throw the array in this way.because when you return it exit from method retuning first value
if you want to return all
then use following code. make sure return type is String[]. instead String
public String[] names() {

   String[] strings = new String[]{

            "name 1",
            "name 2",
            "name 3",
            "name 4",
            "name 5",
            "name 6"

    };

    return strings;
}

A: You want to change the return type of the method to String[], and, instead of making a loop, just return strings


text:
Q: Method or data member not found. when debug it will shows - method or data member not found and will highlight at .cell. may i know why with that error?
i already change the cells to cell. but still did not work.
i am stil new in VBA, i already searched a few website or any suggestion, but still its hard for me to understand and not really clear.
Any help would be very much appreciated.
Thanks
Private Sub cmdAdd_Click()
'dimention the variable
Dim DataSH As Worksheet
Dim Addme As Range
Dim str As String
Dim totalRows As Long

'set the variable
Set DataSH = Sheet1
'error handler
On Error GoTo errHandler:
'set variable for the destination
Set Addme = DataSH.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'hold in memory and stop screen flicker
Application.ScreenUpdating = False
If Me.txtName = "" Or Me.cboAmount = "" Or Me.cboCeti = "" Then
MsgBox "There is insufficient data, Please return and add the needed information"
Exit Sub
End If
'determine worksheet row to post data
totalRows = Sheet1**.Cell**(Rows, Count, "A").End(xUp).Row
If totalRows < 3 Then
totalRows = 3
Else
totalRows = totalRows
End If
'send the values to the database
Sheet1.Cell(totalRows + 1, 1) = txtName.Text
If cbWhatsapp.Value = True Then
str = "Whatsapp, "
End If
If cbSMS.Value = True Then
str = str & "SMS, "
End If
If cbEmail.Value = True Then
str = str & "Email, "
End If
If cbFacebook.Value = True Then
str = str & "Facebook, "
End If
If cbPhoneCall.Value = True Then
str = str & "Phone Call, "
'deleting comma and space, the 2 characters at the end of str
str = Left(str, Len(str) - 2)
Sheet1.Cell(totalRows + 1, 2) = str
If optYes.Value = True Then
Sheet1.Cell(totalRow + 1, 3) = "Yes"
ElseIf optNo.Value = True Then
Sheet1.Cell(totalRows + 1, 3) = "No"
End If
Sheet1.Cell(totalRows + 1, 4) = cboAmount.Value
Sheet1.Cell(totalRows + 1, 5) = cboCeti.Value
Sheet1.Cell(totalRows + 1, 6) = txtPhone.Text
Sheet1.Cell(totalRows + 1, 7) = txtEmail.Text
'sort the data by "cboCeti"
DataSH.Select
With DataSH
.Range("A2:G10000").Sort Key1:=Range("E2"), Order1:=xlAscending, Header:=xlGuess
End With

A: *

*Add Option Explicit to the very top of your code

*Add Option Explicit to the very top of your code

*You are not fully qualifying your objects. Use the variable ws as seen in code to properly qualify your objects

*You are using Cell when you should be using Cells

*You had some typos where you used totalRow instead of totalRows

*Properly indenting your code goes a long way. Namely with readability, making your code easier to update in future, and making your code easier to de-bug since it is easier to follow

Option Explicit would have caught errors 4 and 5 and brought them right to your attention by highlighting the undeclared (typo) variables and other compile errors.

Option Explicit

Private Sub cmdAdd_Click()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim Addme As Range, str As String, totalRows As Long

Set Addme = ws.Cells(ws.Rows.Count, 1).End(xlUp).Offset(1, 0)

Application.ScreenUpdating = False

If Me.txtName = "" Or Me.cboAmount = "" Or Me.cboCeti = "" Then
    MsgBox "There is insufficient data, Please return and add the needed information"
    Exit Sub
End If

totalRows = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
totalRows = Application.WorksheetFunction.Max(totalRows, 3)

ws.Cells(totalRows + 1, 1) = txtName.Text

If cbWhatsapp.Value = True Then
    str = "Whatsapp, "
End If

If cbSMS.Value = True Then
    str = str & "SMS, "
End If

If cbEmail.Value = True Then
    str = str & "Email, "
End If

If cbFacebook.Value = True Then
    str = str & "Facebook, "
End If

If cbPhoneCall.Value = True Then
    str = str & "Phone Call, "
End If

str = Left(str, Len(str) - 2)
    ws.Cells(totalRows + 1, 2) = str

If optYes.Value = True Then
    ws.Cells(totalRows + 1, 3) = "Yes"
ElseIf optNo.Value = True Then
    ws.Cells(totalRows + 1, 3) = "No"
End If

ws.Cells(totalRows + 1, 4) = cboAmount.Value
ws.Cells(totalRows + 1, 5) = cboCeti.Value
ws.Cells(totalRows + 1, 6) = txtPhone.Text
ws.Cells(totalRows + 1, 7) = txtEmail.TextG1

ws.Range("A2:G10000").Sort Key1:=Range("E2"), Order1:=xlAscending, Header:=xlGuess

End Sub


text:
Q: Problem about SpringLayout in java 1.4.2 public static void main(String[] args) {
    // TODO code application logic here
        JFrame frame = new JFrame();

        SpringLayout layout = new SpringLayout();
        frame.getContentPane().setLayout(layout);
        TitledBorder border = null;
        border = BorderFactory.createTitledBorder("Group1");
        frame.setSize(620, 620);

        JPanel mainPanel = new JPanel();
        mainPanel.setBorder(border);
        //mainPanel.setPreferredSize( new Dimension(600,600));
        layout.putConstraint(SpringLayout.EAST, mainPanel, -15, SpringLayout.EAST, frame.getContentPane());
        layout.putConstraint(SpringLayout.WEST, mainPanel, 15, SpringLayout.WEST, frame.getContentPane());
        layout.putConstraint(SpringLayout.SOUTH, mainPanel, -15, SpringLayout.SOUTH, frame.getContentPane());
        layout.putConstraint(SpringLayout.NORTH, mainPanel, 15, SpringLayout.NORTH, frame.getContentPane());

        frame.getContentPane().add(mainPanel);
        frame.setVisible(true);
}

i am working on the effect with a panel auto-resize along with its parents while its parent resized in java 1.4.2.
I used the SpringLayout to do this, but i found that if i define the SpringLayout.East and SpringLayout.South after the WEST and NORTH, the panel (mainPanel) will not posit at (15,15). It will do if EAST and NORTH are defined in front of WEST and SOUTH.
Why is that?

A: As noted in this related question, the order of constraint specification may be important, particularly if the resulting layout is over-constrained. The order WEST, NORTH, EAST, SOUTH is an example that causes a reset, mentioned in the "Work Around Evaluation" section of a related bug report.


text:
Q: Issues printing the class, name and accuracy score of the voting classifier I would like to train a voiting classifer in SciKit-Learn with three different classifiers. I'm having issues with the final step, which is printing the final accuracy scores of the classifiers.
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

import pandas as pd
import numpy as np

log_clf=LogisticRegression()
rnd_clf=RandomForestClassifier()
svm_clf=SVC()

voting_clf=VotingClassifier(estimators=[('lr',log_clf),('rf',rnd_clf),('svc',svm_clf)],voting='hard')
voting_clf.fit(X_train, y_train)

I am getting errors when I run the following code:
for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_predict=clf.predict(X_test)
    print(clf._class_._name_,accuracy_score(y_test,y_pred))

When I run this chunk of code I get the following:
AttributeError: 'LogisticRegression' object has no attribute '_class_'

I am assuming that calling 'class'is a bit outdated, so I changed class to 'classes_':
for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred=clf.predict(X_test)
    print(clf.classes_._name_,accuracy_score(y_test,y_pred))

When I run this chunk of code I get the following:
AttributeError: 'numpy.ndarray' object has no attribute '_name_'

When I remove 'name' and run the following code, I still get an error:
for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred=clf.predict(X_test)
    print(clf.classes_,accuracy_score(y_test,y_pred))

Error:
 NameError: name 'accuracy_score' is not defined

I'm not sure why accuracy_score is not defined seeing that imported the library

A: For the first error about class, you need to have two underscores here.
Change
print(clf._class_._name_,accuracy_score(y_test,y_pred))

to:
print(clf.__class__.__name__, accuracy_score(y_test,y_pred))

See this question for other ways to get the name of an object in python:

*

*Getting the class name of an instance?
Now for the second error about 'accuracy_score' not defined, this happens when you have not imported the accuracy_score correctly. But I can see that in your code you have imported the accuracy_score. So are you sure that you are executing the line print(clf.__class__.__name__, accuracy_score(y_test,y_pred)) in the same file? or in any different file?


text:
Q: Divs in stack and filling parent div I have next case:

Some content

Another content

There are two requirements:
1) Each of the child should be expanded to the parent's size (100%).
2) In some cases "child1" should be display for the user in other "child2".
So how I can implement this in css?

A: Created a jsfiddle for you - FIDDLE LINK
display:none and display: block are what you are looking for.
All child divs are hidden by default (#parent div { display: none; }). The child you want shown (in this case #child2) is given display:block to unhide. display: block; also enables the child to have a height of 100%.
As some helpful people have pointed out, you would possibly need to use some PHP/javascript/jQuery depending on what you are trying to achieve. Are you using something like PHP or jQuery currently?
HTML

Child 1

Child 2

CSS
#parent {
   width: 400px;
   height: 300px;
   background: #F00;
}

#parent div {
   background: #CCC;
   height: 100%;
   display: none;
}

#parent #child1 {
   display: none;
}

#parent #child2 {
   display: block;
}

A: Try this:
#parent div {
   min-width: 100%;
}

Now, there are two options for hiding the divs.

*

*You do this on the server side.

*You use JS to hide the div on the client side.
CSS won't hide the elements on a condition. Unless the condition is the screen related property.
Server side:
if(condition == value) {
   /* write the code for the div here */
} else {
   /* don't write the div code on the first place. */
}

Client side is same, use JS and the same condition block of the if else and then show hide it.
Hint for hiding the div,
document.getElementById("child1").style.display = "none";
document.getElementById("child1").style.display = "block"; // for showing..


text:
Q: Replace part of a string in sqlite I recently moved my mp3 library to my home folder, and this caused banshee to forget my file data (such as rating, ect).  If I can update the file path in banshee's sqlite table, I can get restore my user-entered file data.
sqlite stores path data in a Uri field of the CoreTracks table.
Example:
Uri
file:///storage/Music/mp3/Genre/Artist/Album/Track.mp3

I'd like to change all instances to
file:///home/user/Music/mp3/Genre/Artist/Album/Track.mp3

Is there a safe way of changing just the first 15 characters of data contained in the Uri field?

A: Create the database backup. Then use the sqlite.exe command line shell. open your database like this:
sqlite rating.sqlite
> UPDATE CoreTracks SET Uri = 'file:///home/user' + substr(Uri, 17);
>

At the end press Ctrl-D to finish the sqlite console. I think I counted the characters correctly. Please double check if value 17 needs to be changed to something else


text:
Q: Run update on multiple tables in BigQuery I have lake dataset which take data from a OLTP system, with the nature of transactions we have lot of updates the next day, so to keep track of the latest record we are using active_flag = '1'.
We also created a update script which retires old records and updates active_flag = '0'.
Now the main question: how can i execute a update statement by changing table name automatically(programmatically).
I know we have a option of using cloudfunctions but it'll expire in 9 mins and I have atleast 350 tables to update.
Has anyone faced this situation earlier??

A: You can easily do this with Cloud Workflows.
There you setup the template calls to Bigquery as a substeps, and then you pass a list of tables, and loop through the items and invoke the BigQuery step for each item/table.
I wrote an article with samples that you can adapt: Automate the execution of BigQuery queries with Cloud Workflows


text:
Q: How can I get Google Chat and Gmail notifications without having Chrome open? I bought an old laptop from a friend recently, and I've been trying to get it up and running with all the services that I'd like to use.  One of these is Google Chat/Gmail.  However, the laptop isn't very powerful, and I'd rather not have to keep Chrome open all the time to get chat and mail notifications.
Basically, what I want is the old Google Talk app, but Google seems to have dropped support for that, and I can't find anywhere that I can download it.  Hangouts sort of works, but the Hangouts app requires a Chrome process to be running, and it doesn't seem to give me mail notifications.
Is there a simple way for me to get Google Chat and Gmail notifications without running Chrome constantly?
My laptop's system specs are:

*

*Windows 7 32-bit

*AMD Turion(tm) 64 Mobile Technology MK-36, ~2.0GHz

*2048MB RAM

A: Gmail Notifier (http://www.gmailnotifier.com/download/) SEEMS to do what you want. (never used, just googled)  It's an .exe and the requirements page lists only a Win xp or better, not Chrome.
That plus Hangouts might get you were you wanna be.


text:
Q: Scheduling Conflict: can only detect conflict with exact time This is the last problem I have to face in for my capstone project, and it's driving me nuts.
Basically, I have to be able to identify if Section/Faculty/Room are all in use when scheduling a subject, to avoid conflicts.
Here's what I've worked on, but so far it can only detect when Room is in use.
I can't figure out how to be able to prevent scheduling that's in-between time periods. For example: First entry would be 7-8:30AM. Second entry would be 7:30 AM to 9 AM. With the former existing, it should reject the latter but I can't figure out how to do that. This is what I've cooked up so far. How would you guys go about this?
Public Function DataInUse() As Boolean
    Dim Temp As Boolean
    Temp = False

    If FacultyInUse() = True Then
        MessageBox.Show("Faculty in use.")
        cboFaculty.Focus()
        DisplayFacultyInUse()
        DisplayLabelConflictForFaculty()
        Temp = True

    ElseIf RoomInUse() = True Then
        MessageBox.Show("Room in use.")
        cboRoom.Focus()
        DisplayRoomInUse()
        DisplayLabelConflictForRoom()
        Temp = True
    End If
    Return Temp
End Function

Public Function FacultyInUse() As Boolean
    Dim com As New OleDbCommand(" Select * from qrySubjectOfferring Where cTimeIn >=#" & cboFrom.Text & "# and cTimeOut <=#" & cboTo.Text & "# and Faculty like'" & cboFaculty.Text & "%' and cDay Like '%" & cboDay.Text & "%'", clsCon.con)
    Dim dr As OleDbDataReader = com.ExecuteReader()
    dr.Read()
    If dr.HasRows Then
        Return True
    Else
        Return False
    End If
End Function

Public Function RoomInUse() As Boolean
    Dim com As New OleDbCommand("Select * from qryRoomAvailability WHERE (cTimeIn <=#" & cboFrom.Text & "# AND cTimeOut >=#" & cboFrom.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') OR (cTimeIn <=#" & cboTo.Text & "# AND cTimeOut >=#" & cboTo.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') OR (cTimeIn >= #" & cboFrom.Text & "# AND cTimeOut <= #" & cboTo.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') ", clsCon.con)
    Dim dr As OleDbDataReader = com.ExecuteReader()
    dr.Read()
    If dr.HasRows Then
        Return True
    Else
        Return False
    End If
End Function

Public Function SubjectAlreadyOffered(sSubject As String) As Boolean
    Dim com As New OleDbCommand("Select * from qrySubjectOfferring Where Subject LIKE '%" & sSubject & "%'", clsCon.con)
    Dim dr As OleDbDataReader = com.ExecuteReader()
    dr.Read()
    If dr.HasRows Then
        Return True
    Else
        Return False
    End If
End Function

A: Try simplifying your SQL to use Between clause and eliminate all entries where the From or To are in existing entries
In your RoomInUse() function
Dim strSQL as String

strSQL = "SELECT * FROM qryRoomAvailability WHERE " & _
    " Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "'" & _
    " AND NOT (#" & cboFrom.Text "# BETWEEN [" & cTimeIn & "] AND [" & cTimeOut & "])" & _
    " AND NOT (#" & cboTo.Text "# BETWEEN [" & cTimeIn & "] AND [" & cTimeOut & "])"

Dim com As New OleDbCommand(strSQL, clsCon.con)


text:
Q: How can I store keychain credentials for multiple Github accounts? I am running Git on OSX Mavericks and have not had issues until now. What has changed is that I'm trying to use two Github accounts on different repos on the same computer.
The problem is that the osx-keychain is storing the login information from my first account. That was terrific before, but whenever I try to commit or push from my new Github account, it is defaulting to use the keychain's username and password values, and ignoring the locally-defined git config (or even global git config!) files.
I can delete my osx-keychain, and then push to the new account, but in doing so it will create a new keychain for that account, which puts me back at square one: able to push to my secondary account with the new keychain values but locked out of my primary account.
So I'm stuck in an "either-or" situation, and I'm really hoping there's a "both" solution. Any help?
P.S. I have tried this solution, and it did not work, as the osx-keychain appeared to override the SSH Identity functionality

A: If you are using https url, then the solution you mention wouldn't have any effect: it is for multiple ssh keys.
Regarding https, this question mentions a few solutions, including:

*

*By default gitcredentials only considers the domain name.
If you want git to consider the full path (e.g. if you have multiple GitHub accounts), set the useHttpPath variable to true, as described at gitcredentials.
Note that changing this setting will ask your credentials again for each URL.

By default, Git does not consider the "path" component of an http URL to be worth matching via external helpers.
  This means that a credential stored for https://example.com/foo.git will also be used for https://example.com/bar.git.
  If you do want to distinguish these cases, set this option to true.

Also, make sure your https url incudes your account name:
git clone https://user1@github.com/auser/aprojectX
git clone https://user2@github.com/auser/aprojectY

That will help a credential helper to known which account/password it should be looking for.
Finally, the authentication you are using for accessing a git repo hosting service has nothing to do with:
git config (--global) user.name

That last config is only for setting the author associated with your local commits.
It is not for selecting the account used to access a remote hosting website.


text:
Q: How to create more than two grids on a plot in Matplotlib? I want to set 3 or more grids on a single plot.  I've seen how to customize major and minor ticks, but have no idea how (or whether it's possible) to create a third or fourth set of grids.
For instance, I would love to be able to generate a graph with multicolor grids like this colorful graph paper.
I've done the standard major/minor customization, a la:
major_ticks = np.arange(-50, 61, 5)
minor_ticks = np.arange(-50, 61, 1)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(which='minor', alpha=0.5, linewidth = 1, linestyle='--')
ax.grid(which='major', alpha=0.5, linewidth = 2)
ax.grid(which = 'both')

But what I'd really like to do is something like:
major_ticks = np.arange(-50, 61, 20)
minor_ticks = np.arange(-50, 61, 1)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

ticks_3 = np.arange(-50, 61, 10)
ticks_4 = np.arange(-50, 61, 5)

<!--- Additional code here to apply all ticks_3 and ticks_4 to the graph --->

It seems intuitive to me that an arbitrary number of objects with grid locators should be able to be instantiated, but I don't know how to access them...


text:
Q: Regex matches fine in tester but not in Python code I'd like to remove text between the strings "Criteria Details" and both "\n{Some number}\n" or "\nPage {Some number}\n". My code is below:
test = re.search(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', input_text)
print(test)
input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE)

This works on regex101 for the string below, as I can see that the chunk between "Criteria Details" and "88" is detected, but the .search() in my code doesn't return anything, and nothing is replaced in .sub(). Am I missing something?
cyclobenzaprine oral tablet 10 mg, 5 mg,
7.5 mg

PA Criteria

Criteria Details

N/A

N/A

other

N/A

Exclusion
Criteria

Required
Medical
Information

Prescriber
Restrictions

Coverage
Duration

Other Criteria

Age Restrictions  Patients aged less than 65 years, approve. Patients aged 65 years and older,

End of the Contract Year

PA does NOT apply to patients less than 65 yrs of age. High Risk
Medications will be approved if ALL of the following are met: a. Patient
has an FDA-approved diagnosis or CMS-approved compendia accepted
indication for the requested high risk medication AND b.  the prescriber
has completed a risk assessment of the high risk medication for the patient
and has indicated that the benefits of the requested high risk medication
outweigh the risks for the patient AND c.Prescriber has documented that
s/he discussed risks and potential side effects of the medication with the
patient AND d. if patient is taking conconmitantly a muscle relaxant with
an opioid, the prescriber indicated that the benefits of the requested
combination therapy outweigh the risks for the patient.

Indications

All Medically-accepted Indications.

Off-Label Uses

N/A

88

Updated 06/2020

I would expect the output to be something like
cyclobenzaprine oral tablet 10 mg, 5 mg,
7.5 mg

PA Criteria

Updated 06/2020

A: You got it, just a silly mistake. Change your code to this
input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE)
print(input_text)

Where you went wrong is
input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE) # This is the necessary replacement well done
test = re.search(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', input_text) # This extracts a pattern which will never be found because you already removed it
print(test) # The result of the previous line which would never be found

Hope this helps! We all have bad days

A: I figured it out. When using Pdfminer to parse the PDF into text, there aren't actually newlines after the page number, but they get converted into newlines if I copy and paste the output to the regex website, or Stackoverflow. I ended up using \s instead of \n to detect the trailing spaces after the page numbers.


text:
Q: How to update Column related to Row Number Is there any easy way to update Column by Row number not a PK
ex:
UPDATE contact m
SET    ContactNumber = sub.rn + 500
FROM  (SELECT Id, row_number() OVER (ORDER BY Id) AS rn FROM contact) sub
WHERE  m.Id = sub.Id;

A: The syntax for using joins in UPDATE in MySQL and MariaDB is:  UPDATE a JOIN b ON  ... SET ... WHERE ... ;. The syntax you used UPDATE .. SET ... FROM ... WHERE ... ; is used in SQL Server.
For recent versions of MariaDB that have window/ranking functions, the following will work:
UPDATE
    contact AS m
  JOIN
    ( SELECT Id, row_number() OVER (ORDER BY Id) AS rn
      FROM contact
    ) AS sub
  ON  m.Id = sub.Id
SET
    m.ContactNumber = sub.rn + 500
 ;

Tested in dbfiddle.uk

A: UPDATE contact
SET ContactNumber = (@rownum := 1 + @rownum) + 500
WHERE 0 = (@rownum:=0)
-- for a given client, for example, Client_Id=123, use
-- WHERE Client_Id = 123 + (@rownum:=0)
ORDER BY id;

A: I got the answer :)
UPDATE contact m
join
(
   SELECT Id, @rownum:=@rownum+1 rownum FROM contact
   CROSS JOIN (select @rownum := 0) rn
   order by contact.Id
) as sub on sub.Id= m.Id
set m.ContactNumber = sub.rownum + 500
where m.Client_Id=1


text:
Q: Java Android XML Resource / Referring an integer-array I'm developing a java Android app and i'm having a XML-Resource, it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- first pattern -->
    <integer-array name="pattern_a">
        <item>1</item>
        <item>0</item>
        <item>1</item>
    </integer-array>

    <!-- second pattern -->
    <integer-array name="pattern_b">
        <item>1</item>
        <item>1</item>
        <item>0</item>
    </integer-array>

    <!-- broad configuration -->
    <string        name="config_broad_name">broad</string>
    <integer-array name="config_broad_pattern">@array/pattern_a</integer-array>

    <!-- small configuration -->
    <string        name="config_small_name">small </string>
    <integer-array name="config_small_pattern">@array/pattern_b</integer-array>

</resources>

I'm creating a Configuration and set some values from my resource files, which seems easy straight forward...
public Configuration createConfiguration(){

    Configuration configBroad = new Configuration();

    String configName = getResources().getString(R.string.config_broad_name);
    int[] pattern = getResources().getIntArray(R.array.config_broad_pattern);

    configBroad.setName(configName);
    configBroad.setPattern(pattern);

    return configBroad;
}

Problem: int[] pattern is an empty int[] (like int[]{})
what would really help, something like this:
int patternId = getArrayId(getResource(), R.string.config_broad_pattern);
configBroad.setPatternId(patternId); //setting just the id, not the whole pattern

then i could retrive the value itself, or even better - set the id on my config instead of the array.
i know, there a ton's of explanations on how to work on this problem with string[] (like array_of_array) and @image/...-Arrays but i couldn't find any one with integer array (especially when looking for Typed-Array i couldn't find help)

A: OK, it took me lots of time to solve this issie...
when you want to refer to another defined value from your XML, you have to refer to that value as a STRING, at least if you follow my solution...
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- first pattern -->
    <integer-array name="pattern_a">
        <item>1</item>
        <item>0</item>
        <item>1</item>
    </integer-array>

    <!-- second pattern -->
    <integer-array name="pattern_b">
        <item>1</item>
        <item>1</item>
        <item>0</item>
    </integer-array>

    <!-- broad configuration - notice difference on reference -->
    <string        name="config_broad_name">broad</string>
    <string name="config_broad_pattern">@array/pattern_a</string>

    <!-- small configuration -->
    <string        name="config_small_name">small </string>
    <string name="config_small_pattern">@array/pattern_b</string><!-- same here -->

</resources>

of course we use that same code as above but we must slightly adjust it some places:
public Configuration createConfiguration(){

    Configuration configBroad = new Configuration();

    String configName = getResources().getString(R.string.config_broad_name);
    String refPatternName = getResources().getString(R.string.config_broad_pattern);
    refPatternName = refPatternName.replace("@",""); //removing @-prefix
    int refPatternId = Integer.parseInt(str); //this value now is the same as R.array.pattern_a

    configBroad.setName(configName);
    configBroad.setPatternId(refPatternId);

    return configBroad;
}

A: For me this is a simple question. In XML just use string-array and then in java code cast it to integer that all.


text:
Q: Numbering/Labeling images (eg 1,2,3 or A,B,C) with ImageMagick montage I'm using
montage *.tif output.tif

to combine several images to one. I would now like them to be numbered (sometimes 1,2,3 …; somtimes A,B,C …)
What possibilities are there to label the single images in the combined? Is there an option to put the label not underneath the picture but eg in the upper left or lower right corner?
Unfortunately I could't really figure out how to use the -label command to achieve that. Thanks for any suggestions.

A: If you want to invest a little more effort you can have more control. If you do it like this, you can label the images "on-the-fly" as you montage them rather than having to save them all labelled and then montage them. You can also control the width, in terms of number of images per line, more easily:
#!/bin/bash
number=0
for f in *.tif; do
   convert "$f" -gravity northwest -annotate +0+0 "$number" miff:-
   ((number++))
done | montage -tile x3 - result.png

It takes advantage of ImageMagick miff format, which means Multiple Image File Format, to concatenate all the output images and send them into the stdin of the montage command.
Or, you can change the script like this:
#!/bin/bash
number=0
for f in *.tif; do
   convert "$f" -gravity northwest -fill white -annotate +0+0 "$number" miff:-
   ((number++))
done | montage -tile 2x - result.png

to get

Or maybe this...
#!/bin/bash
number=0
for f in *.tif; do
   convert "$f" -gravity northwest -background gray90 label:"$number" -composite miff:-
   ((number++))
done | montage -tile 2x - result.png

Or with letters...
#!/bin/bash
number=0
letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for f in *.tif; do
   label=${letters:number:1}
   convert "$f" -gravity northwest -background gray90 label:"$label" -composite miff:-
   ((number++))
done | montage -tile 2x - result.png

A:
What possibilities are there to label the single images in the combined?

Iterate with a for loop.
for INDEX in {A,B,C}; do
    convert ${INDEX}.jpg labeled_${INDEX}.jpg
done

Is there an option to put the label not underneath the picture but eg in the upper left or lower right corner?

Try using the -annotate with -gravity
convert rose: -fill white \
        -gravity NorthWest -annotate +0+0 "A" \
        A.png

convert rose: -fill white \
        -gravity SouthEast -annotate +0+0 "B" \
        B.png

A: Based on the answers above, I wrote a  small perl script to combine figures into labelled subfigures, which might be useful to others. It works for me on a Mac, but I didn't really test it.
Usage: pics2grid geometry output_file [-title title] [-bycols] input_files

where the geometry format is [# cols]x[# rows] and input_files accept wild cards. If your title contains spaces, the title must be quoted and the spaces escaped.
I paste it below, but it can also be downloaded from http://endress.org/progs.html#subfigs
#!/usr/bin/perl -l

use strict;
use warnings;
use autodie;
use Getopt::Long 'HelpMessage';

### Process options and arguments ###
if (@ARGV < 3){
  HelpMessage(1);
}

if (($ARGV[0] !~ /^\d+x/) && ($ARGV[0] !~ /x\d+$/)){
  HelpMessage(1);
}

my $geometry = shift @ARGV;

my $output_file = shift @ARGV;

my $title = "";
my $bycols = "";

GetOptions ('bycols' => \$bycols,
        'title=s' => \$title,
        'help'     =>   sub { HelpMessage() },
       ) or HelpMessage(1);

# Wildcards are automatically expanded in @ARGV, but just make sure that they are
my @input_files = map { glob } @ARGV;

$title = "-title $title"
  if ($title);

if ($bycols){
  die "When option -bycols is set, a fully specified geometry is needed."
    unless ($geometry =~ /^\d+x\d+$/);
 }

 @input_files = reorder_input_files (\@input_files, $geometry)
   if ($bycols);

### Define the labels for the subfigures. If you want different figures, change it here. ###
my @labels = "a".."z";
@labels = @labels[0..$#input_files];
@labels = reorder_input_files (\@labels, $geometry)
   if ($bycols);

my $pic_data;

foreach my $f (@input_files){
  # Pictures are combined by rows
  my $lab = shift @labels;
  $pic_data .= `convert \"$f\" -pointsize 48 -font Arial-Regular -gravity northwest -annotate +20+10 \'$lab\' \\
                -bordercolor black -border 1 \\
                 miff:-`;

}

open (OUT,  "| montage -tile $geometry -geometry +0+0 -background white -pointsize 60 -font Arial-Regular $title - $output_file");
print OUT $pic_data;
close (OUT);

sub reorder_input_files {

  my ($input_files, $geometry) = @_;

  my ($ncols, $nrows) = split (/x/, $geometry);

  my @rows = ([]) x $nrows;

  foreach my $i (0..$#$input_files){

    my @tmp_array = @{$rows[$i % $nrows]};
    push (@tmp_array, $input_files->[$i]);
    $rows[$i % $nrows] = \@tmp_array;

  }

  my @reordered_files = ();

  map {push (@reordered_files, @$_)} @rows;

  return (@reordered_files);

}

=head1 NAME

pics2grid - arrange pictures on a grid of sub-figures and number the individual pictures with letters

=head1 SYNOPSIS

  pics2grid geometry output [-title title] [-bycols] inputfiles

  The inputfiles argument accepts wild cards.

  Geometry format: [\# cols]x[\# rows].
                   Unless you set the option -bycols, specifying either
                   the number of rows or of columns is sufficient.

  Options:
    --title,-t      Title. If your title contains spaces, the title needs
                    to be quoted *and* the spaces need to be escaped.
    --bycols,-b     Arrange and number pictures by columns rather than rows
    --geometry,-g   Not yet implemented
    --help,-h       Print this help message

  Examples:
    # Create grid with 3 columns and 2 rows in which images are arranged by *rows*
    pics2grid.pl 3x2 output.pdf input1.png input2.png input3.png\
                                input4.png input5.png input6.png

    # Create grid with 2 columns and 3 rows in which images are arranged by *columns*
    pics2grid.pl 2x3 output.pdf -bycols input1.png input2.png input3.png\
                                        input4.png input5.png input6.png

    # Same as above but with a title including spaces.
    # Note that the title needs to be quoted *and* the space needs to be escaped
    # (i.e., put \ in front of the space)
    pics2grid.pl 2x3 output.pdf -bycols -title "My\ title" input1.png\
                 input2.png input3.png input4.png input5.png input6.png

    # Create grid with 4 columns of all png files in the current directory. Images
    # are arranged by *columns*.
    # It will stop labeling the subfigures for more than 26 images
    pics2grid.pl 4x output.pdf *.png

=head1 VERSION

0.01

=cut


text:
Q: UIImage Context editing causes SIGABRT / EXC_BAD_ACCESS I've got a pretty strange behaviour on my code. I want to edit some graphical stuff within an UIGraphicsImageContext. Sometimes it works, sometimes it doesn't. I'm detaching the image proccessing function to a new thread which looks like this:
-(void)process:(SEL)function withObject:(id)sender {
UIActivityIndicatorView  *av = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
av.frame = CGRectMake(round((self.view.frame.size.width - 50) / 2),
                      round((self.view.frame.size.height - 50) / 2), 50, 50);
av.tag  = kActivityTag;
[self.view addSubview:av];
[av startAnimating];
[self enableControls:NO];
[NSThread detachNewThreadSelector:function toTarget:self withObject:sender];

Before the process function is called by one of this functions like that:
-(void)imageColorTintChanged:(id)sender {
[self process:@selector(tint:) withObject:sender];}

-(void)tint:(id)sender {
@synchronized(image) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    float f       = ((UISlider *)sender).value;
    NSInteger tag = ((UISlider *)sender).tag;
    if (tag == 0) {
        redTint = f;
    } else if (tag == 1) {
        greenTint = f;
    } else if (tag == 2) {
        blueTint = f;
    }
    previewImage = [ImageUtil colorizeImage:image color:[UIColor colorWithRed:redTint green:greenTint blue:blueTint alpha:1.0]];
    [imageView setImage:previewImage];
    [self processDidFinish];
    [pool release];
}}

Finally my graphic editing starts here on the new thread:
+ (UIImage *)colorizeImage:(UIImage *)baseImage color:(UIColor *)theColor {
if (baseImage) {
    @synchronized (baseImage) {
        UIGraphicsBeginImageContext(baseImage.size);  // CRASH!!

        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGRect area = CGRectMake(0.0f, 0.0f, baseImage.size.width, baseImage.size.height);

        CGContextTranslateCTM(ctx, 0.0, baseImage.size.height);
        CGContextScaleCTM(ctx, 1.0, -1.0);

        [theColor set];
        CGContextFillRect(ctx, area);

        CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

        CGContextDrawImage(ctx, area, baseImage.CGImage);

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return newImage;
    }
}
return baseImage;

Most of the time it crashes in this line:
UIGraphicsBeginImageContext(baseImage.size);
What could it possibly be? A threading thing?
Thanks in advance.
EDIT:
Well, i made an activity monitor test on Instruments and for some reason it says no memory leak, but the real Memory usage goes up to 53 MB after some image processing and then it crashes. Is it possible that it's just some "I use too much memory" Error?

A: From UIKit Function Reference, regarding UIGraphicsBeginImageContext():

You should call this function from the main thread of your application only.

You'll need to create a CGBitmapContext here instead.


text:
Q: Using Alecrim Core Data with Swift 3 I'm having trouble with Alecrim Core Data in Xcode 8 Beta. The DataContext and DataContextOptions seem to be missing from the Swift_3 branch. Grasping at straws, I just updated the files from the master branch to Swift3 syntax hoping the functionality hadn't changed too much. But when it tries to read data I get an error message "Cannot fetch without an NSManagedObjectContext in scope".
I've done as much triage as I can think of. Breakpoints set at the spot that creates an NSManagedObjectContext and I can see it. The place that creates the fetchRequest has been updated with the new NSFetchReqeust syntax (although I see no sign of a MOC there).
Here's my link into the Alecrim lib DataContext:
let dataContext = DataContext()

extension DataContext
{
    public var collections: Table<CoreDataCollection> { return Table<CoreDataCollection>(context: self) }
    public var expressions: Table<CoreDataExpression> { return Table<CoreDataExpression>(context: self) }
    public var fileAssets: Table<CoreDataFileAsset> { return Table<CoreDataFileAsset>(context: self) }
    public var purchases: Table<CoreDataPurchase> { return Table<CoreDataPurchase>(context: self) }
    public var reeConfigs: Table<CoreDataReeConfig> { return Table<CoreDataReeConfig>(context: self) }
    public var stickers: Table<CoreDataSticker> { return Table<CoreDataSticker>(context: self) }

}

And the part that attempts to get data:
for item in dataContext.reeConfigs {
    let reeConfigVO = ReeConfigVO()
    reeConfigVO.initFromCoreData(item)
    items.append(reeConfigVO)
}

I'm not sure if this will be helpful but the part of Alecrim that's tossing the error:
// MARK: - GenericQueryable

extension TableProtocol {

    public final func execute() -> [Self.Element] {
        do {
            return try self.toFetchRequest().execute() as [Self.Element]
        }
        catch let error {
            AlecrimCoreDataError.handleError(error)
        }
    }

}

// MARK: - CoreDataQueryable

extension TableProtocol {

    public final func toFetchRequest<ResultType: NSFetchRequestResult>() -> NSFetchRequest<ResultType> {
        let fetchRequest = NSFetchRequest<ResultType>()

        fetchRequest.entity = self.entityDescription

        fetchRequest.fetchOffset = self.offset
        fetchRequest.fetchLimit = self.limit
        fetchRequest.fetchBatchSize = (self.limit > 0 && self.batchSize > self.limit ? 0 : self.batchSize)

        fetchRequest.predicate = self.predicate
        fetchRequest.sortDescriptors = self.sortDescriptors

        return fetchRequest
    }

}

Does anyone have experience with Alecrim in Swift 3 that can help figure out what's going wrong?
Thanks,
Mike

A: I found the answer I was looking for. I'm not sure this is what Alecrim wants to be done because, as I mentioned, the swift_3 branch doesn't even contain DataContext or DataContextOptions. However... if you have brought those files in from the main branch and updated them to swift 3 as I have and you have problems with the error "Cannot fetch without an MSManagedObjectContext in scope" here's how to fix it in the "TableProtocol.swift" file:
extension TableProtocol {

    public final func execute() -> [Self.Element] {
        do {
            return try self.context.fetch(self.toFetchRequest()) as! [Self.Element]
            //return try self.toFetchRequest().execute() as [Self.Element]
        }
        catch let error {
            AlecrimCoreDataError.handleError(error)
        }
    }
}

self.context is the NSManagedObjectContext (or a derived type i.e. our DataContext) that is needed for this to work. The as! [Self.Element] is crucial because Swift uses it to infer the RestultType in the function that builds the NSFetchRequest
Hope this helps.


text:
Q: Android horrizontal scroll gallery application I want to create simple application like android image gallery but I don't want to display images. I want to display an editTexts and buttons...
My idea is to use android.widget.Gallery. Is it good way to solve this?
My next idea is HorizontalScrollView but here is problems with snaps etc.

A: Yes, you could do this with Gallery, make an Adapter that returns your layout that contains the EditText and Buttons.
However, you should check out ViewPager