text:
Q: Why won't mgo unmarshall my struct properly? Earlier I posted this question asking about writing custom BSON marshalling/unmarshalling in Go using mgo. Now I've come to test it I think I've hit on a bigger problem. All my structs unmarshal to nil values.
This is my currency struct with the implementations of bson.Getter and bson.Setter:
type Currency struct {
    value        decimal.Decimal //The actual value of the currency.
    currencyCode string          //The ISO currency code.
}

/*
GetBSON implements bson.Getter.
*/
func (c Currency) GetBSON() (interface{}, error) {
    f, _ := c.Value().Float64()
    return bson.Marshal(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    }{
        Value:        f,
        CurrencyCode: c.currencyCode,
    })
}

/*
SetBSON implements bson.Setter.
*/
func (c *Currency) SetBSON(raw bson.Raw) error {
    decoded := new(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    })

    fmt.Println(string(raw.Data))
    bsonErr := raw.Unmarshal(decoded)

    if bsonErr == nil {
        fmt.Println("Debug: no error returned.")
        fmt.Println(decoded)
        c.value = decimal.NewFromFloat(decoded.Value)
        c.currencyCode = decoded.CurrencyCode
        return nil
    } else {
        return bsonErr
    }
}

By looking at the raw data, it marshals correctly, but when unmarshaling the resulting struct is just empty. Any ideas where I'm going wrong here? I used the go get gopkg.in/mgo.v2command literally yesterday so I would hope it was up to date and a bug like this wouldn't be present in "the hottest MongoDB driver around".

A: The GetBSON method should return the value to be marshaled, not the binary data resulting from marshaling it. That's why its first result type is interface{} and not []byte.


text:
Q: Rails 5 - Google Page Speed Insights - Leverage Browser Caching I've got a Rails 5 development site running on a public server. The project is also in development mode. I have been scanning the site with Google Page Speed Insights and one of the largest suggestions has been to leverage browser caching. So, I looked around on google and every answer says to use this code:
config.public_file_server.headers = {
  'Cache-Control' => 'public, s-maxage=31536000, maxage=15552000',
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}

Because the project is in development mode I put this code in my development.rb file rather than production.rb. I haven't been able to get any different results by doing this. No errors either. I could use some guidance! Thanks in advance.

A: Testing a rails server in development is like trying to empty the oceans of water. The main changes in the production environment are performance enhancing configurations (caching, class reloading, asset compilation, etc).
I'd suggest copying the default production configurations over to your development config if you want to test performance in development mode. This will probably make development painful for you, however.
Or switch environments to production.
What's your real goal here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How is the information displayed by "top" ordered by default? Been looking at top command as I'm new to Linux, but I can't see any correlations on how the displayed information is sorted. Can anyone sched any light on that?

A: The display starts by default sorted (descending) on the %CPU column.
However, the < and > keys select other columns: for example, a single > makes it sort on %MEM at the next refresh. The R key reverses the order: for example, 8 < plus R keeps the whole list in PID number order. The x key toggles highlighting of the complete column which is currently being sorted.
The f command opens up a menu where you can rearrange the whole panel as much as you wish, adding and hiding columns, etc. There are (around) 53 fields (columns) available for display: for example OOMs  --  Out of Memory Score.
info top should give you 2000 lines of detail, or try https://linux.die.net/man/1/top.

A: top will display first the most demanding processes (highest %CPU) and then the others by decreasing %CPU.


text:
Q: Subgroups of normal subgroups Suppose $G$ is a group and $N$ is a normal subgroup of $G$. If every subgroup of $N$ is a normal subgroup of $N$, could we say $N$ is subgroup of centralizer of $N$ in $G$?

A: This is not true: take $N=G=Q_8$, the quaternion group of order 8.


text:
Q: What's proper syntax for #each helper? So it seems Ember creates a controller (as I didn't specify one) and sets the model property defined in the route as a controller property.
Why is it that some of the other ways to loop through data that worked in previous versions simply don't output the data as show below?  Am I missing a dependency or have these methods simply been removed?
//this works

  {{#each post in model}}

    {{post.title}}

  {{/each}}

//block params doesn't work

Posts

  {{ log posts }}
  {{#each posts as |post|}}

    {{post.title}}

  {{/each}}

//neither does this

  {{#each}}

    {{title}}

  {{/each}}

//http-mock for api endpoint
res.send({
  'posts': [
    {
      id: 1,
      title: "Bananas"
    },
    {
      id: 2,
      title: 'Apples'
    }
  ]
});

//routes/posts.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.find('post');
  }
});

//package.json
  "devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "ember-cli": "0.2.7",
    "ember-cli-app-version": "0.3.3",
    "ember-cli-babel": "^5.0.0",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "^1.0.0",
    "ember-cli-htmlbars": "0.7.6",
    "ember-cli-ic-ajax": "0.1.1",
    "ember-cli-inject-live-reload": "^1.3.0",
    "ember-cli-qunit": "0.3.13",
    "ember-cli-uglify": "^1.0.1",
    "ember-data": "1.0.0-beta.18",
    "ember-disable-proxy-controllers": "^1.0.0",
    "ember-export-application-global": "^1.0.2",
    "express": "^4.12.4",
    "glob": "^4.5.3",
    "morgan": "^1.5.3"
  }

//bower
{
  "name": "blog",
  "dependencies": {
    "ember": "1.12.0",
    "ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
    "ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
    "ember-data": "1.0.0-beta.18",
    "ember-load-initializers": "ember-cli/ember-load-initializers#0.1.4",
    "ember-qunit": "0.3.3",
    "ember-qunit-notifications": "0.0.7",
    "ember-resolver": "~0.1.15",
    "jquery": "^1.11.1",
    "loader.js": "ember-cli/loader.js#3.2.0",
    "qunit": "~1.17.1"
  },
  "devDependencies": {
    "bootstrap": "~3.3.4"
  }
}

A: You are right that Ember creates posts controller (of Ember.Controller class) and sets the model property as posts router model promise resolved.
the right way:
{{#each model as |post|}}
   {{post.title}}
{{/each}}

comments on other ways:
{{#each post in model}} {{post.title}} {{/each}} works too but this syntax is outdated, will be deprecated on Ember 2.0 road
{{#each}} {{title}} {{/each}} - deprecated each without block param, title here is a property of posts controller, so wasn't set.
{#each posts as |post|}} {{post.title}} {{/each}} syntax is ok, but posts property wasn't set in posts controller
Deprecations links:
http://emberjs.com/deprecations/v1.x/#toc_more-consistent-handlebars-scope
http://emberjs.com/deprecations/v1.x/#toc_code-in-code-syntax-for-code-each-code
http://emberjs.com/deprecations/v1.x/#toc_objectcontroller


text:
Q: VBA INSERT INTO with ADO parameters I'm working in ACCESS VBA. I have a sub, which inserting the given collection into different tables, which depends on the current element. I just met and would like to work with this ADO parameter thing, because I have problem with the simple docmd.runsql "insert into...". The problem is that some strings contain "'" character, so I got error at these records. I searched and found ADO parameters, but no good tutorials and now I'm tired from the error codes which are not helpful either (coming from java).
My code snippet:
Dim adoCMD As Object
Set adoCMD = CreateObject("ADODB.Command")
With adoCMD
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdText
    .parameters.Append .CreateParameter("pKey", adInteger)
    .parameters.Append .CreateParameter("pTitle", adVarChar, 100)
    .parameters.Append .CreateParameter("pid", adInteger)
    .parameters.Append .CreateParameter("pAired", adDate)
    .parameters.Append .CreateParameter("pmtype", adInteger)
    .parameters.Append .CreateParameter("pSyear", adSmallInt)
    .parameters.Append .CreateParameter("pSeason", adInteger)
    If addDate Then
        .parameters.Append .CreateParameter("pAdded", adDate)
    End If
    For Each elem In ac
        If elem.aired >= seasonStart And elem.aired <= seasonEnd Then
            key = Nz(DMax("table_Akey", "table_A"), 0) + 1
            .parameters("pKey").Value = key
            .parameters("pTitle").Value = elem.title
            .parameters("pid").Value = elem.id
            .parameters("pAired").Value = elem.aired
            .parameters("pmtype").Value = elem.mtype
            .parameters("pSyear").Value = syear
            .parameters("pSeason").Value = season
            If addDate Then
                .parameters("pAdded").Value = Date
                .CommandText = "INSERT INTO table_A(table_Akey,title,id,aired,media,seasonyear,season,added) VALUES(pKey,pTitle,pid,pAired,pmtype,pSyear,pSeason,pAdded);"
            Else
                .CommandText = "INSERT INTO table_A(table_Akey,title,id,aired,media,seasonyear,season) VALUES(pKey,pTitle,pid,pAired,pmtype,pSyear,pSeason);"
            End If
        Else
            wCounter = wCounter + 1
            key = Nz(DMax("wskey", "ws"), 0) + 1
            .parameters("pKey").Value = key
            .parameters("pTitle").Value = elem.title
            .parameters("pid").Value = elem.id
            .parameters("pAired").Value = elem.aired
            .parameters("pmtype").Value = elem.mtype
            .parameters("pSyear").Value = syear
            .parameters("pSeason").Value = season
            .CommandText = "INSERT INTO ws(wskey,title,id,aired,media,wsyear,season) VALUES(pKey,pTitle,pid,pAired,pmtype,pSyear,pSeason);"
        End If
        .Execute
    Next elem
End With

I get the error: Runtime Error '3001' Arguments are of the wrong type, are out of acceptable range or are in conflict with one another
at the line
.parameters.Append .CreateParameter("pTitle", adVarChar, 100)

Maybe the whole code is wrong, I don't know how to do properly with ADO parameters, but you can see what I want to do. I give a collection to the function. I loop through the elements and place them the right table and I have one switch as well (addDae).
Please help me.

A: You could also write a function that escapes the DB single quote. Generally, a single quote is "escaped" by doubling it. It would be something like:
Function escapeDBquote(s As String) As String
    Dim sOut As String
    Dim i As Integer
    i = 1
    While (i <= len(s))
        If (Mid(s, i, 1) = "'") Then sOut = sOut +"'"
        sOut = sOut + Mid(s, i, 1)
        i = i + 1
    Wend
    escapeDBquote = sOut
End Function

and call it like:
Dim szSQL As String
szSQL = "insert into myTable (sfield1, ..) values ('" + escapeDBquote(myString) + "');"

(Note: haven't compiled this code; there could be some typos.)


text:
Q: OneToMany with composite key I have 2 classed User and Bottom , User has many relationship with Bottom.
User have 2 composite key
userId
class TireId {
 private String uId;
 private String schoolId
}

User entity :
@IdClass(UserId.class)
@Entity
Class User {

 @Id
 private String uId;
 @Id
 private String schoolId

    @OneToMany(mappedBy="user")
    private List<Bottom> bottoms;

}

BottomId :
class BottomId {
   private String bId;
   private String cId;
   private String schoolId;

}

Bottom class :
@IdClass(BottomId.class)
@Entity
class Bottom {
    private String bId;
   private String cId;
   private String schoolId;
    @ManyToOne
   private  User user;
}

In above case hibernate will create 2 additional column in Bottom table name user_uId and user_schoolId .
But I need User oneToMany relation with following relation
schoolId of user == schoolId of Bottom
and uId of user == cId of of Bottom

how can i archive this?

A: This is a "derived identity", so BottomId should look like this:
class BottomId {
    private String bId;
    private UserId user; // matches name of attribute and type of User PK
}

and Bottom should be mapped like this:
@IdClass(BottomId.class)
@Entity
class Bottom {
    @Id
    private String bId;

    @Id
    @JoinColumns({
        @JoinColumn(name="cId", referencedColumnName="uId"),
        @JoinColumn(name="schoolId", referencedColumnName="schoolId")
    })
    @ManyToOne
    private  User user;
}

Derived identities are discussed (with examples) in the JPA 2.1 spec in section 2.4.1.


text:
Q: Is there a way to make Resque distribute given jobs equally? I have 5 Resque workers setup like this:
QUEUE=* rake environment resque:work
QUEUE=* rake environment resque:work
QUEUE=* rake environment resque:work

when I run a heavy job like this:
100.times do
Resque.enqueue(DoTheJob)
end

First worker gets about 80 of the job and other workers share the rest...
In my case, I may have 40 concurrent and really heavy jobs -video transcoding-. They will be triggered consecutively and I want jobs to be seperated equally or at least fairly to my existing workers (they can be up to 30).
Is there an option or something like that?
How can I achieve this?
Thank you

A: Well, when I try the code above with a simplest Resque worker class structure like this:
class MyWorker
@queue=:test

def self.perform(data)

puts "Testing...."

end

end

100.times do
Resque.enqueue(MyWorker)
end

All the jobs are queued to the same worker.
BUT.
When I put a few seconds sleep to the worker, I see that jobs are distrubeted pretty fairly.
class MyWorker @queue=:test

def self.perform(data)

puts "Testing...."
sleep 3
end

end

I don't know what is Resque's algorythm for this purpose but looks like there's no problem with it.


text:
Q: Make sidebar stick when one of the child elements reaches top having the child element on top of it with an auto height I'm having a problem trying to make my sidebar stick in the correct height and making the desired effect, this is my code:
https://jsfiddle.net/oavgLrf9/
I want my sidebar to add a fixed class when the second module reaches top, the problem is that both of the modules use height auto so their height change depending of the monitor.

Also I want that when the user scrolls top the side bar goes top too, and when it reaches bottom changes to absolute, like this example:
http://jsfiddle.net/gmolop/y3tdL9wd/
I tried using the sticky-kit plug in  it does almost exactly what I want, would be the example 4, but it doesn't stick in the height I need because of these changing values.

A: you can use HcSticky to solve your problem.
http://someweblog.com/hcsticky-jquery-floating-sticky-plugin/
see examples:
http://someweblog.com/demo/hcsticky/


text:
Q: get a 3 column list on laravel filled with array data I have an array. In this array are multiple datas. Like name, created_at, updated_at, id...... and this for about 30 different products.
Now I want to output there names in the blade on 3 columns
Like :
product A product F product J
product B product G product K
product C product H product L
product D product I product M

( only the names )
I recieve all the names with
@foreach($products as $product)
    {{$product->name}}
@endforeach

It doesn't matters if it's in unordered list or on a table. I just want to get the product-names on 3 columns and per column about 10 names.
I tried multiple things out but couldn't make it.
Does anybody knows a solution for that?


text:
Q: Hibernate can't load Custom SQL collection There is a table Item like,
code,name
01,parent1
02,parent2
0101,child11
0102,child12
0201,child21
0202,child22

Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code :
class Item{
    String code;
    String name;
    Item parent;
    List<Item> children;

    .... setter/getter....

}

<hibernate-mapping>
    <class name="Item" table="Item">
        <id name="code" length="4" type="string">
            <generator class="assigned" />
        </id>
        <property name="name" column="name" length="50" not-null="true" />

    <many-to-one name="parent" class="Item" not-found="ignore">
        <formula>
        <![CDATA[
        (select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end))
        ]]>
        </formula>
    </many-to-one>

        <bag name="children"></bag>

    </class>

</hibernate-mapping>

I try to use formula to define the many-to-one relationship,but it doesn't work!Is there  something wrong?Or is there other method?
Thanks!
ps,I use mysql database.
add 2010/05/23
Pascal's answer is right,but the "false" value must be replaced with other expression,like "1=2".Because the "false" value would be considered to be a column of the table.
select i.code
from Item i
where (
  case length(code)
    when 4 then i.code=SUBSTRING(code,1,2)
    else 1=2
  end)

And I have another question about the children "bag" mapping.There isn't formula configuration option for "bag",but we can use "loader" to load a sql-query.I configure the "bag" as following.But it get a list whose size is 0.What's wrong with it?
<class>
     ... ...
   <bag name="children">
        <key />
        <one-to-many class="Item"></one-to-many>
        <loader query-ref="getChildren"></loader>
    </bag>

    </class>
    <sql-query name="getChildren">
    <load-collection alias="r" role="Item.children" />
        <![CDATA[(select {r.*} from Item r join Item o where
        o.code=:code and
         (
        case length(o.code)
        when 2 then (length(r.code)=4 and SUBSTRING(r.code,1,2)=o.code)
        else 1=2
        end ))]]>
    </sql-query>

A: According to the documentation, you're supposed to return the value of the computed foreign key, nothing more:

formula (optional): an SQL expression that defines the value for a computed foreign key.

So I would expect a query like this:
select i.code
from Item i
where (
  case length(code)
    when 4 then i.code=SUBSTRING(code,1,2)
    else false
  end)

Disclaimer: not tested.


text:
Q: Tool to plot thread context switch I'm looking for a tool for performance analysis and debugging that plots threads context switches, and maybe semaphore states, events, ...
I've used tools like that in the embedded world but I'm now looking for the same in the windows or Linux platforms.
The application I want to profile is a c++ multithreaded application.
Does anyone has a tool to recommend for this ?

A: For Linux and Solaris the Oracle Thread Analyzer from the Oracle Solaris Studio (it also runs on Linux despite its name) can provide a lot of insight into the performance problems of multithreaded applications. Besides Oracle Solaris Studio is still free.
Intel VTune Amplifier XE (previously called Intel Thread Analyzer) is available on both Linux and Windows.

A: On Windows you can use xperf tool to collect and plot context switches. It's a free tool, which is a part of Windows Performance Analysis Developer Center. Worked fine for me, see screenshot.

A: Windows Performance Monitor?
perfmon.exe
I think it's standard on most Windows Platforms and provides information on context switches and much much more.
Windows only I'm afraid though.

A: Probably this is not the tool you are thinking about, but it is simple, fast and can be useful.
When using GDB, you can type:
info threads

to see information about threads being run. Next you can switch to the chosen thread and print the backtrace to see, where it was:
thread <thread-id>
bt


text:
Q: How to make a rectangle of characters? How to make a rectangle of characters?
I need to make such a picture appear in the console
 **********
*          *
*          *
*          *
 **********

But I get this:
*********
*********
*********
*********
*********

Sides a and b are entered from the console.
    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

A: public class Rectangle {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.printRectangle(7,9);
    }

    private void printRectangle(int row, int col) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
                        || !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
                    System.out.print(" ");
                }
                else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }

    private boolean isFirstOrLastRow(int currentRow, int row) {
        return currentRow == 0 || currentRow == row - 1;
    }

    private boolean isFirstOrLastCol(int currentCol, int col) {
        return currentCol == 0 || currentCol == col - 1;
    }
}

The four corners and the middle position should output spaces, so we should judge whether it is the four corners or the middle position,I use isFirstOrLastRow and isFirstOrLastCol to help judge.
here is the result for input 7,9
 *******
*       *
*       *
*       *
*       *
*       *
 *******

A: A pretty concise way to do it just a few lines:
int a = requestNumber();
int b = requestNumber();

System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {
    System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));

EDIT: Fixed typo, works now!


text:
Q: Why did http request and backend service save string data type to database with double quotes? I am working on a web application. Backend: spring boot and frontend: vuejs.
When I test with Swagger, my controller that provide to save a string data to database work fine but save with double quotes. At the same time when I wrote my data from an input in vue js I face to face same mistake again. My data is in my database but with double quotes.
I hope I can explain my problem clearly.
I don't want to see "sample data" in database, it will be just sample data without double quotes.
@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody String sampleName)

{
    return this.columnTableService.addSampleName(clmnId, sampleName);
}

A: I found where I made mistake. @RequestBody had got directly String type. I changed my parameter's type to "Map<String, object>" and this fixed my problem. I add my new code block.
@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody Map<String, Object> data)
{

    return this.columnTableService.addSampleName(clmnId, data);
}

(Of course you should change your method that is in service and class that implemented this service.)


text:
Q: Editor Unable to Upload Files in ExpressionEngine 2.2.0 I recently upgraded from EE 1.6.6 -> 2.2.0.
After the upgrade one of my co-workers that is permissioned as an "Editor" on the site said that she can not longer find the place in the control panel to upload photo files.
I logged in as her and confirmed that the file upload feature is not exposed to her view.
I then logged in as admin and confirmed that "Editors" are allow to upload files (at the botton of the File Upload Permissions page) http://expressionengine.com/legacy_docs/cp/admin/weblog_administration/file_upload_preferences.html
It definitely says that "yes" Editors can upload files….
What am I missing?  Is there something else I need to enable?  Some config that might have been lost in my 2.2.0 upgrade?

A: You have probably sorted this by now but if she cannot see the file manager link at all, check that the member group has permission to access this via member groups > edit group > control panel access > can access content: file manager.

A: Are you referring to the "Upload File" link, which was previous in a green box under the "Submit Entry" button?
If so, this feature is now exposed through a small icon that is optionally enabled per field:


text:
Q: Nested replace for update I have package with cursor and I want to replace some characters on a column? The select works but I need to update, thank you.
Here is my code :
DECLARE
    CURSOR get_data
    IS
        SELECT e.column1,
               e.column2,
               d.column3,
               d.column4
          FROM table1 e, table2 d
         WHERE e.column1 = d.column3;
BEGIN
    FOR i IN get_data
    LOOP
        UPDATE table1
           SET column1 = REPLACE (REPLACE (column1, 'OPRS', 'V'), 'ABV', 'T')
         WHERE column1 = i.column1
           AND column1 LIKE '2027044%';

        UPDATE table2
           SET column3 = REPLACE (REPLACE (column3, 'OPRS', 'V'), 'ABV', 'T');
    END LOOP;
END;

The error is:
ORA-00001: unique constraint (DB_KSS_ONLINE.NETOPERIDX) violated ORA-06512: at line 10
00001. 00000 - "unique constraint (%s.%s) violated"
*Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level.
*Action: Either remove the unique restriction or do not insert the key.

A: The code would be:
update table1
   set column1 = REPLACE(REPLACE(column1, 'OPRS', 'V'), 'ABV', 'T')  ;

I think you are just missing the =.
I would recommend adding:
where column1 like '%OPRS%' or column1 like '%ABV%'

This limits the update logic only to the rows that match.

A: From your cursor query we can see that table1.column1 and table2.column3 are identifiers. These are also the columns you are manipulating in the UPDATE statements. So there is a gap in the procedural logic which means the SET clause is generating duplicate values in a unique column. It seems your data has a different state from what you think it has.
To fix this you need to do some investigation of the data.

*

*Is DB_KSS_ONLINE the real name of table1 or table2 in your redacted code? This tells you which data you need to investigate.

*Run a SELECT statement which reproduces the updated values. This tells you what additional rule (filter) you need to put in place.

Something like this:
SELECT e.column1
       , case when e.column1 like '2027044%' then
              REPLACE(REPLACE(column1, 'OPRS', 'V'), 'ABV', 'T')
              else null
         end as updated_col1
       , d.column3
       , REPLACE(REPLACE(column3, 'OPRS', 'V'), 'ABV', 'T') as updated_col3
       , e.column2
       , d.column4
  FROM table1 e, table2 d
  WHERE  e.column1 = d.column3
  order by 4 nulls last, 2 nulls last ;


text:
Q: Where can i find draw js file - beginner I am going through the following example. The code is found here.
I need to know where i could find draw.js?
<script src='draw.js'></script>

A: That was a head-scratcher for me too, until I realized that it refers to the JS window on the upper right. That script is draw.js :D


text:
Q: Magento Setting Configurable super attribute I have made all the scripts to add one configurable product, and multiple simple products, and managed to associate them all with color and size. My scripts works fine and does the job but, I always have to go to backend and select the configurable product attribute settings color and size and save the product to be able to view it on main page.
Here is what my script does with configurable product:
PS I am saving the sku's of both simple and configurable product in csv $file. before associate them with configurable product.
code:
<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$confProduct = Mage::getModel('catalog/product')-     >loadByAttribute('sku',$asian);
$colorAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');
    $confProduct->getTypeInstance()->setUsedProductAttributeIds(array($colorAttributeId));
 $sizeAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'size');
    $confProduct->getTypeInstance()->setUsedProductAttributeIds(array($sizeAttributeId));

$file_handle = fopen($file, "r");
while (!feof($file_handle) ) {

$line_of_text = fgetcsv($file_handle, 1024);
$simpleSku = $line_of_text[0];
$configurableSku = $line_of_text[1];
    if($simpleSku){

$simpleProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$simpleSku);
$configurableProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$configurableSku);
$simpleId = $simpleProduct->getId();
$ids = $configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
    $newids[$id] = 1;
}
$newids[$simpleId] = 1;
//echo "Updating configurable product " . $configurableSku;
//echo "<br>";
        $confProduct->setCanSaveConfigurableAttributes(true);

Mage::getResourceModel('catalog/product_type_configurable')->saveProducts($configurableProduct, array_keys($newids));

    }
}
fclose($file_handle);

 return ($idconfig);
}

A: Try this,
$configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray();
$confProduct->setCanSaveConfigurableAttributes(true);
$confProduct->setConfigurableAttributesData($configurableAttributesData);

Before saving your product.


text:
Q: How to prove Chinese Remainder Theorem by Coq? I have already have the following definition and notation:

Definition modulo (a b n : Z) : Prop := (n | (a - b)) .
Notation "( a == b [ n ])" := (modulo a b n) .

And following lemmas(all of them are already proved, ends up with Qed .):

Lemma modulo_refl : forall a n : Z, (a == a [ n ]) .
Lemma modulo_symm : forall a b n : Z, (a == b [ n ]) -> (b == a [ n ]) .
Lemma modulo_tran : forall a b c n : Z,
    (a == b [ n ]) -> (b == c [ n ]) -> (a == c [ n ]) .
Lemma modulo_plus_comm : forall a b n : Z, (a + b == b + a [ n ]) .
Lemma modulo_plus_assoc : forall a b c n : Z, (a + b + c == a + (b + c) [ n ]) .
Lemma modulo_plus_subst : forall a b c n : Z,
    (a == b [ n ]) -> (a + c == b + c [ n ]) .

Now I want to prove the ChineseRemainderTheorem:

Hypothesis m n : Z .
Hypothesis co_prime : rel_prime m n .
Theorem modulo_inv : forall m n : Z, rel_prime m n ->
    exists x : Z, (m * x == 1 [ n ]) .
Theorem ChineseRemainderTheorem : forall a b : Z,
    exists x : Z, (x == a [ m ]) /\ (x == b [ n ]) .

How can I do this?

A: You already have those definitions in the standard library, file Require Import ZArith.Znumtheory.. Then we could prove the Chinese remainder theorem like this
Lemma ChineseRemainder : forall n p a b : Z,
    n <> 0 ->
    p <> 0 ->
    rel_prime n p ->
    exists x:Z, (x mod n = a mod n) /\ (x mod p = b mod p).
Proof.
  intros n p a b npos ppos coprime.
  destruct (rel_prime_bezout _ _ coprime) as [u v H0].
  exists (a*v*p+b*u*n). split.
  - rewrite Z.mod_add. 2: exact npos.
    rewrite <- Z.mul_assoc, <- Zdiv.Zmult_mod_idemp_r.
    assert ((u * n + v * p) mod n = 1 mod n) as H.
    rewrite H0. reflexivity.
    rewrite Z.add_comm, Z.mod_add in H. rewrite H.
    rewrite Zdiv.Zmult_mod_idemp_r, Z.mul_1_r.
    reflexivity. exact npos.
  - rewrite Z.add_comm, Z.mod_add. 2: exact ppos.
    rewrite <- Z.mul_assoc, <- Zdiv.Zmult_mod_idemp_r.
    assert ((u * n + v * p) mod p = 1 mod p) as H.
    rewrite H0. reflexivity.
    rewrite Z.mod_add in H. rewrite H.
    rewrite Zdiv.Zmult_mod_idemp_r, Z.mul_1_r.
    reflexivity. exact ppos.
Qed.


text:
Q: How would one rewrite a program to eliminate side effects? I'm trying to research this problem in a java textbook.
The problem is to rewrite this program to eliminate the side effects,
where a change to the state of an object or program variable is produced by a call on a function (or a method, which is kinda the same thing).
package sideeffect;
public class SideEffect {

    **public static int x;**

    public static int f(int n){
        x = x * 2;
        return x + n;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        x = 5;

        //int result = f(x) + f(x);
        int result = 2 * f(x);
        //System.out.println(result);
    }

}

The commented out lines are what happens when I implement the integer variable and it's printout.
If I implement those lines and comment out the other lines,
the result is 45.
If implement the other one,
the result is 30.
Is there a way to straighten out the program so there are no side effects?
I was thinking I remove the global variable line since it says in the book that it can lead to this bad,
confusing code.
But what else can I try?

A: I know this is an assignment but stuff like this is always somewhat maddening.  The "problem" is that they are using a global variable in a way it should NEVER be used.  "Doctor it hurts when I do this. Don't do that".
In general static (class level) variables are seldom what you really want.  Also main() is for instantiating your objects and turning them lose on the world, not doing the heavy lifting like this was a C program.
Create classes and pass by value.  Don't use global variables unless you REALLY mean to have one and only one instance.
That's really about the best I can offer because it isn't clear from your question what "the correct" outcome is.

A: Okay, much more better:
package sideeffect;
public class SideEffect {

      public static int f(int x, int n){
        x = x * 2;
        return x + n;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       int x = 5;
       int result = f(x , 5) + f(x, 5);
        System.out.println(result);

    }
}

I've brung in x as a int in the public static int so I won't have to initialize the variable.

A: This might work, but I'm not sure. I've commented the global variable, then declared int x in both the f method and main methods. The result is that it doesn't matter whether I use either "int result" calls, it's still going to be 10 as the output. But I could be wrong through:
public class SideEffect {

    **//public static int x;**

    public static int f(int n){
        int x = 0;
        x = x * 2;
        return x + n;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int x = 5;

        //int result = f(x) + f(x);
        int result = 2 * f(x);
        System.out.println(result);
        //System.out.println(result2);
    }

}


text:
Q: Java - byte buffer Out Of Memory Sort of new to Java but I've been able to learn quite a bit quite quickly. There are still many methods that elude me though. I'm writing a Java program that is to run through a bunch of files and test them thoroughly to see if they are a valid level pack file. Thanks to Matt Olenik and his GobFile class (which was only meant to extract files) I was able to figure out a good strategy to get to the important parts of the level pack and their individual map files to determine various details quickly.
However, testing it on 37 files (5 of which aren't level packs), it crashes after testing 35 files. The 35th file is a valid level pack. The error it gives is:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     Iterator iter = itemList.keySet().iterator();
     numJKLs = 0;
     while (iter.hasNext()) {
        String nextFile = (String) iter.next();
        if (nextFile.startsWith("jkl\\")) {
           System.out.println(((ItemInfo) itemList.get(nextFile)).length);
-->        byte[] buffer = new byte[((ItemInfo) itemList.get(nextFile)).length];
           gobRaf.seek(((ItemInfo) itemList.get(nextFile)).offset);
           gobRaf.read(buffer, 0,
                 ((ItemInfo) itemList.get(nextFile)).length);
           String[] content = new String(buffer).toLowerCase().split(
                 "\n");
           levels.add(numJKLs, new JKLFile(theFile, nextFile, content));
           gametype = levels.get(numJKLs).getFileType();
           progress.setProgText(nextFile);
           buffer = null;
           content = null;
           numJKLs++;
        }
     }

Arrow shows where the error is marked. The ´JKLFile´ class reads the content array for these important parts, but should (in theory) dispose of it when done. Like here, I set content = null; in JKLFile just to make sure it is gone. If you are wondering how big the map file it stopped on is, well, it managed to pass a 17 Mb map file, but this one was only 5 Mb.
As you can see these JKLFile objects are kept in this object (GobFile.java) for easy access later on, and the GobFile objects are kept in another class for later access, until I change directory (not implemented yet). But these objects shouldn't be too packed with stuff. Just a list of file names and various details.
Any suggestions on how I can find out where the memory is going or what objects are using the most resources? It would be nice to keep the details in memory rather than having to load the file again (up to 2 seconds) when I click on them from a list.
/Edward

A: Right now you are creating a new buffer for every loop. Depending on your garbage collection some of these may not get recycled/freed from memory and you are then running out. You can call the garbage collector using System.gc() but there is no guarantee that it actually runs at any given time.
You could increase the memory allocated to the JVM on the command line when calling your program with the -Xmx and -Xms arguments. Also if you are not on 32bit windows ensure you are using a 64bit JVM as the 32bit has memory limitations that the former does not. Run java -version from the command line to see the current system JVM.
You can move the declaration for your byte[] buffer outside your loop (above your while) so that it gets cleared and reused on each iteration.
Iterator iter = itemList.keySet().iterator();
numJKLs = 0;
byte[] buffer;
while (iter.hasNext()) {
    ...
    buffer = new byte[] ...
    ...
}

How big are the files you are handling? Do you really need to add every one of them to your levels variable? Could you make do with some file info or stats instead? How much RAM has your JVM currently got allocated?
To look at the current memory usage at any given time you will need to debug your program as it runs. Look up how to do that for your IDE of choice and you will be able to follow any Object's current state through the program's lifespan.


text:
Q: bad use of pthread, for waiting response of sockets my main function is like this :
void create_serv_and_init_client(client_t *cl)
{
    static int i = 0;
    pthread_t thread_serv;
    serv_t serv;

    if (i == 0) {
        //cl[0].content = retrieve_info();
        cl[0].connected = 1;
        //PORT = cl[0].content.port;
        serv = create_serv_socket();
        if (pthread_create(&thread_serv, NULL, waiting_connection, \
        (void *)&serv) < 0) {
            perror("could not create thread");
            exit(1);
        }
        cl[0] = create_client(0);
        printf("OK\n");
        i++;

    }
}

and the waiting function of the pthread :
void *waiting_connection(void *server)
{
    serv_t *serv = (serv_t *)server;

    serv->newSocket = accept(serv->sockfd, (struct sockaddr*)&serv->newAddr, \
    &serv->addr_size);
    if (serv->newSocket < 0) {
        exit(1);
    }
    if ((serv->childpid = fork()) == 0) {
        close(serv->sockfd);
        while (recv(serv->newSocket, serv->buffer, 1024, 0) != 0) {
            printf("Client: %s\n", serv->buffer);
            send(serv->newSocket, serv->buffer, strlen(serv->buffer), 0);
            bzero(serv->buffer, sizeof(serv->buffer));
        }
    }

if i comment the pthread_create call and call after the if the waiting_connection function, it will work, so i have a problem with my pthread, but why he doesnt work ? thanks again !

A: You may have a race condition which may cause undefined behavior.  In create_serv_and_init_client() you define a local variable serv.  The address of this variable is passed to the thread.  When create_serv_and_init_client completes serv will go out of scope, even if the thread is still using it.  As a result the value of serv may no longer be correct.

A: Note a multi-threaded program can really only fork to execute a new program using execve. For example from Linux manuals:

*

*After a fork() in a multithreaded program, the child can safely call only async-signal-safe functions (see signal-safety(7)) until such time as it calls execve(2).

printf for example can lock the stdout. If you happen to fork in while the printf lock is held by another thread then crazy things might or might not happen.


text:
Q: Bitmap.Save "Generic Error" When I run my application the following error get's thrown in my face "A generic error occurred in GDI+."
I've looked around and seen people have similar errors, but have found no real solution, or it is a real pain in the butt to implement. And those that have not gotten a solution have not posted their code.
So I thought I might as well give it a shot and throw another thread up about how to fix this error. This is my Code & Error
            Random r = new Random();
            DirectoryInfo di = new DirectoryInfo(folderbrowser.SelectedPath);
            FileInfo[] fi = di.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();
            for (int i = 0; i < imageCount; i++)
            {
                int img1 = r.Next(imageCount);
                int img2 = r.Next(imageCount);
                while (img2 == img1)
                    img2 = r.Next(imageCount);
                pic1.Image = Image.FromFile(fi[img1].FullName);
                pic2.Image = Image.FromFile(fi[img2].FullName);
                Image i1 = pic1.Image;
                Image i2 = pic2.Image;
                Bitmap bitmap = new Bitmap(i1.Width + i2.Width, 1080);
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.DrawImage(i1, 0, 0);
                    g.DrawImage(i2, i2.Width, 0);
                }
                bitmap.Save(@"C:\TEST\Image_"+i.ToString());
            }

And here's the Error code
System.Runtime.InteropServices.ExternalException was unhandled
  Message=A generic error occurred in GDI+.
  Source=System.Drawing
  ErrorCode=-2147467259
  StackTrace:
       at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
       at System.Drawing.Image.Save(String filename, ImageFormat format)
       at System.Drawing.Image.Save(String filename)
       at WallpaperMerger.Form1.btn_merge_Click(Object sender, EventArgs e) in C:\Users\PeppeJ\documents\visual studio 2010\Projects\WallpaperMerger\WallpaperMerger\Form1.cs:line 113
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WallpaperMerger.Program.Main() in C:\Users\PeppeJ\documents\visual studio 2010\Projects\WallpaperMerger\WallpaperMerger\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

So what do you guys here at StackOverflow think. Am I the same boat as the others and have to type a ridiculously complex code to solve this problem, or have I made a simple mistake and it's easy to correct?
If you want to test it yourself if that might somehow help, here's a link to the Debug Build
Simply tick "Use Multiple Files", select a folder containing image files (C:\Users\Public\Pictures\Sample Pictures) for instance. Hit Merge.
I'd like to add that I use Bitmap.Save in this function, and it works flawlessly.
        Bitmap bitmap = new Bitmap(pic1.Image.Width + pic2.Image.Width, 1080);
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.DrawImage(pic1.Image, 0, 0);
            g.DrawImage(pic2.Image, pic1.Image.Width, 0);
        }
        if (savepicfile.ShowDialog() == DialogResult.OK)
            bitmap.Save(savepicfile.FileName);

In the above function files are loaded like this:
    DialogResult result = pic1file.ShowDialog();
    if (result == DialogResult.OK)
        pic1.Image = Image.FromFile(pic1file.FileName);

Something else worth mentioning is that "picX" is a "System.Windows.Forms.PictureBox" object.

A: In my experience, 99% of the time this error is caused by an issue where either:

*

*You don't have permission to write the file.

*The file you're trying to write to is locked by another process.

Occasionally I've run into it when:

*

*I'm drawing GraphicPaths with zero points in them.

*I'm not property disposing of my GDI+ objects. (possibly related to option 2 above)

I'd check the first two things first. If that can be ruled out I can see where you're not properly disposing of a few objects in the code you provided. I'd clean that up. GDI+ isn't particularly cooperative with .NET's GC if you aren't calling Dispose() when you're supposed to.
        var r = new Random();
        var di = new DirectoryInfo(folderbrowser.SelectedPath);
        var fi = di.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();
        for (var i = 0; i < imageCount; i++)
        {
            var img1 = r.Next(imageCount);
            var img2 = r.Next(imageCount);
            while (img2 == img1)
            {
                img2 = r.Next(imageCount);
            }
            pic1.Image = Image.FromFile(fi[img1].FullName);
            pic2.Image = Image.FromFile(fi[img2].FullName);
            var i1 = pic1.Image;
            var i2 = pic2.Image;
            using (var bitmap = new Bitmap(i1.Width + i2.Width, 1080))
            using (var g = Graphics.FromImage(bitmap))
            {
                g.DrawImage(i1, 0, 0);
                g.DrawImage(i2, i2.Width, 0);
                bitmap.Save(@"C:\TEST\Image_"+i.ToString());
            }
        }

EDIT: More ideas (Well, really clarification of number 2 above)...

*

*If you have a PictureBox or other control in your app referencing the images in your C:\TEST directory that you're trying to write, you can see this error.

*If you have other code reading the image you're trying to write to you can see this error.

*If an external process, such as your IDE, an image viewer/editor, etc. has the file open you can see this error.

Debugging ideas:

*

*Try setting a break point on the Save call. When you get to it, use the tips found here to figure out what process might be accessing the file: How do I find out which process is locking a file using .NET?

*Try just deleting the files first to see if it allows you to save if they're not their.

*Try setting full permissions for "Everyone" on the directory you're writing to (Don't leave it like this, though)

*Make sure the width of the image you're trying to save is a number greater than zero. I noticed you're setting that programatically.

*Make sure the width of the image you're trying to save isn't ridiculously huge (an maybe you're running into a memory issue?)

A: I found the answer, the directory "\TEST\" didn't exist. When I created it , it worked flawlessly.

A: I had this exact problem, and what fixed it was to wrap the Bitmap in the using clause; Bitmap needs to be disposed as well
using (Bitmap bmp = new Bitmap())
{
    // Bitmap operation
}

A: Try doing the bitmap.Save before you dispose of the Graphics object:
Bitmap bitmap = new Bitmap(i1.Width + i2.Width, 1080);
using (Graphics g = Graphics.FromImage(bitmap))
{
    g.DrawImage(i1, 0, 0);
    g.DrawImage(i2, i2.Width, 0);
    bitmap.Save(@"C:\TEST\Image_"+i.ToString());
}


text:
Q: I am getting this error when I am trying to add files from the local drive to the Repository in the local drive I am getting this error when I am trying to add files from the local drive to the Repository in the local drive that is a clone of Git repository of same name:-

run_git-add:
[exec] fatal: not a git repository (or any of the parent directories):
  .git       [exec] Result: 128      [echo] add done

Please guide me
This is my whole command in ANT:
<?xml version="1.0"?>
<!--New Build File-->

<project default="run_git-add">

<!--GIT COMMAND LOG-->
<macrodef name="git">
        <attribute name = "command" />
        <attribute name = "dir" default = "" />
        <element name = "args" optional = "true" />
        <sequential>
                <echo file="GIT_COMMAND_LOG" message="git @{command}
"
                    append="yes" />
                <exec executable = "git" dir = "@{dir}">
                    <arg value = "@{command}" />
                    <args/>
                </exec>
        </sequential>
    </macrodef>

<!--GIT INIT-->
    <macrodef name = "git-init">
        <attribute name = "repository" />
        <sequential>
            <git command = "init">
                <args>
                    <arg value = "@{repository}" />
                </args>
            </git>
        </sequential>
    </macrodef>

<!--GIT ADD-->
    <macrodef name = "git-add">
        <attribute name = "path" />
        <attribute name = "target1" />
        <sequential>
            <git command = "add" dir="@{path}">
                <args>
                    <arg value = "@{target1}" />
                </args>
            </git>
        </sequential>
    </macrodef>

<!--GIT COMMIT-->
    <macrodef name = "git-commit">
        <attribute name = "path" />
        <attribute name = "message" />
        <sequential>
            <git command="commit" dir="@{path}">
                <args>
                    <arg value= "@{message}" />
                </args>
            </git>
        </sequential>
    </macrodef>

<!--GIT PUSH-->
    <macrodef name = "git-push">
        <attribute name = "path" />
        <attribute name = "branch" />
        <attribute name = "head" />
        <sequential>
            <git command = "push" dir="@{path}">
                <args>
                    <arg value = "@{branch}" />
                    <arg value = "@{head}" />
                </args>
            </git>
        </sequential>
    </macrodef>
<!--test fail-->
    <macrodef name="test">
        <attribute name = "path" default="hello" />
        <sequential>
            <fail message="fail">
                <condition>
                    <not>
                        <contains string="@{path}" substring="hello" />
                    </not>
                </condition>
            </fail>
        </sequential>
    </macrodef>

<target name="run_git-init">
<git-init repository="Hello-world"/>
<echo message="init done" />
</target>

<target name="run_git-add">
<git-add path="C:\ANT MIGRATION\mig tool full\salesforce_ant_41.0\sample\retrieveUnpackaged1\classes" target1="C:\ANT MIGRATION\mig tool full\salesforce_ant_41.0\Hello-world"/>
<echo message="add done" />
</target>
    </project>

A: As per the message, it seems like you are not inside a git repository.
Try git status to verify that.
Or check for a hidden .git directory inside your projects's root directory.
If you get the same error, it means that the directory is not git repository.
You should start by initializing the git repository to start using it as local git repo.
git init

And need to add the remote urls
git remote add origin https://github.com/github_repo_name/project_name.git

A: That directory is not a git working tree.
To be able to use git you need to initialize a repository.
Assuming you started from scratch, you should run
git init

to create the repository and make that directory a git working tree.
Once initialized the repository you'll be able to add your files as you correctly did. You just missed the first step.
If you're supposed to collaborate with others it might be worth (or necessary) to setup a remote repository.
Assuming that you started from scratch you can do that with
git remote add origin URI

where URI can be either an HTTP address or an SSH resource.
I assumed that you started from scratch because cloning an existing repository doesn't require to run the git init command. Unless you unintentionally deleted the .git directory.
From your build it seems that you're trying to add a file that's outside the current directory. With git add you can only run files in the local tree.


text:
Q: Stored Procedure to populate Materialized View How to create a stored procedure.
We have a parent view with the data in the one of the columns as below,

*

*Link-ABCD*Link-Child01*Link-Child02

*Link-DEFG*Link-Child03*Link-Child04

*Link-XYZ*Link-Child05*Link-Child04

We want to create a Materialized View on top of this Parent View having the following structure,
ID_COLUMN | ELEMENT_COLUMN        | PARENT_ID_COLUMN
  1       |        Link-ABCD      |     0
  2       |        Link-Child01   |     1
  3       |        Link-Child02   |     2
  4       |        Link-DEFG      |     0
  5       |        Link-Child03   |     4
  6       |        Link-Child04   |     5
  7       |        Link-XYZ       |     0
  8       |        Link-Child05   |     7
  9       |        Link-Child04   |     8
   -

*

*ID_Column = Auto Generated

*ELEMENT_COLUMN = Need to split the data present in the parent view with the delimiter "*", and insert each element only if it does not exist before or if element is already exists, then we need to check parent id of the existing element and if the parent id is not the same as the ID_COLUMN of the current parent. For example we had to insert  Link-Child04 again because the parent is different for last case.

*PARENT_ID_COLUMN = value will be the same as the ID_COLUMN of the parent element. FOR eg Link-Child01 is a child of Link-ABCD whose id was 1, so the parent_id for Link-Child01 has to be 1. and so on.
The parent_id for the elements who don't have any parents will be 0. For example parent id for Link-ABCD, Link-DEFG and Link-XYZ is 0.

A: You can generate the result you want using a recursive CTE (as long as you're on Oracle 11gR2 or higher), and a ranking function. If the column in your parent_view is called, for example, str then you can do:
with rcte (str, root_rn, child_level, element) as (
  select str,
    row_number() over (order by str),
    1,
    regexp_substr(str, '(.*?)(\*|$)', 1, 1, NULL, 1)
  from parent_view
  union all
  select str,
    root_rn,
    child_level + 1,
    regexp_substr(str, '(.*?)(\*|$)', 1, child_level + 1, NULL, 1)
  from rcte
  where child_level <= regexp_count(str, '\*')
)
select rank() over (order by root_rn, child_level) as id,
  element,
  case when child_level = 1 then 0
       else rank() over (order by root_rn, child_level) - 1 end as parent_id
from rcte
order by root_rn, child_level;

which with your sample strings gets:
        ID ELEMENT               PARENT_ID
---------- -------------------- ----------
         1 Link-ABCD                     0
         2 Link-Child01                  1
         3 Link-Child02                  2
         4 Link-DEFG                     0
         5 Link-Child03                  4
         6 Link-Child04                  5
         7 Link-XYZ                      0
         8 Link-Child05                  7
         9 Link-Child04                  8

But it's unclear what you really want to do with those. You could create a normal view or a materialized view from that query, but the IDs will change as rows are added, removed modified in the parent view - or rather, in its base tables. (And views built on top of views can introduce performance issues).
You could also maintain a normal table from a procedure, using the same query; but that would seem to be duplicating the functionality that a materialized view gives you.

You might also want to look at the parent view's query to see where those strings are coming from - it's just a guess, but it might be generating them by aggregating values from base tables which you could just look at directly.

A: Example of how to extract the 3 fields:
select a.link_info,
       substr(a.link_info,
              1,
              instr(a.link_info,'*',1,1)-1       /* Until 1st asterisk*/
              )                      as element1,
       substr(a.link_info,
              instr(a.link_info,'*',1,1)+1,     /* between 1st and 2nd asterisk*/
              instr(a.link_info,'*',1,2)-instr(a.link_info,'*',1,1)-1
              )                      as element2,
       substr(a.link_info,
              instr(a.link_info,'*',1,2)+1     /* after the 2nd asterisk */
              )                      as element3
from (select 'Link-ABCD*Link-Child01*Link-Child02' as link_info
      from dual
      union all
      select 'Link-DEFG*Link-Child03*Link-Child04' as link_info
      from dual
      union all
      select 'Link-XYZ*Link-Child05*Link-Child04' as link_info
      from dual
      ) a;


text:
Q: Encoding in networkx I can't draw a graph with networkx because of Cyrillic characters.
import networkx as nx

G = nx.Graph()
s = "СукупністьЇЄ"
G.add_node(s.decode('utf-8'))

nx.draw_graphviz(G)

And I'm getting
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Library/Python/2.7/site-packages/networkx-1.10-py2.7.egg/networkx/drawing/nx_pylab.py", line 982, in draw_graphviz
pos = nx.drawing.graphviz_layout(G, prog)
File "/Library/Python/2.7/site-packages/networkx-1.10-py2.7.egg/networkx/drawing/nx_pydot.py", line 257, in graphviz_layout
return pydot_layout(G=G,prog=prog,root=root,**kwds)
File "/Library/Python/2.7/site-packages/networkx-1.10-py2.7.egg/networkx/drawing/nx_pydot.py", line 296, in pydot_layout
node = node[0]
IndexError: list index out of range

I tried changing the line #296 in nx_pydot file to
node = node[:2]

and the line after that (#297) to
pos=node.get_pos()[2:-2]

given that a Cyrillic symbol takes two bytes, but nothing changed.
I'm using Python 2.7.5 on Mac and networkx 1.10.

A: I received help from a networkx developer, Aric.
According to him, the problem was that I was using the pydot interface to graphviz which doesn't seem to work with unicode
# -*- coding: utf-8 -*-

import networkx as nx
import matplotlib.pyplot as pl

labels={}
graph = nx.Graph()

words= ["сукупність","вдача","волосся","колектив"]

for word in words:
    w = word.decode('utf-8')
    graph.add_node(w)
    labels[w]=w
graph.add_edge("сукупність".decode('utf-8'),"вдача".decode('utf-8'))
graph.add_edge("сукупність".decode('utf-8'),"волосся".decode('utf-8'))
graph.add_edge("сукупність".decode('utf-8'),"колектив".decode('utf-8'))
pos=nx.spring_layout(graph)
# pos=nx.drawing.pydot_layout(graph) # doesn't work with unicode
# pos=nx.drawing.pygraphviz_layout(graph) # this also works, pygraphviz
nx.draw_networkx(graph, pos=pos, labels=labels)
pl.show()

A: I do not know what is the problem but when I tried nx.draw(G) No error occured. So if you do not care about the graphviz layout, you can use it.


text:
Q: sugarCRM: How to redirect to external page after logout? I am trying to redirect to a page on my external page, what I have tried till now is. Manually I added some files.
In /custom/modules/Users/logic_hooks.php
<?php

    $hook_version = 1;
    $hook_array = Array();

    $hook_array['after_logout'] = Array();
    $hook_array['after_logout'][] = Array(
        //Processing index. For sorting the array.
        1,

        //Label. A string value to identify the hook.
        'after_logout example',

        //The PHP file where your class is located.
        'custom/modules/Users/logic_hooks_class.php',

        //The class the method is in.
        'logic_hooks_class',

        //The method to call.
        'after_logout_method'
    );

?>

And another file in In /custom/modules/Users/logic_hooks_class.php
<?php

    if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

    class logic_hooks_class
    {
        function after_logout_method($bean, $event, $arguments)
        {

        header('Location: http://raviranjan.info/');
        }

         function AfterLogout(&$bean, $event, $arguments)
    {
        SugarApplication::redirect('http://raviranjan.info/');
    }
    }

?>

So is there any other way to redirecting or just show something on screen before or after logging out from SugarCRM application.
Advance Thanks for any help.

A: There are multiple ways of doing this. Read following details:

*

*show alert of any other type of message by handling click event of logout link. e.g. when user click that link then show alert of any other type of message.

*after logout redirect user to your custom page( you can build custom entry point which will be accessible with auth=>false).

*you can add any button or java-script to show message then redirect it to your target page.

Simple jquery selector, see following:
$("a.utilsLink").click(function(){

var r = confirm("Are you sure to logout?");
if (r == true) {
    console.log("yes is clicked");
} else {
     console.log("cancel is clicked...");
return false;
}

});


text:
Q: Replace attribute values in custom sections in same web.config file In same web.config file i got two custom sections like
<SectionOne>
    <Element1 value="value1" />
    <Element2 value="value2" />
</SectionOne>

<SectionTwo>
    <items>
        <item key="value1" ... />
        <item key="value2" ... />
    </items>
</SectionTwo>

and i would like to use once defined values in SectionOne, and put them in SectionTwo, each one in its place... and other places in web.config file.
"value1" from SectionOne goes to "value1" in SectionTwo and so on...
Is it possible to do?


text:
Q: Use [Authorize] with Blazor server I've looked just about everywhere and tried everything I can find but cannot for the life of me figure this out.
I'm using the default Visual Studio Blazor Server template and using Facebook Authentication.
I need to filter out my controller using the [Authorize] tag and use the UserId for filtering of Data.
Using a normal Blazor Control a call to the Controller returns HTML telling me to log in, although the user is already logged in. Removing the [Authorize] tag allows the application to run as expected.
Calls directly to the Controller through the URI after logged in work as well.
I can see the Authorization Request header is not sent from the Client.
I tried to set the Tokens in the _Host.cshtml but  await HttpContext.GetTokenAsync("access_token"), returns null


text:
Q: Circuit drawing more current on PCB I have a circuit that I developed on breadboard. I have then soldered it on a PCB and it is now drawing more current on PCB compared to when it was on breadboard. I only want to discuss possible reasons for this without going into much detail about the circuit as I haven't changed it before or after soldering on PCB unless someone really wants me to.
Details about the circuit:

*

*Micro-controller based circuit.

*A couple sensors and a single radio.

*Step-up regulator for powering everything (Pololu 5V).

This is what comes to my mind:

*

*Flux conducting some current?

*Possible tiny short-circuit somewhere?

*Possible faulty chip after soldering?

*Possible different current consumption with different power supplier?
(3.6V lipo battery over a cheap AC 1A 5V adapter)

*Possible larger resistance on breadboard circuit.

The circuit works fine so I assume there is no problem with PCB.
On breadboard it was drawing about 28.5mA. Now on PCB it's drawing about 40mA.
Thanks everyone.

A: If you supplied 5V while the circuit was on a breadboard, and 3.6V while it is on a PCB, that seems to me the biggest explanation of different currents. Having no idea what your circuit is, I'll just calculate if it has the same power in both configurations:
Breadboard: \$P = 5 \times 0.0285 = 142.5\mathrm{mW}\$
PCB: \$P = 3.6 \times 0.04 = 144\mathrm{mW}\$
It looks like the device draws the same power so I think you may be seeing a problem that isn't there.


text:
Q: Using AppleScript with administrator privileges, "not ask for authentication again for five minutes." doesn't work? in Apple Document Technical Note 2065, it mention "do shell script command with administrator privileges",when using this way,"Once a script is correctly authenticated, it will not ask for authentication again for five minutes."
but, it still need ask for authentication again and again.
I find,when use ScriptEditor.app, the Apple Document is right.
eg:
do shell script "/bin/cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop/ " with administrator privileges
but, when use NSAppleScript running shell script, the Apple Document is wrong.
eg:
    NSDictionary *error = nil;
NSString *copyScript = @"do shell script \"/bin/cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop \" with administrator privileges";
NSAppleScript *copyAppleScript = [[NSAppleScript alloc] initWithSource:copyScript];
if ([copyAppleScript executeAndReturnError:&error])
{
    NSLog(@"copyAppleScript Success!");
}
else
{
    NSLog(@"copyAppleScript Failuer!");
}

I hope, when do shell script with NSAppleScript, it will not ask for authentication again for five minutes also.

A: First, I don't think this is the best way to approach this problem. But let me answer the question first, and then suggest another avenue.
Note that tech note 2065 says this:

The authentication only applies to that specific script: a different
  script, or a modified version of the same one, will ask for its own
  authentication.

Every time you run this line:
NSAppleScript *copyAppleScript = [[NSAppleScript alloc] initWithSource:copyScript];

...you create a new script, and that new script will need authorization of its own. If you want to reuse a given script without constantly reauthorizing, you'll need to create an NSAppleScript property, store your script there once, and then call it repeatedly.  In other words:
@interface MyObject ()

@property (strong) NSAppleScript *myAppleScript;

@end

@implementation MyObject

- (void)setUpScript {
    // call this once
    NSDictionary *error = nil;
    NSString *copyScript = @"do shell script \"/bin/cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop \" with administrator privileges";
    self.myAppleScript = [[NSAppleScript alloc] initWithSource:copyScript];
}

- (void)runScript {
    // call this as needed; shouldn't need reauthorization
    if ([self.myAppleScript executeAndReturnError:&error]) {
        NSLog(@"myAppleScript Success!");
    } else {
        NSLog(@"myAppleScript Failure!");
    }
}

@end

However, since your goal here is to run a shell script, I'd suggest you forget about NSAppleScript entirely, and use NSTask instead. NSTask is how shell scripts are meant to be run from objC, and should avoid authorization problems entirely. The easiest way to do this is to write an explicit shell script and store it in the bundle:
#!/bin/bash
cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop

Then call and run that shell script:
NSError *err;
NSTask *task = [NSTask launchedTaskWithExecutableURL:[[NSBundle mainBundle] URLForResource:@"ShellScript"
                                                                             withExtension:@"sh"]
                                           arguments:[NSArray array]
                                               error:&err
                                  terminationHandler:nil];

...or maybe this, if you don't want to bundle a script...
NSError *err;
NSTask *task = [[NSTask alloc] init]
task.arguments = [NSArray arrayWithObjects:@"#!/bin/bash",
                  @"-c",
                  @"cp -r /Users/Simon/Desktop/Test/test.zip /Users/Simon/Desktop",
                  nil];
[task launchAndReturnError:&err];

P.S.
I've been assuming that this cp command is just proof-of-concept, but if your actual goal is to copy a file, forget about NSAppleScript and NSTask. Use NSFileManager's copyItemAtURL:toURL:error: instead.


text:
Q: take data from one table and put it into another along with new information I have 2 tables. the first is customers the second is invoice, both have a row for "customer ID". When adding a new invoice through a web form how do I make it so it will take the "customer ID" from customers and put it into the "customer ID" in invoice along with the new information upon submission of the form?
This is the code from my index.php
?php
include 'DBConfig.php';
//Insert or Update contact information
if(isset($_POST['action_type']))
{
if ($_POST['action_type'] == 'add' or $_POST['action_type'] == 'edit')
{
    //Sanitize the data and assign to variables
    $invum = mysqli_real_escape_string($link, strip_tags($_POST['invnum']));
    $cost = mysqli_real_escape_string($link, strip_tags($_POST['cost']));

    if ($_POST['action_type'] == 'add')
    {
        $sql = "insert into invoice set
                cost = '$cost'";
    }else{
        $sql = "update invoice set
                cost = '$cost',
                where invnum = $invnum";
    }

    if (!mysqli_query($link, $sql))
    {
        echo 'Error Saving Data. ' . mysqli_error($link);
        exit();
    }
}
header('Location: invoicelist.php');
exit();
}
//End Insert or Update contact information

//Start of edit contact read
$gresult = ''; //declare global variable
if(isset($_POST["action"]) and $_POST["action"]=="edit"){
$id = (isset($_POST["ci"])? $_POST["ci"] : '');
$sql = "select invnum, cost from invoice
        where invnum = $id";

$result = mysqli_query($link, $sql);

if(!$result)
{
    echo mysqli_error($link);
    exit();
}

$gresult = mysqli_fetch_array($result);

include 'invoiceupdate.php';
exit();
}
//end of edit contact read


text:
Q: Jenkins Multibranch Pipeline Project vs Pipeline Project It might be a simple question but what is the main differences between managing multi-branches (dev-test-master) using declarative pipeline in Pipeline project and select Multibranch pipeline project?
I would like to deploy my application to the Kubernetes environment according to the branch variable. Which project type should I use to follow best practices or which one is easy to manage? I guess I can do the same thing and manage my branches and deployment environment only one Jenkinsfile in Pipeline project.

A: With Multibranch, you get one Jenkinsfile per branch. Without it, you don't. That's the main difference.
With file per branch, you can have separate instructions on how exactly to build this branch (the "configuration as a code" notion). E.g. if you have 5 containers, you may have five "Build Container X" stages (maybe run in parallel) and five "Test Container X" stages (ditto). In your new branch you develop a new container, so in that branch's Jenkinsfile you may now have six build and six test stages instead of five. Now, under source control, any branch that descends from the regular branch(es) will inherit its Jenkinsfile (and build/test 5 containers) while any branch over this new branch will inherit that Jenkinsfile (and build/test 6 containers) without any need to change a thing.
With one Jenkinsfile, this may quickly get convoluted.
This is completely orthogonal to the branch variable that you may check and act on it differently. In our environment, we have both: a Jenkinsfile per branch, and checking the branch variable inside all Jenkinsfiles. This minimizes the merge effort.


text:
Q: Clojure "repeatedly" makes "future" run sequentially While this snippet
(dorun
  (map deref
    (map #(future
            (println % (Thread/currentThread)))
         (range 10))))

prints 10 intermixed lines showing different threads:
0 #object[java.lang.Thread 0x5f1b4a83 Thread[clojure-agent-send-off-pool-26,5,main]]
2 #object[java.lang.Thread 1 0x79dfba1f #object[Thread[clojure-agent-send-off-pool-28,5,main]java.lang.Thread]
3 4 #object[java.lang.Thread #object[java.lang.Thread 0x7ef7224f Thread[clojure-agent-send-off-pool-27,5,main]0x5f1b4a83 ]Thread[clojure-agent-send-off-pool-26,5,main]]
5
67  #object[java.lang.Thread #object[0x79dfba1f java.lang.Thread Thread[clojure-agent-send-off-pool-28,5,main]]0x77526645
 8 #object[java.lang.Thread #object[java.lang.ThreadThread[clojure-agent-send-off-pool-29,5,main] ]9 #object[java.lang.Thread 0xc143aa5 0x7ef7224f                                                             Thread[clojure-agent-send-off-pool-31,5,main]]Thread[clojure-agent-send-off-pool-27,5,main]]

0x1ce8675f 0x379ae862 Thread[clojure-agent-send-off-pool-30,5,main]Thread[clojure-agent-send-off-pool-32,5,main]]]

as I would expect, the following snippet:
(dorun
  (map deref
    (map #(future
            (println % (Thread/currentThread)))
         (repeatedly 10 #(identity 42)))))

produces 10 neatly aligned strings with the same thread:
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]
42 #object[java.lang.Thread 0x1e1b7ffb Thread[clojure-agent-send-off-pool-39,5,main]]

which clearly indicates that the futures are not run in parallel, but each in the same thread.
This happens only with repeatedly, even if I realize the sequence with doall first, but vectors, ranges or other sequences all result in parallel execution.
Why is future dispatching to the same thread when repeatedly is used?
Thanks!

A: This works:
(dorun (map deref (doall (map #(future (println % (Thread/currentThread))) (repeatedly 10 #(identity 42))))))

The problem is that range produces a chunked sequence while repeatedly produces an unchunked sequence. Map is lazy, so in the repeatedly case you're creating a future, then derefing it, then creating the next future, then dereffing it. In the range case the sequence is chunked so you're creating all futures and then derefing all of them.
Here's another fun way to observe the difference between the behaviour of chunked and unchunked sequences.
=> (first (map prn (range 10)))
0
1
2
3
4
5
6
7
8
9
nil
=> (first (map prn (repeatedly 10 #(identity 13))))
13
nil

The size of the chunks is usually 32 (but I think that's not guaranteed anywhere), as can be seen if you run (first (map prn (range 1000))).
Chunking is one of those hidden features of Clojure that you usually learn when it first bites you :)


text:
Q: For which natural numbers  ≥ 3 is it possible to cut a regular -gon into smaller pieces with regular polygonal shape? I have been working on this question and I found that any regular polygon with n sides works.My claim is that we can cut any regular polygon of n sides into smaller regular polygons with n sides.And we will have smaller polygons with n sides and rhombuses.But the thing is that I haven't found a way to prove this.Is there anything wrong with my claim or is their a way to prove my claim?
Edit -This is for n=5 (not perfect)


text:
Q: Clears all the fields I have 4 fields and 2 buttons, one of the buttons is reset, I want that when I click on the button it clears all the fields

A: Create an onClickListener to that reset button
Button resetButton = (Button) findViewById(R.id.reset);
resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View arg1) {
                textView1.setText(null);//use editText if fields are EditText
                textView2.setText(null);
                textView3.setText(null);
                textView4.setText(null);
                 }
        });

you can use this way on AutoCompleteTextView, EditText and TextView.

A: A simple example:
public class MyActivity extends AppCompatActivity{
    private EditText editText1, editText2, editText3, editText4;
    private Button btn_reset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        //javaVariable = (Cast type) findViewById(R.id.IdFromXML);
        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);
        editText4 = (EditText) findViewById(R.id.editText4);
        btn_reset = (Button) findViewById(R.id.btn_reset);

        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 //Here's the actions to do when btn_reset is clicked
                 editText1.setText("");
                 editText2.setText("");
                 editText3.setText("");
                 editText4.setText("");
            }
        });
    }
}


text:
Q: Retrieving Customer Id from stripe to store in database I am using Stripe as a payment gateway for a site i designed. I have been able to create and charge customers however, I want to also store the customer ids in my database. How can i retrieve the customer id? here is my code snippet:
....
// Create a Customer
      $customer = \Stripe\Customer::create(array(
          'email' => $email,
          'card'  => $token,
          //'address_line1' =  $addr1 . " ". $addr2 . " ". $city . " " . " " .$country ,
          //'address_zip' = $postcode,
          'description' =>'Partnership' . " " . $fname . " " . $lname
      ));

      // Charge the Customer instead of the card
      $charge = \Stripe\Charge::create(array(
          'customer' => $customer->id,
          'amount'   => $amount,
          'currency' => 'gbp',
           "metadata" => array("order_id" => "6735")
      ));

     //retrieve customer id
     $customerId = \Stripe\Charge::retrieve($charge['customer']);

This is the error message I got:
Notice: Undefined variable: charge

Fatal error: Uncaught exception 'Stripe\Error\InvalidRequest' with message 'Could not determine which URL to request: Stripe\Charge instance has invalid ID: ' in ....
 1. enter code here

A: After assigning the customer object to the $customer variable, you can access its ID via $customer->id. This is what you do already to pass the customer ID in the charge creation request.
You should do the same to save the ID in your database.


text:
Q: Watir not finding all elements with a class name I'm trying to find all span elements which have a class in a "feed" website with Watir.
The site loads more posts as I get to the bottom.
I'm currently using the following code:
# Go to the bottom of the page
browser.driver.execute_script("window.scrollBy(0,document.body.scrollHeight)")
likes = @browser.elements(:xpath, "//*[contains(@class, 'className')]")
# I also tried with the following
likes = @browser.spans(:class => "className")

The element I'm searching follows the following style:
Like

But when I'm doing a likes.length I got fewer elements (3) or none when there are, at least, 25 spans with the class className.
Is there something wrong with my code?

A: likes = @browser.spans(:class => "className")

This one clearly wouldn't work because you are speaking like class name contains "className" so you better write with regular expression
likes = @browser.spans(:class => /className/)

Or go with your other option with a little correction since you only want span, you don't have to use * instead use span
likes = @browser.elements(:xpath, "//span[contains(@class, 'className')]")

Watir usually wait until page loads completely when you are navigating one page to another, we don't have to use any static sleep statement but Since you say page loads more span when get to the bottom your case seems to be little different ,I strongly suspect the above code executes quickly even before page loads completely so put sleep 5 to check whether you get increase in number of spans, so write the following code with  sleep 5
WATIR has the execute_script for you, so you don't have to use selenium execute_script directly
@browser.execute_script("window.scrollBy(0,document.body.scrollHeight)")
sleep 5
likes = @browser.elements(:xpath, "//span[contains(@class, 'className')]")


text:
Q: reducing an Array of Float using scala.math.max I am confused by the following behavior - why does reducing an Array of Int work using math.max, but an Array of Float requires a wrapped function? I have memories that this was not an issue in 2.9, but I'm not completely certain about that.
$ scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL

$ scala

scala> import scala.math._

scala> Array(1, 2, 4).reduce(max)
res47: Int = 4

scala> Array(1f, 3f, 4f).reduce(max)
<console>:12: error: type mismatch;
 found   : (Int, Int) => Int
 required: (AnyVal, AnyVal) => AnyVal
          Array(1f, 3f, 4f).reduce(max)
                                   ^

scala> def fmax(a: Float, b: Float) = max(a, b)
fmax: (a: Float, b: Float)Float

scala> Array(1f, 3f, 4f).reduce(fmax)
res45: Float = 4.0

update : this does work
scala> Array(1f, 2f, 3f).reduce{(x,y) => math.max(x,y)}
res2: Float = 3.0

so then it is just reduce(math.max) which cannot be shorthanded?

A: The first thing to note is that math.max is overloaded, and if the compiler has no hint about the expected argument types, it just picks one of the overloads (I'm not clear yet on what rules govern which overload is picked, but it will become clear before the end of this post).
Apparently it favors the overload that takes Int  parameters over the others.  This can be seen in the repl:
scala> math.max _
res6: (Int, Int) => Int = <function2>

That method is most specific because the first of the following compiles (by virtue of numeric widening conversions) and the second does not:
scala> (math.max: (Float,Float)=>Float)(1,2)
res0: Float = 2.0

scala> (math.max: (Int,Int)=>Int)(1f,2f)
<console>:8: error: type mismatch;
 found   : Float(1.0)
 required: Int
              (math.max: (Int,Int)=>Int)(1f,2f)
                                         ^

The test is whether one function applies to the param types of the other, and that test includes any conversions.
Now, the question is: why can't the compiler infer the correct expected type? It certainly knows that the type of Array(1f, 3f, 4f) is Array[Float]
We can get a clue if we replace reduce with reduceLeft: then it compiles fine.
So surely this has to do with a difference in the signature of reduceLeft and reduce.
We can reproduce the error with the following code snippet:
case class MyCollection[A]() {
  def reduce[B >: A](op: (B, B) => B): B = ???
  def reduceLeft[B >: A](op: (B, A) => B): B = ???
}
MyCollection[Float]().reduce(max) // Fails to compile
MyCollection[Float]().reduceLeft(max) // Compiles fine

The signatures are subtly different.
In reduceLeft the second argument is forced to A (the collection's type), so type inference is trivial: if A==Float (which the compiler knows), then the compiler knows that the only valid overload of max is one that takes a Float as its second argument. The compiler only finds one ( max(Float,Float) ), and it happens that the other constraint (that B >: A) is trivially satisfied (as B == A == Float for this overload).
This is different for reduce: both the first and second arguments can be any (same) super-type of A (that is, of Float in our specific case). This is a much more lax constraint, and while it could be argued that in this case the compiler could see that there is only one possibility, the compiler is not smart enough here.
Whether the compiler is supposed to be able to handle this case (meaning that this is an inference bug) or not, I must say I don't know. Type inference is a tricky business in scala, and as far as I know the spec is intentionally vague about what can be inferred or not.
Since there are useful applications such as:
scala> Array(1f,2f,3f).reduce[Any](_.toString+","+_.toString)
res3: Any = 1.0,2.0,3.0

trying overload resolution against every possible substitution of the type parameter is expensive and could change the result depending on the expected type you wind up with; or would it have to issue an ambiguity error?
Using -Xlog-implicits -Yinfer-debug shows the difference between reduce(math.max), where overload resolution happens first, and the version where the param type is solved for first:
scala> Array(1f,2f,3f).reduce(math.max(_,_))

[solve types] solving for A1 in ?A1
inferExprInstance {
  tree      scala.this.Predef.floatArrayOps(scala.Array.apply(1.0, 2.0, 3.0)).reduce[A1]
  tree.tpe  (op: (A1, A1) => A1)A1
  tparams   type A1
  pt        ?
  targs     Float
  tvars     =?Float
}

A: It looks like this is a bug in the inferrer, cause with Int it infers types correctly:
private[this] val res2: Int = scala.this.Predef.intArrayOps(scala.Array.apply(1, 2, 4)).reduce[Int]({
  ((x: Int, y: Int) => scala.math.`package`.max(x, y))
});

but with Floats:
private[this] val res1: AnyVal = scala.this.Predef.floatArrayOps(scala.Array.apply(1.0, 3.0, 4.0)).reduce[AnyVal]({
  ((x: Int, y: Int) => scala.math.`package`.max(x, y))
});

If you explicitly annotate reduce with a Float type it should work:
Array(1f, 3f, 4f).reduce[Float](max)

private[this] val res3: Float = scala.this.Predef.floatArrayOps(scala.Array.apply(1.0, 3.0, 4.0)).reduce[Float]({
  ((x: Float, y: Float) => scala.math.`package`.max(x, y))
});

A: There is always scala.math.Ordering:
Array(1f, 2f, 3f).reduceOption(Ordering.Float.max)

A: It doesn't seem to be a bug. Consider the following code:
class C1 {}

object C1 {
  implicit def c2toc1(x: C2): C1 = new C1
}

class C2 {}

class C3 {
  def f(x: C1): Int = 1
  def f(x: C2): Int = 2
}

(new C3).f _                                    //> ... .C2 => Int = <function1>

If I remove implicit conversion I will get an error "ambiguous reference". And because Int has an implicit conversion to Float Scala tries to find the most specific type for min, which is (Int, Int) => Int. The closest common superclass for Int and Float is AnyVal, that's why you see (AnyVal, AnyVal) => AnyVal.
The reason why (x, y) => min(x, y) works is probably because eta-expansion is done before type inference and reduce has to deal with (Int, Int) => Int which will be converted to (AnyVal, AnyVal) => AnyVal.
UPDATE: Meanwhile (new C3).f(_) will fail with "missing parameter type" error, which means f(_) depends on type inference and doesn't consider implicit conversions while f _ doesn't need parameter type and will expand to the most specific argument type if Scala can find one.


text:
Q: How to suppress specific MSBuild warning Is there any way to disable specific MSBuild warning (e.g. MSB3253) when running MSBuild from command line? My build script calls msbuild.exe much the following way:
msbuild.exe MySolution.sln /t:Rebuild /p:Configuration=Release

I've found out that I can suppress C# warnings (e.g. CS0618) using another parameter for msbuild.exe:
msbuild.exe MySolution.sln /t:Rebuild /p:Configuration=Release /p:NoWarn=0618

However, this approach doesn't work for MSBuild warnings. Maybe there is another magic property to set?
I'm using .NET 3.5 and VS2008.

A: I've managed to supress the warning level with /p:WarningLevel=X
msbuild.exe MySolution.sln /t:Rebuild /p:WarningLevel=0 /p:Configuration=Release
                                      ^^^^^^^^^^^^^^^^^
Warning
Level    Meaning
-------- -------------------------------------------
      0  Turns off emission of all warning messages.

      1  Displays severe warning messages

      2  Displays level 1 warnings plus certain, less-severe warnings, such
         as warnings about hiding class members

      3  Displays level 2 warnings plus certain, less-severe warnings, such
         as warnings about expressions that always evaluate to true or false

      4  (the default) Displays all level 3 warnings plus informational warnings

A: For MSB3253 you can just set in project file (*.csproj) that cause such warning.
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <!-- some code goes here -->
    <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
        None
    </ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
    <!-- some code goes here -->
  </PropertyGroup>

A: According to this thread in the MSDN Forum MSBuild warnings can't be suppressed.

A: More recent versions of MSBuild support this via command line (as mentioned by EM0) or with properties:
<PropertyGroup>
    <MSBuildWarningsAsMessages>$(MSBuildWarningsAsMessages);MSB3253</MSBuildWarningsAsMessages>
</PropertyGroup>

For details see this comment.
I didn't find official documentation about this, but it is mentioned in the VerifyFileHash task documentation.

A: For those Googling this now (like me): the upcoming MSBuild 15.0 (to be released with Visual Studio 2017, I presume) will finally implement the /NoWarn option to suppress specific warnings (as well as /WarnAsError to treat either specific warnings or all warnings as errors).

A: Alternative:
Add this to .csproj.
<PropertyGroup>
  <NoWarn>$(NoWarn);MSB3253</NoWarn>
</PropertyGroup>

A: At the time of this post (2021), Microsoft docs recommend DisabledWarnings, this worked for me:
<PropertyGroup>
    <DisabledWarnings>3568</DisabledWarnings>
</PropertyGroup>

Note that the "MS" prefix is omitted


text:
Q: KeyError: 'Label not in explanation' for LIME Image Explainer for Neural Network for binary classification I am using the below code neural network & then trying to interpret the network using LIME
 import lime
 from lime import lime_image
 from skimage.segmentation import mark_boundaries

 model = Sequential()
 model.add(Conv2D(32, kernel_size=3, padding='same', activation='relu'))
 model.add(MaxPooling2D(pool_size=2))
 model.add(Flatten())
 # Output layer
 model.add(Dense(32,activation='relu'))
 model.add(Dense(1, activation='sigmoid'))

 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=epochs, batch_size=batch_size, verbose=1)

explainer = lime_image.LimeImageExplainer(random_state=42)
explanation = explainer.explain_instance(
             X_val[x] #some random sample,
            model.predict, top_labels=2,labels=iter([0,1])
    )
image, mask = explanation.get_image_and_mask(1)

The last line is throwing error: KeyError: 'Label not in explanation' though working fine when passing 0 as parameter. But I wish to visualize for class 1.


text:
Q: Restore db from backup in SSMS - Amazon RDS SQL Server Error 229 I have just signed up for Amazon Web Services for hosting my ASP.NET MVC 5 app. My app uses 3 databases, 1 from database first approach and 2 from code first approach. For that matter I have created databases from SSMS by connecting to the given server name for RDS and master UserName and Password. But now I want to restore my database first database from my local machine. And when I tried to do so, the following error occured when I pressed add backup from device:

I have tried giving the EXECUTE permission in that database properties but of no use. How can I restore it?

A: You can't use the backup and restore when using RDS to transfer data into RDS. You'll need to use another means to get the data in there.

If you have an existing Microsoft SQL Server deployment that you want
  to move to Amazon RDS, the complexity of your task depends on the size
  of your database and the types of database objects that you are
  transferring. For example, a database that contains data sets on the
  order of gigabytes, along with stored procedures and triggers, is
  going to be more complicated than a simple database with only a few
  megabytes of test data and no triggers or stored procedures.
RDS for SQL Server service does not currently support RESTORE DATABASE
  ... FROM FILE, because the database and log file backups must be local
  to the SQL Server instance. Similarly, FILESTREAM is also not
  supported at this time.
The BULK INSERT and OPENROWSET(BULK...) statements from the server are
  not supported import procedures due to their dependency on the
  ADMINISTER BULK OPERATIONS permission which is not granted for SQL
  Server DB instances. Please use the process outlined below to import
  data to a SQL Server DB instance.

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html


text:
Q: Reversing an ArrayList (Understanding the code) I found an exercise in a book that adds some money into an ArrayList, and then reverses them. I know we can easily use Collection.reverse(), which is what my textbook shows, but I found another cool solution online that I am trying to understand but having trouble with.
Heres the code:
class Purse {
    private ArrayList<String> coins = new ArrayList<String>();

    public void addCoin(String coinName) {
        coins.add(coinName);
    }

    public void reverse() {
        for(int start = 0, end = coins.size() - 1; start < coins.size() / 2; start++, end--) {
            swap(start,end,coins);
        }
    }

    private void swap(int starting, int ending, List aList) {
        Object temp = aList.set(starting, aList.get(ending));
        aList.set(ending,temp);
    }

    public String toString() {
        return "Purse: " + coins;
    }

}

public class PurseDemo {
    public static void main(String [] args) {
        Purse purseObj = new Purse();
        purseObj.addCoin("Quarter");
        purseObj.addCoin("Dime");
        purseObj.addCoin("Penny");
        purseObj.addCoin("Nickel");
        System.out.println(purseObj);
        purseObj.reverse();
        System.out.println(purseObj);
    }
}

Here is where my confusion is:
Object temp = aList.set(starting,aList.get(ending));
aList.set(ending,temp);

First of all, I think I get the idea of this. However, this is my first time seeing the Object keyword. What I don't really get is what temp actually represents ( I got this code off online, in my book they havent introduced this keyword Object yet)
Here are my thoughts on an example iteration
Suppose our arrayList has
[Quarter,Dime,Penny,Nickel]

According to Object temp = aList.set(starting,aList.get(ending));
We take the the first spot in the ArrayList Quarter and put the value of nickel in there. So we get the ArrayList
[Nickel,Dime,Penny,Nickel]

Now I'm kind of confused.. When I system.out.println(temp), it tells me the values are Quarter and Dime. But why? Can someone go through an example iteration with me?
AFTER READING ANSWER
[Quarter,Dime,Penny,Nickel]

Nickel replaces Quarter, thus temp is Quarter. So we add Quarter to the end
I.E we get
Quarter,Dime,Penny,Quarter

Wait.. But where did our nickel go?!

A: The set() method returns the object that is being displaced by the new object. The first line
Object temp = aList.set(starting,aList.get(ending));

is the same as:
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));

You could actually do it without the temp variable, in one line:
aList.set(ending, aList.set(starting, aList.get(ending)));

A: The swap method can be translated into its "usual form":
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));
aList.set(ending, temp);

All the code you found does is combine the first two lines because List.set promises to return the replaced value.
Now let's see your example, where aList initially is [Quarter,Dime,Penny,Nickel], and starting is 0 and ending is 3.

*

*Object temp = aList.get(starting);, now temp is Quarter.

*aList.set(starting, aList.get(ending));, now aList is [Nickel,Dime,Penny,Nickel].

*At last, aList.set(ending, temp);, sets the last element of aList to Quarter: [Nickel,Dime,Penny,Quarter]