Q:

Set caret at an index in RichTextBox WPF

I am trying to set the position of caret in richtextbox based on index position of a word. Even though I am able to change the caret position, the caret does not move to the correct location.
Here is my sample code:
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        RTB_Main.Document.Blocks.Clear();
        for (int i = 0; i < 10; i++)
        {
            Paragraph para = new Paragraph(new Run(i + ""));
            RTB_Main.Document.Blocks.Add(para);
        }
        TextRange richText = new TextRange(RTB_Main.Document.ContentStart, RTB_Main.Document.ContentEnd);
        string searchText = tb_Search.Text; // 1 to 9

        int position = Regex.Match(richText.Text, searchText).Index;

        RTB_Main.CaretPosition = RTB_Main.Document.ContentStart;
        RTB_Main.CaretPosition = RTB_Main.CaretPosition.GetPositionAtOffset(position);
        RTB_Main.Focus();
    }

What is wrong with this approach?
 Also, Please let me know if there is a better way to set the caret position to an index?

A:

The problem in my case was caused by new line characters \r\n. I just replaced these with another characters and it worked for me. Note that I am replacing them with not 2 characters but 4.
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        RTB_Main.Document.Blocks.Clear();
        for (int i = 0; i < 10; i++)
        {
            Paragraph para = new Paragraph(new Run(i + ""));
            RTB_Main.Document.Blocks.Add(para);
        }
        TextRange richText = new TextRange(RTB_Main.Document.ContentStart, RTB_Main.Document.ContentEnd);
        string searchText = tb_Search.Text; // 1 to 9

        string tmpStr = richText.Text.Replace("\r\n", "....");

        int position = Regex.Match(tmpStr, searchText).Index;
        RTB_Main.CaretPosition = RTB_Main.Document.ContentStart;
        RTB_Main.CaretPosition = RTB_Main.CaretPosition.GetPositionAtOffset(position);
        RTB_Main.Focus();
    }


Q:

Ignore index column when loading data to SQLalchemy in python

I want to remove the index column as seen on the picture, it already has. I want to remove either of the two. My idea is to use index_ignore = True but not sure where to put it.
screenshot index column, SQLalchemy in python
import pandas as pd
from sqlalchemy import create_engine

db_file = r'learn-data-analysis-w-python-master/datasets/salesdata.db'

engine = create_engine(r'sqlite:///{}'.format(db_file))
sql = 'SELECT * from scores'
sales_data_df = pd.read_sql(sql, engine)
sales_data_df

A:

In the absence of data to try my solution with, I can suggest you to try
sales_data_df.drop(['index'], axis=1)


Q:

runaway distnoted process

Sometimes I see a distnoted process suddenly spin up and chew up 100% CPU (on one core) and a ton of memory, often in the neighborhood of 1.5G or so. This happens a few times a day, starting a month or so ago.
The command line is /usr/sbin/distnoted agent, and it's started by launchd, neither of which help much. It's usually been running for somewhere between 4h and 24h before it spins up and pegs the CPU.
Web searches say distnoted manages notification delivery, and lots of other people report the same problem with it, but I haven't yet found a fix. Some people find that closing a culprit application (e.g. Skype) stops it, but I haven't found a culprit on my machine yet. I'm usually only running a few apps: Emacs (24.2 from Homebrew), Firefox, Adium, and Dash.
I'm on Mavericks on a late 2012 13" Retina MBP. Thanks in advance!
Update:
I've turned on distnoted logging in the system log by touching /var/log/do_dnserver_log, but it doesn't help much. I see lines like these (uid 501 is me, 89 I haven't found yet):
distnoted[80011]: # distnote server agent  absolute time: 48754.144787848   civil time: Wed Nov 20 10:52:03 2013   pid: 80011 uid: 501  root: no
distnoted[20]: # distnote server daemon  absolute time: 2.808112262   civil time: Tue Nov 19 09:52:24 2013   pid: 20 uid: 0  root: yes
distnoted[444]: # distnote server agent  absolute time: 16.656997509   civil time: Tue Nov 19 09:52:38 2013   pid: 444 uid: 501  root: no
distnoted[1271]: # distnote server agent  absolute time: 52.518265717   civil time: Tue Nov 19 09:53:14 2013   pid: 1271 uid: 89  root: no
distnoted[689]: Interruption - exiting now.

I've also run sudo dtruss -p PID on a spun-up distnoted process, and it spews lines like this:
kevent64(0x3, 0x7FFF7C3FD130, 0x1)       = 1 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
kevent64(0x3, 0x7FFF7C3FD130, 0x1)       = 1 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
kevent64(0x3, 0x7FFF7C3FD130, 0x1)       = 1 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
__disable_threadsignal(0x1, 0x0, 0x0)    = 0 0
__disable_threadsignal(0x1, 0x0, 0x0)    = 0 0
__disable_threadsignal(0x1, 0x0, 0x0)    = 0 0
kevent64(0x3, 0x7FFF7C3FD130, 0x1)       = 1 0
workq_kernreturn(0x20, 0x0, 0x1)         = 0 0
...

A:

I've seen this too.  Emacs 24.3.1, Mavericks 10.9.
I've found that the distnoted process calms down within seconds after I quit out of Emacs.
I've filed an Emacs bug here: http://permalink.gmane.org/gmane.emacs.bugs/80836

A:

Summary from the OP: This was a great tool for debugging. It originally pointed me to Spotlight reindexing the filesystem, but I narrowed down the things it's allowed to index, and I still saw the problem. I ended up setting up a cron job to kill distnoted regularly. See answer farther down.

You can debug distnoted by creating the file /var/log/do_dnserver_log
This causes the CFNotificationCenter server (distnoted) to record information about all notifications to the system log.
I would start there, reboot and look at the system log when the CPU spikes up. This should out the culprit easily.
More info on CFNotificationCenter debugging can be found in official Developer docs here: Technical Note TN2124 > CFNotificationCenter

A:

I know I'm late to the party but this is a memory leak specific to Cocoa emacs on Mavericks that is fixed in the trunk. For now there is a patch you can use to build emacs 24.3 with just the fix.
https://gist.github.com/anonymous/8553178


Q:

Can one program have multiple processes?

after reading and searching about OS and process and threads, I checked on wiki and it said,

A computer program is a passive
  collection of instructions, a process
  is the actual execution of those
  instructions. Several processes may be
  associated with the same program; for
  example, opening up several instances
  of the same program often means more
  than one process is being executed.

Now is it possible for a program to have more than one process and I am not including the possibility of running more than one instance of the same program. I mean one instance of one program is running, is it possible for a program to have more than one process?
If yes, how? If no, why not?
I am a newbie in this, but damn curious :)
Thanks for all your help..

A:

Yes, fairly obviously - you can run two or more copies of most programs - I routinely have about 5 copies of vim running, and each of those is a separate process. As to how, the OS loads the executable file, creates a process and then tells that process to start executing the file contents.

A:

It is most definitely possible but a desktop application might not be a good example and I think this is the source of your confusion.
Consider a webserver instead (NginX or Apache). There is one master process and multiple worker processes at work. The master process "accpets" the work , so to speak, and delegates it to the workers. Both NginX and Apache could be configured to any number of worker processes.
At our company we are in the business of delivering a SaaS that helps businesses have an online chat with their visitors via their websites. The back-end part of our system has multiple "service"es communicating with each other to accomplish the task. Each service has multiple instances running.


Q:

Advice on preserving wealth in a volatile economic/political country

I'm looking for some advice on how to best position myself in an country that faces a volatile economic future in the short/mid term ahead.
Some background:

I live in South Africa where our currency has been slammed this year due to poor economic prospects ahead, a bad political landscape, and also less global appetite for risk.
The outlook for the country over the short/mid term is very shaky. Things could gradually decline over the next few years (most likely), but even take a sharp turn for the worse...a lot depends on the political scene next year.

I've made some investment mistakes in the past of trying to buy individual stocks (without proper analysis) and have lost a bit of money. I decided recently to sell off the individual shares and rather take an approach of just buying and holding long term in diversified index funds.
Recently I also sold off some of my locally based index funds and re-adjusted the balance of my portfolio to try preserve some of my wealth with foreign invesments.  I'm fairly young (early 30s) so my portfolio is fairly aggressive towards equities.
Current portfolio make-up:

10% risky assets (bitcoin)
10% gold index tracker (good hedge for our currency)
41% local indexes & retirement annuity
27% foreign indexes (DBX USA, S&P 500, FTSE 100, etc).
6% cash locally (held in a low interest savings account)
6% cash foreign (USD & GBP)

My main goal is not to panic when things happen but to try stick to a plan.
Questions:

What approach should I take to best protect my wealth against currency devaluation & poor growth prospects. I want to avoid selling off any more of my local index funds in a panic as I want to hold long term. Does my portfolio balance make sense?
Quite a large portion of my foreign investments have been bought at an expensive time when our currency is already around historic lows, which does concern me in the event that it strengthens in future. What strategy should I take in the future if/when my local currency starts the strengthen...do I hold my foreign investments through it and just trust in cost averaging long term, or try sell them off to avoid the devaluation?

Any advice would really be appreciated.
Thanks.

A:

You might find some of the answers here helpful; the question is different, but has some similar concerns, such as a changing economic environment.

What approach should I take to best protect my wealth against currency
  devaluation & poor growth prospects. I want to avoid selling off any
  more of my local index funds in a panic as I want to hold long term.
  Does my portfolio balance make sense?

Good question; I can't even get US banks to answer questions like this, such as "What happens if they try to nationalize all bank accounts like in the Soviet Union?"  Response: it'll never happen.
The question was what if!
I think that your portfolio carries a lot of risk, but also offsets what you're worried about.  Outside of government confiscation of foreign accounts (if your foreign investments are held through a local brokerage), you should be good.  What to do about government confiscation?  Even the US government (in 1933) confiscated physical gold (and they made it illegal to own) - so even physical resources can be confiscated during hard times.

Quite a large portion of my foreign investments have been bought at an
  expensive time when our currency is already around historic lows,
  which does concern me in the event that it strengthens in future. What
  strategy should I take in the future if/when my local currency starts
  the strengthen...do I hold my foreign investments through it and just
  trust in cost averaging long term, or try sell them off to avoid the
  devaluation?

Are these foreign investments a hedge?  If so, then you shouldn't worry if your currency does strengthen; they serve the purpose of hedging the local environment.  If these investments are not a hedge, then timing will matter and you'll want to sell and buy your currency before it does strengthen.  The risk on this latter point is that your timing will be wrong.

A:

I suggest that you're really asking questions surrounding three topics: (1) what allocation hedges your risks but also allows for upside? (2) How do you time your purchases so you're not getting hammered by exchange rates? (3) How do you know if you're doing ok?
Allocations
Your questions concerning allocation are really "what if" questions, as DoubleVu points out. Only you can really answer those. I would suggest building an excel sheet and thinking through the scenarios of at least 3 what-ifs.
A) What if you keep your current allocations and anything in local currency gets cut in half in value? Could you live with that?
B) What if you allocate more to "stable economies" and your economy recovers... so stable items grow at 5% per year, but your local investments grow 50% for the next 3 years? Could you live with that missed opportunity?
C) What if you allocate more to "stable economies" and they grow at 5%... while SA continues a gradual slide? Remember that slow or flat growth in a stable currency is the same as higher returns in a declining currency. I would trust your own insights as a local, but I would recommend thinking more about how this plays out for your current investments.
Timing You bring up concerns about "timing" of buying expensive foreign currencies... you can't time the market. If you knew how to do this with forex trading, you wouldn't be here :).
Read up on dollar cost averaging. For most people, and most companies with international exposure, it may not beat the market in the short term, but it nets out positive in the long term.
Rebalancing For you there will be two questions to ask regularly: is the allocation still correct as political and international issues play out? Have any returns or losses thrown your planned allocation out of  alignment?
Put your investment goals in writing, and revisit it at least once a year to evaluate whether any adjustments would be wise to make.
And of course, I am not a registered financial professional, especially not in SA, so I obviously recommend taking what I say with a large dose of salt.


Q:

GROUPBY Parameter - SSRS

how can I group my parameter values?

A:

Your parameters are probably being pulled from a dataset. You may need to create a new dataset and modify your query to just have the parameters you want to display.
You will want to add DISTINCT to your query, like this:

select DISTINCT SHO_REGION from TABLENAME

Then just populate your parameters with your new dataset. Bam, done.


Q:

JacksonPolymorphicDeserialization: JsonMappingException

I supposed that I had a parent Class Parameter that has 2 sub classes ComboParameter and IntegerParameter
@JsonSubTypes({
    @JsonSubTypes.Type(value = IntegerParameter.class, name = "integerParam"),
    @JsonSubTypes.Type(value = ComboParameter.class, name = "comboParam")
})
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.WRAPPER_OBJECT)
 public abstract class Parameter {
String regEx;
}

@JsonTypeName("integerParam")
public class IntegerParameter extends Parameter {
}

@JsonTypeName("comboParam")
public class ComboParameter extends Parameter {
List<String> values;
}

And I have a class that had an attribute parameter
class A {
@JsonUnwrapped
Parameter parameter;
}

The Serialization of an Object A throw an Exception

com.fasterxml.jackson.databind.JsonMappingException: Unwrapped property requires use of type information: can not serialize without disabling SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS

And if I delete the annotation @JsonUnwrapped I will have a json like That
{
     parameter:{
          integerParam:{
               regEx: regExVal
          }
     }
}

And what I need is a json like that:
{
     integerParam:{
           regEx: regExVal
     }
}

NB I' am using Jackson 2.4.4

A:

Don't think there is easy and clean solution for this problem. But here is some thoughts how you can solve it (Gist demo for both cases):
Option 1: Add @JsonIgnore above property and @JsonAnyGetter in the top level bean. Easy to implement but not nice to have static ObjectMapper in bean and will have to copy this code to every been with Parameter property
public class A {

    @JsonIgnore
    Parameter parameter;

    // can put ObjectMapper and most of this code in util class
    // and just use JacksonUtils.toMap(parameter) as return of JsonAnyGetter

    private static ObjectMapper mapper = new ObjectMapper();

    /************************ Serialization ************************/

    @JsonAnyGetter
    private Map<String, Object> parameterAsMap(){
        return mapper.convertValue(parameter, Map.class);
    }

    /************************ Deserialization **********************/

    @JsonAnySetter
    private void parameterFromMap(String key, JsonNode value)  {
        try {
            parameter =  mapper.readValue(String.format("{\"%s\":%s}", key,value),
                    Parameter.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Option 2: @JsonIgnore property and register custom serializer/deserializer for root A class
SimpleModule module = new SimpleModule();
module.addSerializer(A.class, new ASerializer());
module.addDeserializer(A.class, new ADeserializer());
mapper.registerModule(module);

Can't use @JsonSerialize above A class, because serializers and deserializers inner ObjectMapper will also use this annotation, but you need to setup it to use default serializer/deserializer and not itself recursively. Or you could implement something like https://stackoverflow.com/a/18405958/1032167 if your really want the annotation
And serializer + deserializer would look something like this (Unoptimized and just a prove of concept):
    /************************ Serialization ************************/

public static class ASerializer extends JsonSerializer<A> {
    private static ObjectMapper m = new ObjectMapper();

    @Override
    public void serialize(A value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        Map defaults = m.convertValue(value, Map.class);
        Map params = m.convertValue(value.getParameter(), Map.class);
        defaults.putAll(params);
        gen.writeObject(defaults);
    }

}

    /************************ Deserialization **********************/

public static class ADeserializer extends JsonDeserializer<A> {
    private static ObjectMapper m = new ObjectMapper();
    private static String[] subtipes = {"integerParam", "comboParam"};

    public ADeserializer() {
        m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @Override
    public A deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {

        TreeNode node = m.readTree(p);

        A a = m.convertValue(node, A.class);

        // hardcoded , probably can be done dynamically
        // with annotations inspection
        for (String key : subtipes) {
            TreeNode value = node.get(key);
            if (value != null) {
                String json = String.format("{\"%s\":%s}", key, value);
                a.setParameter(m.readValue(json, Parameter.class));
                break;
            }
        }

        return a;
    }
}

Generic deserializer would be pretty hard to write. But this question is about serialization anyway according to the question body.


Q:

Return records where search data does not exist

I have created a view containing data from tables employees and courses. Using this view i can easily find which courses every employee has been on, I however would like to know (depending on employees job title) what compulsory course they haven't been on. For example, all new employees with the job title 'cle' are required to go on a data protection course ('data'). How do I return all employees with job title 'cle' that haven't been on the 'data' course?
I think I need something similar to '!= 'data'' where it actually returns all employees who have a record of 'cle' but don't have a record of 'data' against them and disregards all the others.
I hope someone understands this?

A:

Your title suggests the answer, use NOT EXISTS:
SELECT e.*
FROM dbo.Employee e
WHERE [job title] = 'cle'
AND NOT EXISTS
(
    SELECT 1 FROM dbo.Courses c
    WHERE c.EmployeeID = e.EmployeeID
     AND  c.ProtectionCourse = 'data'
)

Note that i've presumed all table and column. But you should get the idea.


Q:

Meaning of python -m flag

What does -m in python -m pip install <package> mean ?
or while upgrading pip using python -m pip install --upgrade pip.

A:

If you type python --help
You get
// More flags above
-m mod : run library module as a script (terminates option list)
// and more flags below

A great many things in a terminal will show you how to use it if you either use command --help or man command

A:

From Python Docs

The argument is a module name, you must not give a file extension (.py). The module-name should be a valid Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen).
Package names are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute .main as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument.

A:

The -m stands for module-name.
From Command line and environment:

python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]


Q:

Does a company have the right to perform MITM SSL stripping attack on their employees?

Does a company have the right to sniff all the traffic on their network irrespective of whether it contains personal data of employees if they show a warning message which states "...are subject to having their activities on the system intercepted, monitored and recorded."

Does US law states anything about this?
Does company policy enforcement with such a warning override the right to not be subject to surveillance?

A:

IANAL, and as @GeorgeBailey suggests, you should ask one.  That said, some aspects of your question are directly addressable with what we know.

Does US law states anything about this?

Yes. Federally this falls under the Wiretap Act, 18 U.S.C. §2511.  Workplace monitoring generally falls under either the "System Administrator Exception" or under Consent.  In general, continuing past a banner constitutes consent.

Does company policy enforcement with such a warning over ride the
  right to not be subject to surveillance?

In general, yes.  You don't need to use the companies network if you don't want to consent - and they don't need to hire you if you don't want to use their network.  But it's their network, and their rules apply.
There are some nuances, and courts have found that the wording of the notice has made a difference in some cases, but overall, if the systems are properly posted with banners, then the employer may capture communications.  See the "Bannering and Consent" section of this article from cybertelecom.org, e.g.:

Even if no clicking is required, a user who sees the banner before
  logging on to the network has received notice of the monitoring. By
  using the network in light of the notice, the user impliedly consents
  to monitoring pursuant to 18 U.S.C. § 2511(2)(c)-(d).

Note that stored data is covered by different laws than communications.  It's a nuance.

Is it ethical to sniff all the data without giving any other warning than the logon banner?

"Ethical" is a very different question than "Legal", and largely more subjective.  Most employers require signed consent for monitoring as a condition of employment, and use banners thereafter.  That is ethical by my definition, in that it meets or exceeds the requirements of the law, and does not mislead or use subterfuge.  The tone of your question suggests you find it distasteful, and therefore probably it violates your personal code of ethics.


Q:

Stop Cloudfront from serving whole website

I want to use Cloudfront as a CDN for my CSS, JS, images etc... I've set up a distribution on AWS with an origin domain name as mywebsite.com. The distribution has an alternate domain name as cdn.mywebsite.com. If I user accesses cdn.mywebsite.com they are served the whole website. I don't want this to be possible. My CNAME is set-up to point to the Cloudfront distribution (i.e. ***.cloudfront.net).
Is there a way of stopping this behaviour?

A:

I think you're mixing up 2 different ways of using a CDN in your setup.

If you had all your images for example hosted in an S3 bucket, you would point your CDN to that bucket, call it cdn.images.com. Then on your website you would reference all your images as cdn.mywebsite.com/potato.jpeg. The CDN would then store your images on your the edge locations. Your website's dns record (www.mywebsite.com) still points directly to your server - not to your CDN, but your images are pulled from your CDN.
The other option is if all your content, website, everything is on one server - and you're pointing your CDN to that server. So your website is www.mywebsite.com, and because you only want to store jpegs on the CDN and everything else must go back to the origin, you set that up in your caching. Your DNS record for www.mywebsite.com gets pointed to your CDN

You seem be expecting to do option one, but your setup is more like option 2.
Since it seems like all your content is stored on your digital ocean server - I would just have a URL for www.mywebsite.com and point that to your digital ocean server. Your cache behaviour in the CDN config will then just have *.jpeg, *.css, *.etc...


Q:

jQuery, button message doesn't change

How do I get the text beside my button to change? Everything else works fine except for these button messages. Thanks for your help.
<!DOCTYPE html PUBLIC ">

      <input type='button' value='+' id='PlusMinus'/>
        Larger Text

Smaller Text

My Text!!!

BUTTON STATE 'Message should toggle between Larger Text and Smaller text'
[+] Larger Text

[-] Smaller Text

A:

This worked for me:
<!DOCTYPE html PUBLIC ">

<input type='button' value='+' id='PlusMinus'/>

Larger Text

Smaller Text

My Text!!!

The changes I made were:
changed $("h6").toggle(); to $("body h6").toggle(); and moved it up to the $('#PlusMinus').click function
moved the button out of the "Larger Text" h6 element
added  tag at the top
removed "Not Working" comments ;)


Q:

Ocelot API Gateway - Best url template to assign microservices?

We have a number of microservices in our company.
We also use the Api Gateway pattern to route these microservices, which in fact we used Ocelot for this.
What is the best Url format for applying to these Microservices?

The important thing is that we use Rest architecture for our service

For example, I have these templates right now:

api.example.com/microservice1/{controller}
example.com/api/microservice1/{controller}

what is your opinion?

A:

IMHO,
This pattern
example.com/api/microservice1/{controller}

is good if you intend to implement a separation between your APIs and WFE (Web Frontend) projects. In fact, this approach will be really good when used with a Microfrontend architecture for your front-end projects.
BTW, I've written an API Gateway series about Ocelot and ASP.net Core, if you want to learn more about API Gateway Architecture, you can check it out from:
https://www.pogsdotnet.com/2018/08/api-gateway-in-nutshell.html
Hope it helps!


Q:

Cannot insert the value NULL into column where using Sql Select statement

Can you tell me how to avoid below mentioned exception ?
 INSERT INTO [Migrated].[dbo].[Cities] (Name, ZipCode)
     SELECT DISTINCT
         a.City, a.ZipCode
     FROM
         [Legacy].[dbo].[Ziplist] AS a
     WHERE
         (a.City IS NOT NULL AND a.ZipCode IS NOT NULL);

Exception:

Cannot insert the value NULL into column 'IsDeleted', table 'Migrated.dbo.Cities'; column does not allow nulls. INSERT fails.

A:

As @jamieD77 commented you are missing the IsDeleted column in your insert statement.
The error means that the column is marked as "NOT NULL" and therefore a value must be inserted when a new row is created.
So you either need to remove the NULL constraint from the table yourself or insert a value in the column.
 INSERT INTO [Migrated].[dbo].[Cities] (Name, ZipCode, IsDeleted)
 select  DISTINCT a.City,a.ZipCode,0 from [Legacy].[dbo].[Ziplist] as a where (
 a.City is not null and a.ZipCode is not null);

For a bit field which I would assume it is (but you should confirm!) the value 0 would be false and 1 would be true.  If the field is a different data type these values may have different meanings!!!


Q:

list of list of str

I'm trying to write a function that will open a .txt file in the shell as a list of list of str.
The file is something like:
TYUIO
GHJKL
BNMCV
ASDFG
XCVBN

And I need my function to return:
[['T', 'Y', 'U', 'I', 'O'], ['G', 'H', 'J', 'K', 'L'], ...]

and so on.
The function I have written almost produces this. It returns:
[['TYUIO'], ['GHJKL'], ...]

and so on. What do I need to change/add to this function to make it return to correct nested list?
This is my function:
board_list = []
for line in board_file:
    items = line.rstrip('\n').split('\t')
    items = [item.strip() for item in items]
    board_list.append(items)

return board_list

Can anyone help?

A:

Try using list() and extend().
items = [list(item.strip()) for item in items]
board_list.extend(items)

You can also do it in one line, assuming each line contains a single word. I'm not sure why you are splitting on \t so this might not work for you.
with open("data.txt") as board_file:
    board_list = [list(line) for line in board_file.read().split('\n') if line]


Q:

VB.Net Why does my dictionary need to be explicitly declared in order to use select?

Using VB.Net with MVC5.
I have a dictionary:
Dim Filter as New Dictionary(Of String, Object)

' the key's value is another dictionary
Filter.Add("customParams", New Dictionary(Of String, String) From {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}})

and I am trying to convert the Filter("customParams") value, which is a Dictionary(Of String, String), to a delimited string, "k1=v1, k2=v2, k3=v3"
This doesn't work:
Dim kvString As String = String.Join(", ", Filter("customParams").Select(Function(x) x.Key & "=" + x.Value).ToArray())

I get this exception:

Public member 'Select' on type 'Dictionary(Of String,String)' not
  found.

But if I explicitly declare a new variable for the Dictionary(Of String,String) and use that instead of Filter("customParams") then this works:
Dim customParams As Dictionary(Of String, String) = Filter("customParams")
Dim kvString As String = String.Join(", ", customParams.Select(Function(x) x.Key & "=" + x.Value).ToArray())

Why doesn't it work the other way?  The exception itself says that it's working with a Dictionary(Of String, String)

A:

By default, VB.Net allows late binding (OPTION STRICT OFF). Late binding is the equivalent of dynamic in C# and means the runtime looks up the method to call by name and the compiler does not type checking or validation. Only public members can be accessed by late binding, so extension (friend) methods such as Select are not available. This is automatic for object variables in VB.Net. customParams has a (non-object) assigned type and thus uses early binding.


Q:

Can't subclass PFQueryTableViewController

I'm writing an iOS App using Parse.com to interact with a server.
I've downloaded and installed the SKD, added all frameworks correctly and everything works fine until it comes to the PFQueryTableViewController. It doesn't appear in the drop down list when I'm creating a new class and I can't create one programmatically because Xcode just doesn't know it.
Same with a PFImageView, is this somehow related?
The SKD should be up to date since I updated it yesterday including the local datastore.
Am I missing here something?
Thanks in advance!

A:

For anyone using swift having this issue. In your bridging header file make sure you have the following:
#import <Parse/Parse.h>
#import <Bolts/Bolts.h>
#import <ParseUI/ParseUI.h>


Q:

PHP session_id never the same on refresh

I am trying to use session_id() on some php pages, but the id changes between every file and it changes everytime i refresh the page. I placed the following script which should increment on ever reload, but it does not.
session_start();
if (!isset($_SESSION['hits'])) $_SESSION['hits'] = 0;
++$_SESSION['hits'];

echo '
Session hits: ', $_SESSION['hits'], '
';
echo '
Refresh the page or click here.';

In my php.ini file, I have cookies turned on as well as set my save_path tp '/tmp'.
In the actual folder, there are session files... so i know it is not a file writing issue. I have also ensured that every file is utf-8 with bom to ensure consistency.
If there are any other solutions you can think of, please help me solve this. It is driving me insane.
Thanks!!!

A:

The 3 possibilities I can think of for your situation are:

How are you calling session_id()? Include that code in your question. If you're calling it with any arguments it will override the session ID to whatever argument you passed.
Are cookies enabled in your browser? The session ID is sent to the browser as a cookie.
Are you calling session_destroy() at any point? This will delete the session data from the server and cause a new session to be started on subsequent pageviews.


Q:

Random Prompt showing up when executing code that isn't found in my code anywhere

I am trying to do these steps:
1. Prompt user for three inputs, course_no, depart, and enrollment.
2. Check if depart is found in my departments table.
3. If it is found, check for an available room that satisfies condition. If not, print message.
Here is my code:
ACCEPT course_no number PROMPT "Enter course_no:  ";
ACCEPT depart PROMPT "Enter Department name: ";
ACCEPT Enrollment number PROMPT "Enter Enrollment: ";

DECLARE
deptFound number;
availableRooms number;
roomNumber  number;

BEGIN
select case
                when exists (select 1 from dept where code = '&depart')
                then 1
                else 0
           end as d_exist
        into deptFound
 from dual;

 if deptFound = 1 then
        select count(*) into availableRooms from rooms where capacity > &enrollment;
        if availableRooms > 0 then
                select room_no into roomNumber from rooms r where capacity  = ( select min(capacity) from rooms where capacity > &enrollmen) and rownum = 1;

        else
                DBMS_OUTPUT.PUT_LINE('No available rooms!');
        end if;
  end if;

END;
/

However, when I run this, it asks me for course_no, department name, and enrollment, then it prompts me  with this:
 Enter value for enrollmen:

I don't even have that prompt in my code. Where is it coming from??

A:

Well you actually do have that in your code. But to see it you need to understand substitution variables. See PLSQL 101 Substitution vs bind variables.  In this particular case that prompt actually exists twice at:
"select count(*) into availableRooms from rooms where capacity > &enrollment"
and again at
" ... from rooms where capacity > &enrollment  ..."


Q:

Is there any way to tell the number of matches found in a database value matched with LIKE?

Is there any way I can query a SQL-Server-CE database that will return the number of matches found in a cell value using LIKE (or MATCH AGAINST or any other method I'm not aware of, really)?
EXAMPLE table, "exampleTable":
**ObjectID**        **value**
     1           I Love Lemonade
     2             I Love Love

Using a query like this one:  SELECT * FROM exampleTable WHERE value LIKE '%love%', I can easily find any entries where the value contains the word (or has a word where part of it contains the word) "love." I would like to be able to know just "how many" matches were found (for sake of search priority) in the matched fields, so that they can be displayed as more relevant. I realize that I'm probably asking a lot out of a simple query, however, I also know how powerful SQL can be, too, so thought I would ask if this was possible and if not, if there is any other approach I might take (that won't force me to rewrite the database).
I thought of using sub-queries somehow, but there is no way (that I have been able to find) to combine "LIKE" and "IN".  Also, I am not even sure using a sub-query would get the job done since I'm working with a relational database where one main table relates to 8 others and the "8 other" tables have the values I want to search on, but the main table has the location I need (although, I suppose I don't have a problem adding a "location" column to these "8 other" tables, as it would be helpful in other areas, too).
It's entirely possible that I didn't design the "relational" part of the relational database to perfection, but this is the first time I have designed (although, certainly not worked with) a relational database by myself, and, at least, it works well with the back-end of my website (yes this site is a private partial CMS).
Any help is appreciated, and thank you for your time!

A:

You compare the length of the string with and without the text you're searching for:
  select
        ObjectID
        ,value
        ,(len(value) - len(replace(value,'love',''))) / 4 as occurs
        from exampleTable
        where value like '%love%'

A:

With the aid of a Numbers table:
CREATE TABLE Numbers
  ( i INT NOT NULL PRIMARY KEY ) ;

INSERT INTO Numbers (i)
VALUES                                        -- fill the table up to 10
  (1), (2), ... (10) ;

INSERT INTO Numbers (i)                       -- fill the table up to 100
SELECT m.maxi * a.i + b.i
FROM
    (SELECT MAX(i) AS maxi FROM Numbers) m    -- if you run this once more
  CROSS JOIN Numbers a                        -- it will get up to 10000
  CROSS JOIN Numbers b
WHERE a.i < m.maxi ;

you can run this:
SELECT e.ObjectID, e.value, COUNT(*) AS matches
FROM exampleTable AS e
  JOIN Numbers AS n
    ON  n.i <= LEN(e.value) + 1 - 4
    AND SUBSTRING(e.value, n.i, 4) = 'love'
WHERE e.value LIKE '%love%'
GROUP BY e.ObjectID, e.value ;


Q:

If $G$ is nilpotent of class 2 and if $a \in G$, then the function $\alpha: G \rightarrow G$ ...

If $G$ is nilpotent of class 2 and if $a \in G$, then the function $\alpha: G \rightarrow G$ defined by $x \rightarrow [a,x]$ is a homomorphism.
Proof: Let $x,y \in G$
Then $\alpha(xy) = [a,xy] = [a,x][a,y]^x$
So if we can show that $[a,y]^x=[a,y]$ then we'll basically have done it.
The fact that $G$ is nilpotent of class 2 will mean that $\frac{G}{Z(G)}$ is abelian.
case 1: $x \in Z(G)$. Then $[a,y]^x=[a,y]$ automatically.
case 2: $x \notin Z(G)$. Then we have
$[a,y]^x$ mod $Z(G)=[a,y]$  mod $Z(G)$
And i'm a bit stuck here it seems.

A:

The fact that $G$ is nilpotent of class 2 precisely means that $[a,y]$ will commute with $x$, which is what you need to complete your proof.


Q:

How can I efficiently browse through extends and implements in Java?

The idea of polymorphism sounds great on paper. In real life someone joins a new project and starts working on this code:
class Tom extends Cat implements Male {
temperature temperature = Tom.getTemperature();
..............
class Cat extends Feline{
..............
class Feline extends Mammals{
..............
class Mammals extends Animals implements WarmBlooded{
.......
interface WarmBlooded{
int temperature=96; //In case they forget to set the right temperature...
public int getTemperature(){
return temperature;
}

Compare to
Cat cat = new Cat(Tom, m, 96);

and
class Cat(Stiing name, char gender, int temperature){
    ....
}

Sure, we saved a couple of lines of code by implementing WarmBlooded, but at what cost? We have to look through multiple classes just to find out what getTemperature() is doing - isn't this an example of a spaghetti code? Millions of coders chose Java. There must be a reason for polymorphism. I will anyway have to keep in mind name, gender and temperature of a cat I am creating. Implementing Male is no different than passing "m" as a parameter when creating Tom. Why not bundle everything in Cat?
Does it mean I should read and understand the whole project to start benefiting from polymorphism? Are there any methods to make browsing through extends/implements easier?

What does efficiently browse through extends/implements mean?
It means "can find out what this method is doing in reasonable time".

A:

Use IDE. Such as NetBeans or Eclipse. Also, use UML. Otherwise it is hard to follow the code. It allows you to click on getTemperature() to see the implementation.
 Class Feline is useless if it only holds
    Boolean isFeline = true;

However, if it holds multiple methods it makes life easier - you don't have to keep in mind all these methods.
Java works best for larger projects. Joining such projects can be more difficult.


Q:

Is it possible to use Mercurial ACL Extension in a Bitbucket repository?

We have a small team working together with a BitBucket Mercurial repository. The thing is we have a "Releases" branch and want to restrict access to this to just certain people.
I've been looking to the Mercurial ACL extension, but it seems to work just with local repositories.
Do you know any solution for this if everyone pushes directly to Bitbucket?
Thx!

A:

No, you cannot use the ACL extension with Bitbucket. It would have to be enabled on their servers and they would have to provide a web interface for you to edit the rules. They haven't done this.
What you can do is to use a fork (separate repository) on Bitbucket to store your releases. You can restrict push/pull access on a per-fork basis so this could help you.
An alternative is to let only a few people push to the Bitbucket repository. They would then act as gatekeepers and so they can reject changesets on the wrong branch.
However, restricting access like this is generally not necessary. If it is, then you have a social problem that you should solve by talking with your developers.


Q:

Apache: Don't deliver website by IP address

I have to admin a web server with Apache 2 to deliver some different websites - every site has its own domain. The server has a single IP address, say: 78.9.10.11. For every site a VirtualHost is defined like this:
<VirtualHost *:80>
  ServerName mydomain.com
  ServerAlias *.mydomain.com
  ....
</VirtualHost>

It works fine, but there is a configuration problem: If someone tries to access the server via its IP address (http://78.9.10.11), the first VirtualHost is delivered - which I don't want. Instead, the access should be blocked or a special website should be served (to render some kind of error message). The server should only deliver sites by domain names.
How can I define a VirtualHost which is used for IP based access?

A:

<VirtualHost 78.9.10.11>
  ....
</VirtualHost>

Server up your custom error page (or whatever) inside that block.


Q:

rank values passed in subroutines

I am having some issues with using multi-dimensional array in some fortran code I am writing.
Basically, I define a 2-dimensional array, which is passed to membrane, then have to pass a 1-dimensional version of it to set.
Case (1)
  Call membrane ("Set", scv(i,:), sty)

Here is the routine that takes the 1-d array.
Subroutine membrane (tsk, scv, sty)
Implicit None
Character (Len=*), Intent (In) :: tsk
Logical, Intent (In), Optional :: scv(:,:)
Character (Len=*), Intent (In), Optional :: sty

Select Case (tsk)

Case ("Set")
  Call set (tsk, scv(1,:), sty)

...

Here is my set subroutine
Subroutine set (tsk, scv, sty)

Implicit None
Character (Len=*), Intent (In) :: tsk
Logical, Intent (In), Optional :: scv(:)
Character (Len=*), Intent (In), Optional :: sty

I then get this error when I try to compile my code
sct/btun/membrane.f:185:35:

     Call membrane ("Set", scv(i,:), sty)
                               1
Error: Rank mismatch in argument 'scv' at (1)
(rank-2 and rank-1)

A:

You are calling the routine membrane using a one-dimensional slice of scv. Since that subroutine is expecting a two-dimensional array:
Logical, Intent (In), Optional :: scv(:,:)

You get the error. I am not quite sure what you are trying to achieve, but since you are accessing the first column of the array in membrane (hard-coded), I would change the dummy argument scv to be one-dimensional in membrane:
Subroutine membrane (tsk, scv, sty)
...
Logical, Intent (In), Optional :: scv(:)
...

Select Case (tsk)

Case ("Set")
  Call set (tsk, scv(:), sty)
...

Note that that now the complete array is passed to set.
Alternatively, pass the complete 2D array to membrane along with the counter i, and pass the i-th row to set.


Q:

Porting My Linux Compiler to Windows

I am designing a programming language and have completed a compiler that generates x86 assembly code that works in Linux.
Specifically, my compiler takes as input a "myprogram.stanza" text file and generates an "myprogram.s" text file containing the x86 instructions to be assembled and linked by the GCC toolchain.
I would like now to be able to support Windows as well. What is the most straightforward way of doing that? Specifically:
1) Is Visual Studio the "standard" toolchain for Windows?
2) I want to be able to generate an assembly file and have it compile naturally with the rest of a large C/C++ project. What assembler should I be targeting?
Thanks very much for your help.
-Patrick

A:

The two major assembly syntax are:
-Intel Syntax: [opcode] [destination], [origin] (ex: mov eax, 10)
-AT&T Syntax: [opcode] [origin], [destination] (ex: movl $10, %eax)
Because you where targeting GCC you most probably was generating assembly in AT&T syntax.
Most assembler of the common toolchain in Windows use Intel Syntax, Visual Studio assembler use Intel Syntax, MASM and NASM too.
Question 1) Yes Visual Studio is the defacto toolchain in Windows (this don't mean that it's the only one or the better or anything, but it's the most used toolchain when working in Windows). GCC work in Windows, Intel Compiler integrate very well with VS and Embarcadero is leading the way of clang base compiler in Windows. When you are working in multi plataform project the common used compilers combination are GCC - VC++ (by far) and Intel,GCC - Intel,GCC.
Question 2) If you would like to assemble in Windows with the common toolchain you would need to generate Intel Syntax, if you have AT&T Syntax already working would be fast enough. My recommendation here if you like to push the project forward is to use for example LLVM or another library, to translate your language source code into intermediate representation (ex: LLVM IR) and from there to assembler (note: LLVM handle AT&T and Intel syntax)


Q:

Windows Networking - Treat two subnets as one network

We have an existing (old) network (10.0.0.0/24) and we're trying to add another (new) subnet (20.0.0.0/24) using a Cisco 2901 router. I added the appropriate routes and tested everything out. We're good. I can ping across to the old subnet, can get to the Internet, etc.
On the new subnet we have a Cisco 2504 WLC with a few access points. The WLC hands out DHCP. I can connect to that network and get online.
On the old subnet we have a server running Windows Server 2008 R2. Windows Firewall is turned off both on this server and on all clients. Due to some organizational constraints we have to be able to browse to \Server1 from our new subnet but we cannot.
In other words, a client on the old network can see the server under "Networking" in Windows. a client on the new network cannot, but if you manually browse to \10.x.x.x (The server's IP) I can access everything as expected. So, the question is this...
In this scenario, how can I get a network of Windows 7 Pro machines on multiple subnets to see this all as one network from a Windows perspective? Note there is no domain controller, no ADDS, etc. This Server is the only one on our network and just acts as a file share of sorts.

A:

"Seeing" the network is a function of several components, but is largely facilitated by NetBIOS broadcasts. Broadcast traffic is typically blocked by a router. You can do one of two things:

Configure the router to forward broadcast traffic between the two networks.
Install and configure a WINS server and configure all of your clients to use the WINS server.

http://technet.microsoft.com/en-us/library/cc787830(v=ws.10).aspx


Q:

Pandas UnicodeDecodeError while using read_sql

I am trying to execute SQL queries using pandas.read_sql. It usually works, but for certain queries I run into this error:
  File "C:\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1454, in _fetchall_as_list
    result = cur.fetchall()

    UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 3: ordinal not in range(128)

I tried solutions suggested for a very similar problem here (UnicodeDecodeError with pandas.read_sql) but it didn't resolve the issue.
I am using cx_oracle library for the database connection.
I tried
db = cx_Oracle.connect(user,pwd, dsn_dict[dbname],encoding='utf-8')

but when I check the encoding using
print(db.encoding)
print(db.nencoding)

I always get
ASCII
ASCII

I tried changing NLS_LANG using
os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.US7ASCII'

but it results in the same error
These are the database NLS parameters:
NLS_CHARACTERSET    US7ASCII

NLS_NCHAR_CHARACTERSET  AL16UTF16

I ran the same query in access and I notice this character in the query result, which might be causing this issue:
¿

Basically, I don't know how to set proper encoding to deal with the problem. Any help is appreciated. Thank you.
SOLUTION:
For reference, I solved this by setting
os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'

I dont like doing this though. better solutions are appreciated.

A:

With cx_Oracle 6 this should work for you:
cx_Oracle.connect("user/pw@dsn", encoding = "UTF-8", nencoding = "UTF-8")
Since your database encoding is ASCII you could even just set the nencoding parameter. If you are going to use the NLS_LANG environment variable, make sure to you the real UTF-8 encoding. That is called AL32UTF8 in Oracle -- for historical reasons!


Q:

Data Modeling: Supertype / Subtype

Looking to figure out the proper way to model the below requirements.

There are 3 types of “parties” to be concerned with, a Fan, a Band, and a BandMember.
That BandMember will always be associated with a Band and can also be a Fan of any band.
There are common attributes between a Fan, a Band, and a BandMember, but each of these 3 will also have their own unique attributes.
A Fan can be a fan of of any Band or none at all

This is a small part of a bigger thought but it is creating confusion in expanding the model.  I believe it would have to be diagram 2 or some other option since I don't see how a BandMember can be associated with a Band in the first model.
I appreciate any input.

A:

Caveat

First a couple of caveats for understanding the limitations.  All the data being used or stored needs to be considered/modelled together.  Eg. you have found that out anyway in your "creating confusion in expanding the model". From my side, not knowing how the Parties (subtypes) are related to other entities, limits me from provided a totally correct answer (that will not change).
Since you are providing the data in two tranches, therefore the answer will be in two tranches, and the second tranche will require changes to the first model.  Not a complaint, just advising you beforehand, as that could be avoided if I saw all the data up front.
It is really great that you appreciate the need for (a) modelling the data and (b) going through the science (documented for over 30 years) of Conceptual, Logical, then physical.  That is exactly what I do. You cannot imagine the time and effort that is saved by the formal process.

However, that does not come across in my answers at SO, because it is a "question and answer" site, I have to answer at the level of the questioner. (I answer questions more fully than others, and even that, causes negative commentary !).  Be assured that I go through the formal sequence.
.

It must be mentioned that Entity Relation Modelling is the work of giants in the industry, E F Codd and P Chen.  The Methodology is based on their work, and was completed by R Brown in the 1980's.  IDEF1X became a NIST Standard in 1993. When I answer Data Modelling questions, I am not supplying some personal method that I wrote a book about, I stand on the shoulders of giants.

I adhere to the Relational Model by E F Codd & C J Date
The Principle of Full Normalisation by (?) C J Date & F Pascal
The Principle of Orthogonal Design by D McGoveran & C J Date.

Modelling Data

Yes, a Supertype-Subtype structure is correct here.  Unfortunately it is not common and therefore not commonly understood.
Separately, even where Subtypes are implemented, they are implemented in very limited fashion.  Subtypes have the effect of changing the Role of the Supertype. The correct implementation of that is very rare indeed, I have not seen this anywhere (except of course the academic journals and my own database implementations for customers).
Point is, that may look "complex" but it isn't, it is actually very simple.
This is where Ken Downs and Chris Behrens confuse modelled simplicity (highly extensible) with unmodelled implementation (incorrect and un-extensible), due to the simplistic approach advised by dwarves such as Martin Fowler.  No offence, I understand that people are attached to, and will defend, what they know, however limited as that may be.

notice that each Subtype is also a perfectly valid Entity (Table in the Physical, when we get to that stage) in its own right, and can stand on its own.
for the lower levels or transaction or function tables, which have Relations to these Subtypes, the trick is to use the correct Subtype (Role).  The common mistake is they use Party, and then the meaning of the Subtype or Role, and the correct Referential Integrity is lost.
separately all the RoleNames are derived from Party, but that is not a valid reason to useParty instead of the correct Role.
Here you understand the data really well, but (no one has taught you this and) you have confused Roles and Subtypes.
BandMember and Fan are not Parties.  They are Persons, first (and Person is a Party, second)

In order to provide clarity re those points, at this Conceptual level, we need to work with Entities and Identifiers (not Attributes), rather than just Entities.  Therefore I have provided that as well.

It appears you have ERwin (the best!); it allows you to view the single model at that level very conveniently.  Do implement the Identifiers in the Entities, even at this abstract level.

Obstacle
I point these out before presenting the model, because you appear to be seriously interested in learning IDEF1X, the Standard methodolgy for modelling Relational Databases, with a view to easing your models in the future. SO or any website, is not a good medium for formal interactive education, but we will give it our best shot.

In model (1), Band cannot be Independent (square corners): since it is identified as being Dependent on Party; it is a Subtype of Party; and it has the same Identifier.
The missing Cardinality is critical.  Putting it in will actually assist in resolving the model.  I am not fussed re IDEF1X (circles) vs IEEE (crows feet), but I always put them in as I go, and keep changing them as the model progresses.

your model does not show that a Band is made up of one-to-many Members. Et cetera.
.
While programming can progress incrementally (once the definition is stable)), modelling does not. Eg. you can't model the Entities but not the Relations; the Relations but not the Cardinality.  That is why they are different sciences, programmers do not make good modellers, and vice versa.
.

At this stage the Rules are also very important.  Modelling is, in fact, modelling the Rules.  Therefore correcting or modulating the Rules is part of the Modelling process.

A Fan can be a fan of of any Band or none at all is not reasonable. If a Person is none at all then they are a member of the general public, and they have no Relation to any Band.  An ordinary Person.
A Fan has a Relation to at least one Band.  In fact, having a Relation to a Band is what takes a Person out of that realm and causes storage of Fan details or specific fan-of-band details.
If there are is such an Entity as Fan with no Band (ie. you are storing details of that, separate to Fan as per my model), please advise, and I will change the model (paper is cheap!).

Verb Phrases are also important at this stage; no less than my point re Rules and Cardinality above, it is a part of the modelling process, and it needs change/modulation as the model progresses.  You will not believe how important it is to gett the Verb Phrases right. Putting them in may well have assisted you in clarifying Subtypes vs Roles. Here is a definition that every Data Modeller knows by heart.

The Entities are the Nouns in the model
The Relations are the Verbs, the actions that take place between the Nouns
The Verb Phrases define those actions (that's why they are accurately called Verb Phrases, it is not a funny name).

As described in the IDEF1X Notation document, for Associative tables, read the Verb Phrase "through" them, to the parent on the other side of the association.

A Person makes one-to-many Bands, and is thus a Member
A Band is made up of one-to-many People, who are Members
A Person patronises a Band, which makes them a Fan (not merely a Person who has a row in the Fan table)
A Band depends on People, who are Fans

Coming up with the shortest, most meaningful, Verb Phrase; not using simplistic words ("comprises" is to be avoided"), is a challenge for Modellers. Feel free to ameliorate the Verb phrases I supplied.

▶Party Entity Relation◀
Readers who are unfamiliar with the Standard for Modelling Relational Databases may find
▶IDEF1X Notation◀ useful.
Note
All I have done is resolve the Subtypes; Roles; the Cardinality of the Relations, as identified above.

The relevance of the Subtypes vs Roles will be more clear to you when you evaluate your second tranche or your transaction Entities (as you have stated, here we have only Identifying Entities).
Identifiers.  This is worth spelling out, not only for the purpose of clarifying the model, also because it is a good example of IDEF1X Identifiers being used, and the power they deploy.  You have already indicated in your model that you understand that (solid lines), I am merely giving it the full treatment.

Person and Band are Subtypes of Party.  They are also Roles of Party. Therefore we use PersonId and BandId from that point downward, not PartyId (even though it is PartyId).
When a Person plays the Role of Member, we use MemberId (which is PersonId, which is PartyId).
When a Person plays the Role of Fan, we use FanId (which is PersonId, which is PartyId).

Let's say you were listing the Fans of a Band, your query is centred on Fan.  If you had those Id Surrogate Keys on every table, you would be forced to join Person, then join Party. But with the Relational Identifiers you have, you can go directly to Party:
SELECT Name FROM Party WHERE PartyId = FanId

and skip the table in-between.  Yes, the truth is, Normalised Relational Database require fewer joins, less resources (processing, cache, disk I/O), and that is one reason why they perform so much better.  The myth has no scientific basis.

Please evaluate and ask specific questions.


Q:

Вызвать файл по абсолютному пути. html

Есть сервер debian с apache2.2.22
Как вызывать отсюда /var/www/folder/index.html файл с расположением, например /usr/src/file.txt .
Если указываю src='/usr/src/file.txt', то получаю ошибку File does not exist: /var/www/folder/usr

A:

вы можете воспользоваться директивой alias. примерно так:
alias /usr/src/ /usr/src/

область применения — глобальная конфигурация всего сервера или конфигурация конкретного virtualhost-а.


Q:

appropriate index selection among multiple index's on a table in mysql is not happening

I have a MySql table with a hash index's, like this
CREATE TABLE `forecast_item_store` (
`product_key` int(11) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`store_key` int(11) DEFAULT NULL,
`collection` varchar(45) DEFAULT NULL,
`category_key` int(11) DEFAULT NULL,
`flag` int(5) DEFAULT NULL,
`directly` tinyint(1) DEFAULT '1',
KEY `product_key_fr_idx` (`product_key`),
KEY `store_key_frr_idx` (`store_key`,`parent_id`,`product_key`),
KEY `product_key_parent_id` (`product_key`,`parent_id`),
KEY `i1` (`product_key`,`flag`,`store_key`,`parent_id`) USING HASH,
KEY `i2` (`product_key`,`store_key`,`parent_id`) USING HASH,
KEY `i3` (`product_key`,`flag`,`parent_id`) USING HASH,
KEY `i5` (`category_key`,`product_key`,`parent_id`) USING HASH,
KEY `i4` (`product_key`,`flag`,`category_key`,`parent_id`) USING HASH,
KEY `i` (`category_key`,`product_key`,`flag`,`parent_id`) USING HASH,
CONSTRAINT `product_key_fr` FOREIGN KEY (`product_key`) REFERENCES `dim_product`  (`product_key`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `store_key_frr` FOREIGN KEY (`store_key`) REFERENCES `dim_store`  (`store_key`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB

for the following query it is not considering index,i
select
    count(store_key)
from
    forecast_item_store
where
    category_key = 1 and product_key = 8981
        and flag = 1
        and parent_id = 2759;

it is considering index i5. why?

A:

while running a query, mysql picks the best index for it from a bunch of indices, which might not be the best at all. So in order to use a particular index you can force/tell mysql to use it. see the link


Q:

Symfony OneToOne Doctrine like in QueryBuilder

like in symfony's query builder doesn't work and show me error!
this is my query:
    $apiToken = $this->createQueryBuilder('ud')
        ->select('ud.apiToken')
        ->where('ud.user LIKE :userPhone')
        ->setParameter('userPhone','%'.$phone)
        ->getQuery()
        ->getResult();

    return $apiToken;

and this is the error:
[Semantical Error] line 0, col 64 near 'user LIKE :u': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

cant find any extension stuff for like in query builder or useful description!
this is my UserDevice Entity:
class UserDevice implements UserInterface, \Serializable
{
    /**
     * @var int
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="notification_token",type="string", nullable=true)
     */
    private $notificationToken;

    /**
     * @ORM\Column(name="api_token" , type="string", unique=true, nullable=true)
     */
    private $apiToken;

    /**
     * @ORM\OneToOne(targetEntity="User", inversedBy="device", fetch="EAGER")
     * @ORM\JoinColumn(name="user_phone", referencedColumnName="phone")
     */
    private $user;

}

A:

You should use join query between table UserDevice and User.
$apiToken = $this->createQueryBuilder('ud')
        ->select('ud.apiToken')
        ->where('u.phone LIKE :userPhone') // here Users phone field
        ->innerJoin('ud.user', 'u')
        ->setParameter('userPhone','%'.$phone)
        ->getQuery()
        ->getResult();

return $apiToken;


Q:

Data synchronization from an android content provider to my remote server

I'm developing an app (Android 4.0) which relies on a background service to sync specific data from probably sqlite to a remote mysql database.
I am pretty new to Android dev (but not programming) and hence am still struggling with where to begin and how to construct the system. I am planning on leveraging:
"Developing Android REST client applications" by Virgil Dobjanschi (2010)
as a starting point. What he demonstrates is a high level approach to developing such a system which is excellent.
My question is, in two years or so has anything changed, or would this still be considered a viable approach? Any other help you can give having gleened my situation will help me immensely.
Thanks.

A:

Here is an updated approach that I have found very useful
Use an Intent Service to get off the main thread for your requests.  If you want more info about services refer to this.
Hope this helps!


Q:

Router - can I remotely force a router to send my packets through a specific route? (in packet/network layer)

I'm a newbie in network programming in C/C++ and I'm working on raw sockets to program a simple ping or traceroute application as they are written in common network programming books.
Programs like traceroute, manipulate packet headers like TTL so that they can retrieve router IP addresses.
I know that routers are designed to find best routes by finding nearest routers in a simple manner.
I was wondering if it's possible to find a way to manipulate packet headers in a way that packets force a router to choose a specific route instead of their default route, I mean to manipulate packets the way traceroute does and create a manual route to destination.
In first step, is it even possible? if not and there's any similar way to achieve this goal, what is it?

A:

In practice, clients can't affect the router's forwarding decision. Initially, source routing (in RFC 791) was designed to implement this but it's grown out of use and has very little support today.
Strictly speaking, there is no way to accomplish what you're asking. With some more details to the exact intention there might be ways to get what you want (router discovery? network scan? vulnerability scan?).


Q:

Root a Moto G running 4.4.4 KitKat

I have a Moto G. I need to root my phone to use some apps.
Can anyone given me the steps to root a Moto G running 4.4.4 KitKat (the most safest and easyist way).

A:

How to Root Moto G
There are are three simple steps only

UNLOCK BOOTLOADER
FLASH CUSTOM RECOVERY [I USED CWM]
FLASH SUPERSU

DONE
Yeah ...you don't need to downgrade your bootloader which is very risky
Procedure

UNLOCKING BOOTLOADER :- i thinks its already explained well at different sites and motorola's site also [ i used this guide Moto-g-unlock-bootloader-and-root only for unlocking]
FLASHING RECOVERY-

You need 3 things
(a) motorola usb drivers [download from here ]
(b) adb drivers (download from here ]
(c) Custom recovery (download from here ] i used cwm without touch OR USE PHILZ RECOVERY (4.4.4) CLICK HERE TO DOWNLOAD
Real procedure:-

install motorola usb drivers
extract adb drivers anywhere in your computer
copy recovery.img [i renamed it to only recovery] into adb tools folder
boot your phone into fastboot mode by pressing volume down key and pressing power key simultaneously , and then releasing power key .
connect your moto g to your computer through data cable
go into adb tools folder => while pressing shift key => right click => and click open cmd here !
type [fastboot flash recovery recovery.img] and press enter { IGNORE Mismatched partition size' AFTER FLASHING RECOVERY }

DONE  just press volume down and then volume up to boot into cwm

FLASHING SUPER SU
DOWNLOAD THIS FILE FROM HERE
PUT IT IN INTERNAL MEMORY

PROCEDURE => IN CWM =>INSTALL FROM SD CARD => CHOOSE SUPER SU => RESTART
It will ask 'root is broken' WHEN REBOOTING FROM CWM. CHOOSE YES
DONE !
I recommend these apps you should install first after rooting

Greenify (getting awesome battery backup )
xposed installer
gravitybox
tinted status bar (i love this module..make your android like ios7)
Titanium Backup


Q:

Unity e UnitOfWork

Salve galera,
Criei um pequeno projeto para aplicar IoC utilizando o Unity da MS. Primeiramente sempre usei o conceito de UnitOfWork apenas instanciado ele em meus controllers, mas agora quero injetar eles.
Quando inicio a aplicação web ele lista corretamente as informações do banco, porem sempre que chamo o SaveChanges está dando o erro: {"The operation cannot be completed because the DbContext has been disposed."}
Não estou conseguindo achar o motivo disso, visto que o contexto está sendo injeto no UnitOfWork corretamente, se não ele nem conseguiria listar as informações do banco. Segue meu código.
Unity Config
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Mvc;
using MyMoney.DAL.Repositories;
using MyMoney.DAL.UnitOfWork;
using MyMoney.Domain.Interfaces.Repositories;
using System.Web.Mvc;

namespace MyMoney.DAL.Unity
{
    public class Bootstrapper
    {
        public static IUnityContainer Initialise()
        {
            var container = BuildUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            return container;
        }
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.RegisterType(typeof(ITransaction), typeof(TransactionRepository));

            container.RegisterType<IUnitOfWork, UnitOfWork.UnitOfWork>(new ContainerControlledLifetimeManager());

            return container;
        }
    }
}

UnitOfWork
using System;
using MyMoney.DAL.Context;
using MyMoney.Domain.Interfaces.Repositories;

namespace MyMoney.DAL.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private MyMoneyContext _context;
        private ITransaction _transactionRepository;

        public UnitOfWork(MyMoneyContext context, ITransaction transactionRepository)
        {
            this._context = context;
            this._transactionRepository = transactionRepository;
        }

        public ITransaction TransactionRepository
        {
            get
            {
                return _transactionRepository;
            }
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

Repositorio base
using MyMoney.DAL.Context;
using MyMoney.Domain.Interfaces.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace MyMoney.DAL.Repositories
{
    public abstract class RepositoryBase<TEntity> : IDisposable, IRepositoryBase<TEntity> where TEntity : class
    {
        protected MyMoneyContext db;

        public RepositoryBase(MyMoneyContext db)
        {
            this.db = db;
        }

        public virtual void Add(TEntity obj, Guid userId)
        {
            db.Set<TEntity>().Add(obj);
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    db.Dispose();
                }
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public virtual IEnumerable<TEntity> GetAll(Guid userId)
        {
            return db.Set<TEntity>().ToList();
        }

        public virtual TEntity GetById(int id, Guid userId)
        {
            return db.Set<TEntity>().Find(id);
        }

        public virtual void Remove(int id)
        {
            TEntity obj = db.Set<TEntity>().Find(id);
            db.Set<TEntity>().Remove(obj);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        public virtual void Update(TEntity obj)
        {
            db.Entry(obj).State = EntityState.Modified;
        }
    }
}

Repositório
using MyMoney.DAL.Context;
using MyMoney.Domain.Entities;
using MyMoney.Domain.Interfaces.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MyMoney.DAL.Repositories
{
    public class TransactionRepository : RepositoryBase<Transaction>, ITransaction
    {
        public TransactionRepository(MyMoneyContext db) : base(db)
        {
        }

        public override IEnumerable<Transaction> GetAll(Guid userId)
        {
            return db.Transations.Where(x => x.UserId == userId).ToList();
        }

        public override void Add(Transaction transaction, Guid userId)
        {
            transaction.UserId = userId;
            db.Transations.Add(transaction);
        }

        public override Transaction GetById(int id, Guid userId)
        {
            return db.Transations.Where(x => x.UserId == userId && x.Id == id).FirstOrDefault();
        }
    }
}

Controller
using AutoMapper;
using MyMoney.Domain.Entities;
using MyMoney.MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Data.Entity.Validation;
using System.Text;
using MyMoney.DAL.UnitOfWork;

namespace MyMoney.MVC.Controllers
{
    public class TransactionsController : Controller
    {
        readonly IUnitOfWork _unitOfWork;
        readonly Guid userId;

        public TransactionsController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            userId = new Guid(System.Web.HttpContext.Current.User.Identity.GetUserId());
        }

        // GET: Transactions
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult TransactionList()
        {
            var tList = Mapper.Map<IEnumerable<Transaction>, IEnumerable<TransactionViewModel>>(_unitOfWork.TransactionRepository.GetAll(userId));

            return this.PartialView("TransactionList", tList.ToList());
        }

        public PartialViewResult EditCreateForm(int id = 0)
        {
            TransactionViewModel viewModel = null;

            if (id > 0)
            {
                var transaction = _unitOfWork.TransactionRepository.GetById(id, userId);
                viewModel = Mapper.Map<Transaction, TransactionViewModel>(transaction);
            }

            return this.PartialView("EditCreate", viewModel);
        }

        [HttpPost]
        public ActionResult EditCreate(TransactionViewModel viewModel)
        {
            try
            {
                if (viewModel.Id > 0)
                {
                    var transactionDomain = Mapper.Map<TransactionViewModel, Transaction>(viewModel);
                    _unitOfWork.TransactionRepository.Update(transactionDomain);
                    _unitOfWork.Save();

                    return Json(0);
                }
                else
                {
                    var transactionDomain = Mapper.Map<TransactionViewModel, Transaction>(viewModel);
                    _unitOfWork.TransactionRepository.Add(transactionDomain, userId);
                    _unitOfWork.Save();

                    return Json(0);
                }
            }
            catch (Exception ex)
            {
                var msg = new StringBuilder();

                if (ex is DbEntityValidationException)
                {
                    var errors = ex as DbEntityValidationException;
                    foreach (var err in errors.EntityValidationErrors.SelectMany(x => x.ValidationErrors.Select(get => get.ErrorMessage)))
                    {
                        msg.AppendLine(err);
                    }
                }
                else
                {
                    msg.AppendLine(ex.Message);
                }

                return Json(msg.ToString());
            }
        }

        [HttpPost]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                _unitOfWork.TransactionRepository.Remove(id);
                _unitOfWork.Save();

                return Json(0);
            }
            catch (Exception ex)
            {
                var msg = new StringBuilder();

                if (ex is DbEntityValidationException)
                {
                    var errors = ex as DbEntityValidationException;
                    foreach (var err in errors.EntityValidationErrors.SelectMany(x => x.ValidationErrors.Select(get => get.ErrorMessage)))
                    {
                        msg.AppendLine(err);
                    }
                }
                else
                {
                    msg.AppendLine(ex.Message);
                }

                return Json(msg.ToString());
            }
        }

        protected override void Dispose(bool disposing)
        {
            _unitOfWork.Dispose();
            base.Dispose(disposing);
        }
    }
}

Context
using MyMoney.DAL.EntityCfg;
using MyMoney.Domain.Entities;
using System;
using System.Data.Entity;
using System.Linq;

namespace MyMoney.DAL.Context
{
    public class MyMoneyContext : DbContext
    {
        public MyMoneyContext()
            : base("MyMoney")
        {

        }

        public DbSet<Transaction> Transations { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new TransactionConfig());
        }

        public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries().Select(x => x))
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Property("Date").CurrentValue = DateTime.Now;
                }

                if (entry.State == EntityState.Modified)
                {
                    entry.Property("Date").IsModified = false;
                    entry.Property("UserId").IsModified = false;
                }
            }

            return base.SaveChanges();
        }
    }
}

Se precisarem de mais informação eu coloco aqui.
Grato pela ajuda desde já.
Novas Informações:
Descobri o motivo do disposed. O contexto que uso quando chamo o SaveChanges, no controller é _unitOfWork.Save(), é uma instancia diferente do contexto que está no repositório. Isso é, no UnitOfWork é injetado uma instancia do contexto e no repositório é injetado outra instancia do contexto.
A solução pode ser chamar o SaveChanges no contexto do repositório, mas em minha opinião isso está errado, isso deve ficar dentro do UnitOfWork mesmo.
Outra solução é injetar o UnitiOfWork dentro do repositório e assim utilizar o contexto do UnitOfWork, só que no design que está ficaria assim:
UnitOfWork
public UnitOfWork(MyMoneyContext context, ITransaction transactionRepository)
{
   this._context = context;
   this._transactionRepository = transactionRepository;
}

public MyMoneyContext DbContext
{
   get
   {
      return _context;
   }
}

RepositoryBase
protected MyMoneyContext db;

public RepositoryBase(IUnitOfWork db)
{
   this.db = db.DbContext;
}

TransactionRepository
public TransactionRepository(IUnitOfWork db) : base(db)
{
}

O problema ai é que crio uma depenica circular que vai causar um stackoverflow. Alguém tem uma ideia melhor de como resolver?

A:

A  melhor solução para meu caso foi esta:
UnitOfWork
public class UnitOfWork : IUnitOfWork
    {
        private MyMoneyContext context = new MyMoneyContext();
        private TransactionRepository transactionRepository;

        public TransactionRepository TransactionRepository
        {
            get
            {
                if (transactionRepository == null)
                {
                    transactionRepository = new TransactionRepository(context);
                }

                return transactionRepository;
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

Instancio o contexto no UnitOfWork e crio um método que instancia o repositório passando a instancia do contexto, isso é, não injeto mais nada no UnitOfWork. Logicamente também alterei os construtores dos repositórios para receber o contexto e não o UnitOfWork e continuo usando o SaveChanges nele como eu queria. Tudo funcionando aqui. :)


Q:

multiple class selection targeting distinct children

try the following:
add two divs to a page with the same class name.
add two elements within each div: for argument's sake paragraphs.
make the text color of the first paragraph of each div red.
why can't i figure out how to do this relatively simple task without having to use id's?

A:

You can do it like this in jQuery (:first-child selector):
$(".myClass > :first-child").css('color', 'red');

But CSS will do it as well (CSS :first-child selector), and you should use this route if possible :)
.myClass > :first-child { color: red; }


Q:

background-color changes with jquery

This is my first attempt at writing jQuery myself. I'm trying to make it so when I hover on an instance of a name, the background changes to white as well as all the other instances of that name. Every name has a unique data-id that is common to all it's instances.
I think my jQuery goes in err at person = this.data("id"); I'm trying to assign the data attribute of the element hovered over and then change the background of all elements with that data attribute. Not sure if I'm even close.
Errors are as follows:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'data' localhost:60
  (anonymous function) localhost:60
  jQuery.event.special.(anonymous function).handle jquery.js:3353
  jQuery.event.dispatch jquery.js:3062
  elemData.handle.eventHandle

    <% @instances.each do |instance| %>
        <div class="instance" data-id="<%= instance.person.id %>" style="top:<%=top_helper(instance)%>px; left:<%= left_helper(instance) %>px; width:<%= width_helper(instance) %>px;">
            <%= instance.person.first_name %>, <%= instance.rank %>

    <% end %>

A:

You're very close!
$("div.instance").hover(function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","white");
 });

hover takes two functions as arguments, so your mouseout just does the opposite right after:
$("div.instance").hover(function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","white");
 },
 function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","gray");
 });


Q:

What to do if you do not "like" work produced by a freelancer

I have a situation I am not quite sure how to handle.
We have asked a freelancer to come up with some designs for a piece of e-learning. Now, as part of the quote he did some concepts which were part of the pitch so not charge for, however he missed a couple of key points I mentioned in the Brief (unfortunately it was an informal discussion instead of a brief, so I can forgive him that). I am not keen on the look'n'feel anyway, and some of the concepts in the pitch.
Now, I like some of his other stuff, and the design isn't bad, its just not good enough. So, I am thinking of asking him to produce a couple more - and pay him for them, BUT what If we do not like them again? Is that tough cookies? How do you handle this. I realize design is extremely subjective, but I know what I want and I know what makes a good looking usable website.
In general, what do you do if you do not like a piece of design you are paying for? If it was code - you wouldn't pay for something that didn't work.
I did think about posting on the Graphic Designer Stack, however I could predict their answers :)
Thanks guys!

A:

Have you talked to the freelancer? Often verbal requirements leave great gaping holes in expectations.
Separate the topics - first discuss what you think is missing  and how that gets fixed. Then if the freelancer wants to add cost, you can engage in that discussion with some facts behind you.
In the future, my recommendation is never do verbals. Even if you just do an email confirmation, writing it down does something to our brains that makes us strive for clarity.
Good luck. and remember, the freelancer wants to do a good job so he/she will get more work.

A:

Design requirements are actually hard to write. My main suggestions are:

Write down an overall goal
Detail the specific elements you want to see on the design
Include sites that use those elements (examples)
Let him show draft versions of the elements, so that he still has time to fix them without paying him again
Also, tell him to quote you for a few revisions of every design.  So if for 100 he will give you a logo, for 150 he may give you 5 revisions of that same logo.

A:

With design, you are often paying for the brainstorming/concepts themselves. Code will either work or not but design can "work" it just might not "work for you."
Directing a design process is very different from managing a software project. One thing that can help steer the designs is by doing a collage of images, looks, feelings, etc. that you want your site to have.
I first learned about this approach from the founder of an extremely successful design company: http://www.duffy.com/  and have used it since.  It helps take a lot of the subjective out of the process and gives some direction.
Its not perfect, since each aspect can be subject to interpretation. But it does act as a more "design-centric" common reference point to help hone in one where you're going and where you want to be.


Q:

How to apply brightness from one image onto another in Python

I'm trying to make a texture using an image with 3 colors, and a Perlin noise grayscale image.
This is the original image:

This is the grayscale Perlin noise image:

What I need to do is apply the original image's brightness to the grayscale image, such that darkest and lightest brightness in the Perlin noise image is no longer 100% black (0) and 100% white (1), but taken from the original image. Then, apply the new mapping of brightness from the grayscale Perlin noise image back to the original image.
This is what I tried:
from PIL import Image

alpha = 0.5
im = Image.open(filename1).convert("RGBA")
new_img = Image.open(filename2).convert("RGBA")
new_img = Image.blend(im, new_img, alpha)
new_img.save("foo.png","PNG")

And this is the output that I get:

Which is wrong, but imagine the dark and light orange and bright color having the same gradient as the grayscale image, BUT with no 100% black or 100% white.
I believe I need to:

Convert original image to HSV (properly, I've tried with a few functions from colorsys and matplotlib and they give me weird numbers.
Get highest and lowest V value from the original image.
Convert grayscale image to HSV.
Transform or normalize (I think that's what its called) the grayscale HSV using the V values from the original HSV image.
Remap all the original V values with the new transformed/normalized grayscale V values.

A:

 Why is it not working?
The approach that you are using will not work as expected because instead of keeping color and saturation information from one image and taking the other image's lightness information (totally or partially), you are just interpolating all the channels from both images at the same time, based on a constant alpha, as stated on the docs:

PIL.Image.blend(im1, im2, alpha)
Creates a new image by interpolating between two input images, using a constant alpha: out = image1 * (1.0 - alpha) + image2 * alpha
[...]
alpha – The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range.

 Basic working example
First, let's get a basic example working. I'm going to use cv2 instead of PIL, just because I'm more familiar with it and I already have it installed on my machine.
I will also use HSL (HLS in cv2) instead of HSV, as I think that will produce an output that is closer to what you might be looking for.
import cv2

filename1 = './f1.png'
filename2 = './f2.png'

# Load both images and convert them from BGR to HLS:

img1 = cv2.cvtColor(cv2.imread(filename1, cv2.IMREAD_COLOR), cv2.COLOR_BGR2HLS)
img2 = cv2.cvtColor(cv2.imread(filename2, cv2.IMREAD_COLOR), cv2.COLOR_BGR2HLS)

# Copy img1, the one with relevant color and saturation information:

texture = img1.copy()

# Replace its lightness information with the one from img2:

texture[:,:,1] = img2[:,:,1]

# Convert the image back from HLS to BGR and save it:

cv2.imwrite('./texture.png', cv2.cvtColor(texture, cv2.COLOR_HLS2BGR))

This is the final output:

 Adjust lightness
Ok, so we have a simple case working, but you might not want to replace img1's lightness with img2's completely, so in that case just replace this line:
texture[:,:,1] = img2[:,:,1]

With these two:
alpha = 0.25
texture[:,:,1] = alpha * img1[:,:,1] + (1.0 - alpha) * img2[:,:,1]

Now, you will retain 25% lightness from img1 and 75% from img2, and you can adjust it as needed.
For alpha = 0.25, the output will look like this:

 HSL & HSV
Although HSL and HSV look quite similar, there are a few differences, mainly regarding how they represent pure white and light colors, that would make this script generate slightly different images when using one or the other:

We just need to change a couple of things to make it work with HSV:
import cv2

filename1 = './f1.png'
filename2 = './f2.png'

# Load both images and convert them from BGR to HSV:

img1 = cv2.cvtColor(cv2.imread(filename1, cv2.IMREAD_COLOR), cv2.COLOR_BGR2HSV)
img2 = cv2.cvtColor(cv2.imread(filename2, cv2.IMREAD_COLOR), cv2.COLOR_BGR2HSV)

# Copy img1, the one with relevant color and saturation information:

texture = img1.copy()

# Merge img1 and img2's value channel:

alpha = 0.25
texture[:,:,2] = alpha * img1[:,:,2] + (1.0 - alpha) * img2[:,:,2]

# Convert the image back from HSV to BGR and save it:

cv2.imwrite('./texture.png', cv2.cvtColor(texture, cv2.COLOR_HSV2BGR))

This is how the first example looks like when using HSV:

And this is the second example (with alpha = 0.25):

You can see the most noticeable differences are in the lightest areas.


Q:

Could not verify SHA1 signature with RSA

I am trying to verify a certificate signature in Java, but it is failing. I guess there is a difference between SHA1 and SHA1withRSA, but how do I fix it?
This is code for signing in using C# (certificate is mycer.p12):
static string Sign(string token, string cer_name, string passw)
        {
            try
            {
                if (!File.Exists(cer_name))
                {
                    MessageBox.Show("File not found " + cer_name);
                    return "";
                }
                X509Certificate2 cert = new X509Certificate2(cer_name, passw, X509KeyStorageFlags.Exportable);
                RSACryptoServiceProvider csp = null;
                csp = (RSACryptoServiceProvider)cert.PrivateKey;
                if (csp == null)
                {
                    MessageBox.Show("No valid cert was found");
                    return "";
                }
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                byte[] data = encoding.GetBytes(token);
                RSACryptoServiceProvider rsaClear = new RSACryptoServiceProvider();
                rsaClear.ImportParameters(csp.ExportParameters(true));
                byte[] signature = rsaClear.SignData(data, CryptoConfig.MapNameToOID("SHA1"));
                bool isValid = csp.VerifyData(data, "SHA1", signature);
                if (isValid) return Convert.ToBase64String(signature).Trim(new char[] { '\0', '\n' }).Replace("\n", "");
                else
                {
                    MessageBox.Show("Siganture verification = FALSE");
                    return "";
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return "";
            }
        }

I use this command to extract public key

openssl pkcs12 -in mycer.p12 -clcerts -nokeys -out publicKEY.pem

And now this code in Java to verify but it returns false:
 public static boolean verify(String plainText, String signature, String publicKeyFile) {
            try {
CertificateFactory f = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate)f.generateCertificate(new FileInputStream(publicKeyFile));
                Signature publicSignature = Signature.getInstance("SHA1withRSA");
                publicSignature.initVerify(publicKey);
                publicSignature.update(plainText.getBytes("UTF-8"));
                byte[] signatureBytes = Base64.decode(signature);
                return publicSignature.verify(signatureBytes);
            } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException | UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            }
        }

A:

This post helped me https://stackoverflow.com/a/16980246/1444413
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream("mycer.p12"), "password".toCharArray());
String alias = (String) p12.aliases().nextElement();
X509Certificate c = (X509Certificate) p12.getCertificate(alias);
.... c.getPublicKey() ....

And then method verify().. returned true.


Q:

Firebase DB rules. Limit write access by phone number

I am using Firebase realtime datababase to implement synchronized DB for my applications on different platforms.
I need the way to allow everyone read from the database.
Only users authenticated by phone number, and if this number is in admins list, will be able to write to database. i didnt find a way to get phone number from "auth" object in DB rules.
Any help will be gratefully appreciated!
Here is DB Structure and rules I am using right now.
{
  "admins" : {
    "+97254000000" : {
      "name" : "Pirate Pirate",
      ...
    }
  },
  "mesages" : {
    "msg1" : {
      "orderTimestamp" : 1526916646226,
      "txt" : "some message"
    },
    "msg2" : {
      "orderTimestamp" : 1526916643522,
      "txt" : "some message"
    },
    "msg3" : {
      "orderTimestamp" : 1526916486229,
      "txt" : "some message"
    }
  }
}
// Database Rules
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

A:

Ok. After few hours of searching, i took a brake for a coffee, and found answer right away :)
Firebase database security rules comes with "auth" object that contain almost everything you ever need to check identity of the user.(phone number, email, name etc.)
So all information that I was looking for is placed in "auth.token" part.
New rules looks like:
{
  "rules": {
    ".read": "auth != null",
    ".write": "root.child('admins').child(auth.token.phone_number).exists()"
  }
}


Q:

Intel Team TCP Offloading not Working

I verified that TCP offloading is enabled in both the Intel properties for each of NIC that is the member of a two nic Adapter Fault Tolerance Team.
Also, the output of netsh int tcp show global verified that offloading is enabled.
However, when running netstat -tn none of the connections are offloaded, they are all InHost. Has anyone seen this problem before? Are adapter fault tolerant teams not compatible with offloading?

A:

"TOE (TCP Offload Engine) enabled devices can not be added to an ANS team and will not appear in the list of available adapters. If a TOE enabled device is added to an ANS team, it will not be able to do connection offloading while it is a member of the team."
Does this apply? http://public.support.unisys.com/pcproducts/esx/docs/DellDocs5.4/en/IntelNIC/usage.htm#adapter_teaming


Q:

How to identify type by hash value?

So I have basic UDP server, I've implemented some things like restoring byte array exactly how it was send by client (if it was retrieved out of order). Bassicaly, I have client, server and shared class library with types, objects of which could be send from client to server and vice versa. So now I came with idea to serialize some objects and send to server/client. But I need to know what type of object was recieved to deserialize it properly. Two ideas came into mind to solve this problem:

Make a "handshake". Send data about what object will be send after, its length, class name, etc. And after it retrive actual data and deserialize it. I know to do it, but since it's UDP, this "handshake" could be lost  and I need to re-ask it, so there is pretty complicated logic and network over-usage, but I know how to implement this.
And second one is identifing type by some hash value. So client sends data which contains hash value of type and piece of data (I will only send my own type's objects, so no need to implement this for C# and Framework types), and I need to determine type by this hash value and server could deserealize it properly.

So any ideas, how to implement this? It will be perfect if I manage to avoid reflection because it's slow (I don't care about huge switch statement if it works faster)

A:

I did this just today for a prototype I was working on. I defined my message stream thus:
First 4 bytes: length of the assembly-qualified type name as an Int32.
Next n bytes (where n is given by the first 4 bytes): assembly-qualified name of the type.
Rest of the message: the serialized object
It worked like a charm.


Q:

not able to execute .sh file

I downloaded modelsim install file which contained .sh file in it -setup.sh
I did the following two things

Right click->properties->permision->allow executing file as program
->double clicked the setup.sh -> RUN. Nothing happened.  No error...nothing.
In terminal

cd /to the path of the setup.sh
chmod -x setup.sh ...nothing happened no error nothing. The cursor passd on to the next line
./setup.sh ...nothing happened.

I also tired sh setup.sh and bash setup.sh, still nothing happened.
Downloaded the whole file again still nothing happened
Contents of the setup.sh file are:
#!/bin/sh
export SCRIPT_PATH=`dirname "$0"`
export CMD_NAME="$SCRIPT_PATH/components/QuartusSetupWeb-13.0.1.232.run"
eval exec "\"$CMD_NAME\"" $@

A:

chmod -x setup.sh is used to take out the execute permission for the script. The right way to give execute permission for the script is:
chmod +x setup.sh

See man chmod.
Another thing: because of $@, probably your script expects one or more arguments. Check in the same directory where the script is, maybe you have there a README file  to see the right usage. Or try to search for install instructions from where you downloaded it.

A:

Open the file manager,
Go to Edit->Preferences,
On the Behavior-tab under "Executable Text Files"-section set the option to

"Run executable text files when opened" or "Always ask"

Close it and try double clicking the file again


Q:

How to add divider in the bottom navigation view

How can I add a divider in the Bottom Navigation view?
Basically a separator between the icons
Thank you

A:

If I'm not wrong, the bottom navigation view has been created to match/follow Material Design guidelines and dividers are not supposed to be part of bottom navigation.
https://material.io/design/components/bottom-navigation.html