text:
Q: Realm insert or update object with primary key Im not sure i understand the different between them:
As I see it, realm.createObject can't really update existing key (got the error: Primary key value already exists)
OPTION 1:
    try (Realm realm = Realm.getDefaultInstance()) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(@NonNull Realm realm) {
                CacheFastObjTest a = realm.createObject(CacheFastObjTest.class, key);
                a.setDataType(className.getName());
                a.setExpireTimestamp(expires.getTime());
                a.setText1("dsaf");
                a.setText2("234234324");
                realm.insertOrUpdate(a);
            }
        });
    }

OPTION 2:
    try (Realm realm = Realm.getDefaultInstance()) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(@NonNull Realm realm) {
                CacheFastObjTest a = new CacheFastObjTest();
                a.setKey(key);
                a.setDataType(className.getName());
                a.setExpireTimestamp(expires.getTime());
                a.setText1("dsaf");
                a.setText2("234234324");
                realm.insertOrUpdate(a);
            }
        });
    }

A: CacheFastObjTest a = realm.where(CacheFastObjTest.class).equalTo("id", key).findFirst();
if(a == null) {
     a = realm.createObject(CacheFastObjTest.class, key);
}
a.setDataType(className.getName());
a.setExpireTimestamp(expires.getTime());
a.setText1("dsaf");
a.setText2("234234324");
//realm.insertOrUpdate(a);

A: When you're using realm, you need to programmatically increment your object id before save it. On the below code you check if there's any value stored on your table. If there's no value there, you just set the id of the object to 1 as a default value to the nextId.
int nextId = 1;
if (realm.where(yourclass).max("id") != null){
    nextId = realm.where(yourclass).max("id").intValue() + 1;
}
yourclass.setId(nextId);

A: I found my answer:
In the end, the result is the same.
Option 1 is better practice because when you use:
realm.createObject(CacheFastObjTest.class, key);

Realm is wrap your object and make sure you use the correct primary key otherwise the developer will get exceptions about it.
In the other hand, developers can use options 2
CacheFastObjTest a = new CacheFastObjTest();
a.setKey(key);

for the scenarios above:

Note that Realm.createObject returns a new object with all fields set
  to their default values. If the object is a class with a primary key,
  this could create a conflict—there might be an object with that
  primary key set already. To avoid this, you can create an unmanaged
  object, set its field values, then add it to the Realm with
  copyToRealm or insert: Copy to clipboard.

More information about realm with Primary key


text:
Q: Picture autocorrect Can you recommend me a component or lib for  .net which is able to do auto-correct like Microsoft Office Picture manager does?
Or, can you tell me, how does color auto-correct work? What principles are used?
Are used sets of effects (like saturation, brightness, contrast etc. ) or there is some "intelligent" algorithms of restoring pixels or something like that?
I know that I sound a bit messy, because I don't know much about this subject, but any information about automated color correction will be useful.
P. S. I apologize for my not so great English.

Thanks for your reply,
I've had problems with ImageMagick binaries, so I've decided to use AForge instead, and it has many useful functions, but I still don't know how to use them to get auto correct results.
I'm  familiar with histogram stretching for contrast auto-level, and similar things for each (rgb) color, but I'm not sure is that what software for image processing use for implementing auto-correct.
I'm trying to google this topic, but I'm stuck.
Where can I find more about techniques and algorithms for image auto-correct?

A: This question belongs on stackoverflow I believe.
Anyway, ImageMagick is a command-line image tool that can to very many things on an automated basis. Download ImageMagick from http://imagemagick.org/script/download.php and try the script mentioned on this page:
http://www.fmwconcepts.com/imagemagick/autolevel/index.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Elasticsearch how sum values after aggregation result I have a lot of documents as below under Elasticsearch index:
{
        "_index": "f2016-07-17",
        "_type": "trkvjadsreqpxl.gif",
        "_id": "AVX2N3dl5siG6SyfyIjb",
        "_score": 1,
        "_source": {
          "time": "1468714676424",
          "meta": {
            "cb_id": 25681,
            "mt_id": 649,
            "c_id": 1592,
            "revenue": 2.5,
            "mt_name": "GMS-INAPP-EN-2.5",
            "c_description": "COULL-INAPP-EN-2.5",
            "domain": "wv.inner-active.mobi",
            "master_domain": "649###wv.inner-active.mobi",
            "child_domain": "1592###wv.inner-active.mobi",
            "combo_domain": "25681###wv.inner-active.mobi",
            "ip": "52.42.87.73"
          }
        }
      }

I want to make date histogram/range aggregation on multiple fields and store the result in other collection/index.
So I could make doc_count sum using query/aggregation between hours range.
The Aggregation is:
{
  "aggs": {
    "hour":{
      "date_histogram": {
        "field": "time",
        "interval": "hour"
      },
      "aggs":{
            "hourly_M_TAG":{
               "terms":{
                  "field":"meta.mt_id"
               }
            }
         }....
    }
  }
}

The Result as expected:
"aggregations": {
    "hour": {
      "buckets": [
        {
          "key_as_string": "2016-07-17T00:00:00.000Z",
          "key": 1468713600000,
          "doc_count": 94411750,
          "hourly_M_TAG": {
            "doc_count_error_upper_bound": 1485,
            "sum_other_doc_count": 30731646,
            "buckets": [
              {
                "key": 10,
                "doc_count": 10175501
              },
              {
                "key": 649,
                "doc_count": 200000
              }....
            ]
          }
        },
        {
          "key_as_string": "2016-07-17T01:00:00.000Z",
          "key": 1468717200000,
          "doc_count": 68738743,
          "hourly_M_TAG": {
            "doc_count_error_upper_bound": 2115,
            "sum_other_doc_count": 22478590,
            "buckets": [
              {
                "key": 559,
                "doc_count": 8307018
              },
              {
                "key": 649,
                "doc_count" :100000
              }...

Lets assume that I parse the response and try to store the Result in other Index/Collection.
My Question
What is the best way to store the aggregated results ,
so I can make other query/aggregation that sums the "doc_count" between different hour ranges?
for example: between "2016-07-17T00:00:00.000Z" - "2016-07-17T01:00:00.000Z" want to see the total doc_count on each key
EXPECTED RESULT:
{
          "range_sum": {
            "buckets": [
              {
                "key": 649,
                "doc_count": 300000 // (200000+100000)
              },
              {
                "key": 588,
                "doc_count": 2928548 // ... + ...
              }....
            ]
          }
        }

Thanks!

A: I might have your end goal wrong, but it seems to me like you want
the total doc_count for each value of meta.mt_id, over configurable ranges of time?
If that is the case I don't think you really need to store the result of the first aggregation, you really just need to change the interval value to reflect the bucket sizes you want. If you want totals for each value of meta.mt_id, it might help to flip the aggregation around so you are first aggregating on terms and then on the dates:
{
    "size": 0,
    "aggs": {
    "hourly_M_TAG": {
      "terms": {
        "field": "meta.mt_id"
      },
      "aggs": {
      "hour": {
        "date_histogram": {
          "field": "time",
          "interval": "2h"
        }
      }
    }
  }
}

This will give you results for each meta.mt_id if you wish to get totals added for a particular time range just change the interval to reflect that.
EDIT:
There might be some smart elasticsearch way of doing this but I think I would just do it like this:
Do your original aggregation
foreach bucket in buckets:
    index:
        {
            "id" : {meta.id},
            "timestamp" : {key_as_string}
            "count" : {doc_count}
        }

You should then have an index of all meta.id documents with their doc_count at various timestamps, the granularity of the interval depends on what you need.
Then you can just do a term->sum aggregation on the new index with a range filter (Assuming use of elasticsearch 2.x) for the dates:
{
  "size": 0,
  "filter": {
    "range": {
      "timestamp": {
        "gte": "now-1h",
        "lte": "now"
      }
    }
  },
  "aggs": {
    "termName": {
      "terms": {
        "field": "id"
      },
      "aggs": {
        "sumCounts": {
          "sum": {
            "field": "count"
          }
        }
      }
    }
  }
}

Sorry if that is still not what you are looking for, I think there are many different ways of doing this.


text:
Q: unable to map stored procedure to my .EDMX file. The selected stored procedure or function return no columns I am working on an asp.net mvc 4 web application , and i am using EF version 5, with data base first approach. now i created a stored procedure inside sql server 2008 r2, but when i tried to map the stored procude inside my .edmx file i will get the following error :-

The selected stored procedure or function return no columns

A: If your stored procedure does not return any data,  as it what the EF thinks then instead of selecting complex you need to select None.


text:
Q: How do you sum non integer values in SQL Server? Since the SUM function only returns INT, what function can you use to sum non-integer values like float, decimal or money?
I've seen some claims that the return type of SUM adjusts based on the data types you give it but that is not the case. It only returns INT. I've given it FLOAT, DECIMAL and MONEY, all return INT.
Here's an example query:
PayAmount is type MONEY, FXRate is type FLOAT
SELECT EmployeeID,
       SUM(PayAmount * FXRate) AS AmountInUSD
FROM EmployeeTransactions
GROUP BY EmployeeID

Or with conversion:
SELECT EmployeeID,
       SUM(CONVERT(DECIMAL(18,6), PayAmount * FXRate)) AS AmountInUSD
FROM EmployeeTransactions
GROUP BY EmployeeID

Still fails.
Example with constants:
SELECT EmployeeID,
       SUM(3.14159 * 2.365) AS AmountInUSD
FROM EmployeeTransactions
GROUP BY EmployeeID

Result should be 7.42986035. SQL Server returns 7.

A: SUM does not only return int. The type returned by SUM depends is the most precise type of the provided expressions.
Consider this query:
SELECT SUM(3.14159 * 2.365) AS AmountInUSD;

Result:
+-------------+
| AmountInUSD |
+-------------+
|  7.42986035 |
+-------------+

The actual data type returned above is numeric(38,8) as can be determined with sp_describe_first_result_set:
Result:
EXEC sp_describe_first_result_set N'SELECT SUM(3.14159 * 2.365) AS AmountInUSD;';

+-----------+----------------+-------------+-------------+----------------+------------------+------------+-----------+-------+-----+
| is_hidden | column_ordinal |    name     | is_nullable | system_type_id | system_type_name | max_length | precision | scale | ... |
+-----------+----------------+-------------+-------------+----------------+------------------+------------+-----------+-------+-----+
|         0 |              1 | AmountInUSD |           1 |            108 | numeric(38,8)    |         17 |        38 |     8 | ... |
+-----------+----------------+-------------+-------------+----------------+------------------+------------+-----------+-------+-----+

A: To avoid funny business of multiplying a FLOAT data type, perhaps try something like this?
; WITH t as (SELECT EmployeeID, CAST(PayAmount AS DECIMAL(12,5)) as PayAmount, --or adjust 12,5 as needed
       CAST(FXRate AS DECIMAL(12,3)) as FxRate --or adjust 12,3 as needed
FROM EmployeeTransactions)
SELECT EmployeeId, SUM(PayAmount * FxRate) AS AmountInUSD
FROM t
GROUP BY EmployeeId;


text:
Q: Visual Studio giving error when trying to scaffold viewmodel I am trying to add a view using a viewmodel as the Model class to my MVC project, but when I do I get a popup with this error:

"Error
There was an error running the selected code generator: 'A
  configuration for type Blog.Domain.Entities.Post' has already been
  added. To reference the existing configuration use the Entity() or
  ComplexType() methods.'"

It does not throw an error when I use the actual entity though (Blog.Domain.Entities.Post).
The viewmodel: (its the same with ANY viewmodel though)
public class PostViewModel
    {
        public string Title { get; set; }

        public string Description { get; set; }

        public string UrlSlug { get; set; }

        public DateTime PostedOn { get; set; }

        public Category Category { get; set; }

        public ICollection<Tag> Tags { get; set; }
    }

The Post entity:
public class Post : IEntity
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public string Meta { get; set; }

        public string UrlSlug { get; set; }

        public bool Published { get; set; }

        public DateTime PostedOn { get; set; }

        public DateTime? Modified { get; set; }

        public virtual Category Category { get; set; }

        public virtual ICollection<Tag> Tags { get; set; }
    }

My custom DbContext:
public class BlogDbContext : DbContext
    {
        public BlogDbContext() : base("Name=BlogDbContext")
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlogDbContext>());
        }

        public DbSet<Post> Posts { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Tag> Tags { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Configurations.Add(new PostMap());
            modelBuilder.Configurations.Add(new CategoryMap());
            modelBuilder.Configurations.Add(new TagMap());
        }
    }

EF mapping for the Post entity:
public class PostMap : EntityTypeConfiguration<Post>
    {
        public PostMap()
        {
            HasKey(m => m.Id);

            Property(m => m.Title)
                .HasMaxLength(256)
                .IsRequired();

            Property(m => m.Description)
                .HasMaxLength(5000)
                .IsRequired();

            Property(m => m.Meta)
                .HasMaxLength(1024)
                .IsRequired();

            Property(m => m.UrlSlug)
                .HasMaxLength(256)
                .IsRequired();

            Property(m => m.Published)
                .IsRequired();

            Property(m => m.PostedOn)
                .IsRequired();

            Property(m => m.Modified)
                .IsOptional();

            HasRequired(m => m.Category)
                .WithMany(c => c.Posts);

            HasMany(m => m.Tags)
                .WithMany(t => t.Posts)
                .Map(mc =>
                {
                    mc.ToTable("PostTagMap");
                    mc.MapLeftKey("PostId");
                    mc.MapRightKey("TagId");
                });
        }
    }

I can not figure out why it would give me that error, the viewmodel should have nothing to do with EF whatsoever. Halpmeh!


text:
Q: What is the origin of "woof!"? We know that woof is the sound a dog makes when barking. It is used both as a noun and a verb. The word is  onomatopoeic but it is also used as an interjection. People woof too when they are attracted to someone. Wiktionary defines the interjectional sense as:

(humorous) Expression of strong physical attraction for someone.

It is, of course, listed in urbandictionary also but it is mentioned as a term in gay slang; and interestingly it is also used in a negative sense. Here are the top two entries for the positive and the negative sense in Urbandictionary:

In the gay community, it's an adjective used to describe a sexy guy, but not the feminine kind of guy, but a more masculine guy; one who you wouldn't identify as being gay if you saw him on the street.
1) If you see a hot guy, you say: "Woof!"
  2) He's woofy!

word that is used to describe someone (usually a girl) who is ugly or unattractive
"buzz...your girlfriend... woof!" - kevin, from Home Alone

Another version is the duplication of the word: Woof woof! It is also listed in Urbandictionary and the top two entries are again the positive and the negative sense:

Woof woof is very similar to grrr as in it means whoever is on the receiving end of it is looking mighty fine. You are also very likely to get laid a lot if people say woof woof to you. It's probably best used towards men however as you dont want the woman to think you mean she is dog which is completely different

An expression of negativity. An exclaimation of disapproval of the current situation at hand.

OED lists the interjectional and the second noun sense together and the earliest example is the sound of a collie:

Imitation of a gruff abrupt bark of a dog; also transf. (Cf. whoof int.)

Pronunciation: /wʊf/
Forms:  Also wouf, wowff.
1839      J. Ballantine in Whistle-Binkie 2nd Ser. 26     The wowff o' the colley.

But Etymonline mentions an earlier year:

dog bark noise, first recorded 1804, echoic.

Questions: (all related)

*

*How do these different senses interrelate? How did the dog woof originate and evolve into human woof?

*When did people start woofing?

*How does woof have both a positive and a negative sense (as an interjection)?

A: Woof! as an interjection is originated in the American late-night talk show called The Arsenio Hall Show in 1989. Here is the definition and the origin of the expression from The Routledge Dictionary of Modern American Slang and Unconventional English (By Tom Dalzell):

used as a shout of approval, especially as a male declaration of appreciation for a sexually desirable female US, 1992 Originated by television talk show host Arsenio Hall in 1989; the barking is accompanied by a pumped raised hand, fist clenched.

*

*The woof chorus went through the roof, everybody high-fiving, bopping in glee. — Richard Price, Clockers, p. 203, 1992

The "Wuff, Wuff" sound was based on howlings used at Cleveland Browns (aka "The Dogs") football games:

In Cleveland, Hall's hometown, die-hard fans of the local NFL team, the Browns, are known as "the dogs." And when they root for the team, they "woof." - news.yahoo.com

There is another interesting theory for the origin of woof! and it is also associated with the gay slang term woof!. It is said that woof is first uttered by Madeline Kahn in Mel Brooks' movie Young Frankenstein in 1974.

Some bears say it stems from the actress Madeline Kahn—perhaps not a gay icon, but close enough—in her role as Elizabeth in Mel Brooks' Young Frankenstein. When the monster wordlessly propositions her, and after an initial shock, she notes the impressive bulge in his pants and exclaims, "Woof!" The same humor and insinuation underlie the term today, which is an apt fit for a bear gathering: an atypical but exciting sexual situation that doesn't take itself too seriously.
washingtoncitypaper.com

A: The first line of an old question of mine reads: Scottish dogs used to waff
Further on, I quote:

The onomatopoeic waff (17th C) which means to bark or to yelp like a dog is, sad to say, virtually obsolete but its modern-day counterpart, woof (19th C), still thrives.

Chambers's Twentieth Century Dictionary

*

*adj Waff waf (Scot.) weak, worthless, paltry

*n Waff a worthless person

*n Waff waf (Scot.) a slight hasty motion: a quick light blow: a sudden ailment: a faint but disagreeable odour: a ghost.

*n Waff waf an obsolete form of wave.

*v.i Waff waf (prov.) to bark

Source: The English Dialect Dictionary
 By Joseph Wright
There's nothing new under the sun, people have been bestializing man's behaviour and personality since antiquity, the Scots used the onomatopoeic waff to describe someone worthless, someone who would leave no mark or visible trace of their existence after death.

Hence (1) Waffinger, (2) Waffipoke, sb. a vagabond; a worthless, good-for-nothing person;
  (3) Waffish, adj. disreputable; immoral;
  (5) Waff-looking, ppl.adj. of a disreputable, suspicious appearance.
  [. . . ]
   - Wauf-like painted women, STEVENSON Catriona (1893) xxiii

As can be seen, women were not exempt from being compared to canines. Perhaps wauff-like gave rise to the expression she's a real dog, a highly unattractive and unpleasant girl or woman.

A: Answering to the "positive and a negative sense", "human woof" and "interrelate".
The good and bad sense can be explained either by our envy and our reject of our animal side:
-
bitch; the dog female, which can be in heat will have an sexual animal behaviour which is not considered as appropriate for a human.
-
who let the dog out?!; we have this animal side we cherish as the inexpected and uncontroled part which doze in everyone. The beast hunger is also an erotic part of sex.
Animals are acting in a more free way than what we allow in society, woofing is a trace of the desire to come back to a more natural living as much as a stigmatisation of an uncontrollable behaviour.


text:
Q: add mouse event to svg , detect grid hover I have a bit of a complicated question. I'm trying to render a grid via svg and then add event listeners to the grid. Currently I'm rendering the grid via a <pattern> element. I'm open to other avenues for rendering the grid, but it needs to be scalable / performant, as this grid could easily be 10's of thousands of squares. Think of it like a floorplan or a blueprint.
What I want: I'd like to be able to attach an event listener to every square of the grid.
What I've done: I looked up the svg docs, tried a bunch of different things (like onclick handlers, svg attributes like pointer-events... etc) but with no luck. I can probably make it work with mouse client coordinates, however I'd like to avoid using this method if possible as this svg will have zoom and pan functionality.. which can make transforming coordinates a pain.
Base svg code (simplified for this question):
<svg viewBox="0 0 100 100">
  <g className="view-control">
    <defs>
      <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
        <path d="M 10 0 L 0 0 0 10" fill="none" stroke="gray" strokeWidth="0.5"/>
      </pattern>
    </defs>
    <rect width="100%" height="100%" fill="url(#grid)" />
  </g>
</svg>

Fiddle to play with

A: I'm not sure what your objection to "mouse client coordinates" is, but it is very simple to do, and meets your requirement.

*

*Add a click handler to the grid rectangle.  I've used a click handler for this demo. But if you want to base it on hover, you could use the mousemove event instead.
<rect width="200%" height="200%" fill="url(#grid)" onClick={(e) => handleClick(e)}/>

function handleClick(e) {
  var pos = getSVGPosition(e);
  createRectAt(pos);
}

*The function to convert the mouse coords to svg coords looks like this:
function getSVGPosition(e) {
  var svg = e.nativeEvent.target.ownerSVGElement;
  var pt = svg.createSVGPoint();
  pt.x = e.nativeEvent.clientX;
  pt.y = e.nativeEvent.clientY;
  pt = pt.matrixTransform(svg.getScreenCTM().inverse());
  return {svg: svg, x: pt.x, y: pt.y};
}

*And then for the purposes of the demo, I create a square at the relevant grid position
function createRectAt(pos) {
  var rect = document.createElementNS(pos.svg.namespaceURI, "rect");
  rect.setAttribute("x", Math.floor(pos.x / 10) * 10);
  rect.setAttribute("y", Math.floor(pos.y / 10) * 10);
  rect.setAttribute("width", 10);
  rect.setAttribute("height", 10);
  rect.setAttribute("fill", "green");
  pos.svg.appendChild(rect);
}

https://jsfiddle.net/tp530748/31/

A: If you make the grid a <pattern> then you will not be able to register any mouse events on the pattern. The patterns hitbox will cover the whole <rect>
I recommend calculating the coordinates of the squares yourself based on the size of the <svg>, the viewBox and the spacing of the grid. Attach any mouse events to the SVG element


text:
Q: stored procedure exception handling in asp.net Do i need to use try catch in my stored procedure to know where exactly in my procedure error has occured or can i achieve the same if i useSqlConnection.BeginTransaction in my ASP.NET form or simple try catch may be...???
I tried implementing try catch in my stored procedure..i m using sql server 2005 but it does not know TRY and CATCH keywords or ERROR_MESSAGE() function...i also installed sql server 2005 service manager but still it does not work..
if an error is thrown using RAISERROR method will the exception will be shown in my ASP.NET form??

A: Surround the DB call in your code with the try-catch... try and put it at the level of the code-behind. If you are using a data access layer, put a try-catch there also, with a single throw statement. Then handle it in the code-behind when it bubbles up.

A: To use TRY...CATCH within SQL Server look this manual:
http://msdn.microsoft.com/en-us/library/ms175976.aspx
BEGIN TRY
     { sql_statement | statement_block }
END TRY
BEGIN CATCH
          [ { sql_statement | statement_block } ]
END CATCH

You can catch the exception using catch (SqlException ex). You will find it in the System.Data.SqlClient namespace. You can also check the severity level.


text:
Q: GoogleMaps GeoPoint value range I tried to add some GeoPoints on my map but I've problems with some "special" points.
The range of the latitude value is +90 to -90 and therefore I want to add a point like the this...
int latitude: 85000000;
int longitude = 45000000;
GeoPoint point = new GeoPoint(latitude, longitude);

...and after this I double check the latitude value with:
point.getLongitudeE6();

I always get a maximum value of 80000000 back. Can someone explain why google set this limit for a GeoPoint and what the reason for this limitation is?
Thanks!

A: Your issue is with getLatitudeE6(). GeoPoint doesn't work near the poles. You're probably going too far north or too far south.
This behavior is by design. From the docs:

[The latitude] will be clamped to between -80 degrees and +80 degrees
  inclusive, in order to maintain accuracy in the Mercator projection.

Likewise, longitude is limited to -180 to +180.


text:
Q: Save Javascript Date.now() millisecond timestamps in TimescaleDB I am trying to store unix timestamps with millisecond precision generated from Javascript's Date.now() into a TimescaleDB table Data under the column named timestamp with type int8, or DataTypes.BIGINT when using the Javascript library Sequelize.
Question 1: Is int8/BIGINT the recommended type to store millisecond unix timestamps in?
Question 2: When I try to create the TimescaleDB hypertable using:
SELECT create_hypertable('"Data"', 'timestamp', chunk_time_interval => interval '1 day');

I get the error message

ERROR:  invalid interval: must be an integer type for integer dimensions
  , Time: 0.006000s

Is this because the interval '1 day' can not be used with a column of interger type, but only for timestamp and date types?

A: (Timescaler here)

*

*We recommend using the native timestamptz (timestamp with time zone) or timestamp format whenever possible, rather than integers.  It's microsecond accuracy and is much easier to utilize with time zone conversion, queries using timestamps, now(), etc.  The one time this isn't possible is for nanosecond accuracy (need a bigint), but that doesn't apply here.

*You are already encountering an issue in using an integer timestamp (rather than timestamp type).  You are setting chunk_time_interval to an interval type but your column is an integer.  The problem is that we don't know if your integer represents nanoseconds, seconds, hours, etc., so you can't use something human-readable like '1 day'.  In this case, if your time column is milliseconds, you'd need to specify 86400000.
But in generally, would recommend using timestamptz types if at all possible.


text:
Q: Why can I not pass to_lower_copy directly to transform instead of wrapping it in a lambda? I'm trying to use boost::to_lower_copy and std::transform to lower-case a bunch of strings. As below, Variant 1, using a lamdba works; Variant 2 also works demonstrating that that's the right template-overload the compiler picks. But the lambda is silly – all it does is forward the single argument along to boost::to_lower_copy. But Variant 3, using the function template directly doesn't compile, even if I instantiate it. What am I missing?
I have clang version 3.3 (tags/RELEASE_33/rc3), using libstdc++-4.8.1-1.fc19.i686 and boost-1.53.0-14.fc19.i686.
vector<string> strings = {"Foo", "Bar"};
vector<string> lower_cased_strings;
transform(
    strings.begin(),
    strings.end(),
    inserter(lower_cased_strings, lower_cased_strings.end()),
//  Variant 1
//  [](const string &word) {
//      return boost::to_lower_copy(word);
//  }
//  Variant 2
//  [](const string &word) {
//      return boost::to_lower_copy<string>(word);
//  }
//  Variant 3
    boost::to_lower_copy<string>
    );

> clang++ -std=c++11 lowercase.cxx

In file included from lowercase.cxx:3:
In file included from /usr/include/boost/algorithm/string.hpp:18:
In file included from /usr/include/boost/algorithm/string/std_containers_traits.hpp:23:
In file included from /usr/include/boost/algorithm/string/std/slist_traits.hpp:16:
In file included from /usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/ext/slist:47:
In file included from /usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/algorithm:62:
/usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/bits/stl_algo.h:4949:33: error: too few arguments to function call, expected 2, have 1
        *__result = __unary_op(*__first);
                ~~~~~~~~~~         ^
lowercase.cxx:11:5: note: in instantiation of function template specialization 'std::transform<__gnu_cxx::__normal_iterator<std::basic_string<char> *, std::vector<std::basic_string<char>,
  std::allocator<std::basic_string<char> > > >, std::insert_iterator<std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > > >, std::basic_string<char> (*)(const std::basic_string<char>
  &, const std::locale &)>' requested here
transform(
^

A: Default function arguments.
boost::to_lower_copy has a 3 argument and 2 argument version.  The 2 argument version, which you are instantiating, has a default argument.  So when called directly, you do not need to provide it, it is provided implicitly.
The function pointer to to_lower_copy does not, however, package the fact there is a default argument.


text:
Q: Loading Custom Rules into unaccent postgresql hosted into an amazon aws instance The default unaccent module has no or little support for Greek Letters using the unaccent module as seen in following links:

*

*https://stackoverflow.com/q/49845063

*https://www.postgresql-archive.org/BUG-15347-Unaccent-for-greek-characters-does-not-work-td6035023.html
Also this is my problem in my case as well. So I wanted to load custom unaccent rules as seen in https://www.postgresql.org/docs/current/unaccent.html
So I wanted to know:

*

*In the example CREATE TEXT SEARCH CONFIGURATION fr ( COPY = french ); where the ( COPY = french ) is located?

*Can be the copy statement ( COPY = french ) use data from the STDIN with my own rules?

*Also can I use a dedicated database table in order to load my own unaccent rules as well?
The database is hosted into an Amazon RDS instance.

A:
In the example CREATE TEXT SEARCH CONFIGURATION fr ( COPY = french );
  where the ( COPY = french ) is located?

Text search configurations are stored in pg_catalog.pg_ts_config.
They can also be displayed with \dF[+] in psql.

Can be the copy statement ( COPY = french ) use data from the STDIN with my own rules?

No. The COPY clause in CREATE TEXT SEARCH CONFIGURATION clones a text configuration and has nothing to do (besides the name) with the SQL COPY command meant to import data from the outside of the database.

Also can I use a dedicated database table in order to load my own unaccent rules as well?

No.
The latest version of PostgreSQL (12) comes with unaccent rules that correctly support Greek (as far as I understand) solving the issue #15347 mentioned in the question. For on-premise PostgreSQL instances, DBAs can get the latest unaccent.rules and copy it into an older PostgreSQL version, and making sure that the indexes that depend on unaccent get reindexed. With instances managed by a third party you would have to ask them.


text:
Q: Not able to fetch data besides  tag in Robot Framework I am trying to fetch the numeric value after strong tag, as its not an web element, I am not able to get the value 123456789 in to variable:
If I use Get Text xpath=//*[@id='referral-or-navinet-reference-number'] then the result is "Referral #: 123456789"
Please help me in getting only numeric value in to variable.
HTML Code:

    Referral #: 123456789

A: You can directly use split method of python
Like :-
x.split(":") // x is a string variable of your gettext
http://www.tutorialspoint.com/python/string_split.htm
http://www.pythonforbeginners.com/dictionary/python-split
Hope it will help you :)

A: If your td only contains the wanted text as content text you may use the following xpath:
//*[@id='referral-or-navinet-reference-number']/text()

This should return 123456789 (perhaps with some whitespace)

A: You can use given xpath :
//td[@id="referral-or-navinet-reference-number"]/text()[normalize-space()]


text:
Q: Spatial Filter in Qgis Using Python Is it possible to create buffer and get intersected features in Qgis using Python?
I did in ArcObjects.but i need the same in QGIS also.
Dim topo As ITopologicalOperator
topo = chkPoint
Dim sFc As ISpatialFilter = New SpatialFilter
With sFc
  .Geometry = topo.Buffer(1000)
  .GeometryField = "Shape"
  .SpatialRel = esriSpatialRelIntersects
  .WhereClause = "NAME = 'ROYAL'"
End With
pFcursor = pLayer.Search(sFc, False)
pFeature = pFcursor.NextFeature


text:
Q: Laplace's equation I am very confused. So I have Laplace's equation $\nabla^2\phi(x,y)=0$
and B.C.'s $\phi(x,0)=f(x); \,\,\,\,\,\, \phi(x,1)\equiv0$ where
I have to solve it by Fourier transform.
So I take the Fourier transform of the equation $-k^2\Phi(k,y)=0$ But I don't expect $\Phi$ to be identically $0$...?
Also, I have no idea how to proceed and it's driving me nuts. PLease help! Thanks.

A: If $\Phi(k,y)$ is the Fourier transform of $\phi(x,y)$ with respect to $x$, the equation $\nabla^2 \phi(x,y) = 0$ becomes $\displaystyle -k^2 \Phi(k,y) + \frac{\partial^2 \Phi}{\partial y^2}(k,y) = 0$.  Treating $k$ as constant, you want to solve this as an ordinary differential equation with boundary conditions $\Phi(k,0) = F(k)$ and $\Phi(k,1) = 0$.

A: Either you forgot to "transform the $y$-variable" or "treat the $y$-derivative".
Moreover, it is quite important how the domain for $(x,y)$ looks like. Probably $0\leq y\leq 1$ and $x\in\mathbb{R}$?


text:
Q: PHP variable assign back to self So in PHP, there's all sorts of assignment operators, (like $a += $b, or $str .= $another_str), but is there a way to do such a thing with the built-in functions (or others, even)?
For example, is it possible (or even worthwhile) to shorten this:
$str = strtolower($str)
Object-wise, we'd normally do something like:
$str->toLower() (Pseudo-code)
Where the value of $str would then be the lower case'd value.
but does PHP have and/or do anything like that?
EDIT: In regards to this being string-specific, that was just an example. I'm also curious if it would be possible to "shorten":
$array = array_values($array)
This is more out of curiosity than anything else, since I know these functions all operate with a return value. The question is more about whether there is an operator that assigns the return of the function back to the same variable name.
$a += 4;
// yields same result as
$a = $a + 4;

But is there an operator which can do the same as the top line for things other than math, concatenation, and bitwise. (I'm fairly certain the answer is "no", but the PHP world is vast)

A: No. Unless a built-in takes a variable by-reference (like sort), the built-in will return its result for you to make the assignment yourself (like strtolower).
If you want a OO String behavior, you can use Stringy:
s('string')->toTitleCase()->ensureRight('y') == 'Stringy'

If you're looking to shorten array calls, the pipe operator RFC discussion may interest you:
$ret = scandir($arg)
    |> array_filter($$, function($x) { return $x !== '.' && $x != '..'; })
    |> array_map(function ($x) use ($arg) { return $arg . '/' . $x; }, $$)
    |> getFileArg($$)
    |> array_merge($ret, $$);

This clearly, and unambiguously shows scandir() as the initial source of data, that it goes through an array_filter to avoid recursion, an array_map to requalify the paths, some local function, and finally a merge to combine the result with a collector variable.

A: No because the string is not an object, it's a language construct.


text:
Q: Best approach to add borders to UITableViewCell I often need to add borders to edges of UITableViewCell, but the approach I tried seems not quite working well.
First, I created CustomBorderView class, and implemented drawRect to draw specified type of borders to the view.
#import <UIKit/UIKit.h>

typedef NS_ENUM (NSUInteger,CustomBorderType)
{
    CustomBorderTypeTop,      //Draw a border only at top
    CustomBorderTypeBottom,   //Draw a border only at bottom
    CustomBorderTypeLeft,     //Draw a border only at left
    CustomBorderTypeRight,    //Draw a border only at right
    CustomBorderTypeSides,
    CustomBorderTypeAll,      //Draw a border on all edges
    CustomBorderTypeDottedBottomSolidSides, //Draw a dotted border at bottom and solid    border both sides
    CustomBorderTypeNone      //Cell with no border
};

@interface CustomBorderView : UIView

@property (strong, nonatomic) UIColor *borderColor;
@property (nonatomic) CGFloat borderWidth;
@property (nonatomic) CustomBorderType borderType;

- (id)initWithFrame:(CGRect)frame borderType:(CustomBorderType)borderType;

@end

.m
- (void)drawRect:(CGRect)rect
{
  [super drawRect:rect];
  /* draw lines in the cell */
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetStrokeColorWithColor(context, self.borderColor.CGColor);
  CGContextSetLineWidth(context, self.borderWidth);

  switch (self.borderType)
  {
    ...

    case CustomBorderTypeAll:
        //draw top separator
        CGContextMoveToPoint(context, 0.0f, 0.0f + (self.borderWidth / 2)); //start at this point
        CGContextAddLineToPoint(context, self.bounds.size.width, 0.0f + (self.borderWidth / 2)); //draw to this point

        //draw left edge line
        CGContextMoveToPoint(context, 0.0f + (self.borderWidth / 2), 0.0f); //start at this point
        CGContextAddLineToPoint(context, 0.0f + (self.borderWidth / 2), self.bounds.size.height); //draw to this point

        //draw right edge line
        CGContextMoveToPoint(context, self.bounds.size.width - (self.borderWidth / 2), 0.0f); //start at this point
        CGContextAddLineToPoint(context, self.bounds.size.width - (self.borderWidth / 2), self.bounds.size.height); //draw to this point

        //draw bottom separator
        CGContextMoveToPoint(context, 0.0f, self.bounds.size.height - (self.borderWidth / 2)); //start at this point
        CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height - (self.borderWidth / 2)); //draw to this point
        break;

    case CustomBorderTypeDottedBottomSolidSides:
    {
        //draw left edge line
        CGContextMoveToPoint(context, 0.0f + (self.borderWidth / 2), 0.0f); //start at this point
        CGContextAddLineToPoint(context, 0.0f + (self.borderWidth / 2), self.bounds.size.height); //draw to this point

        //draw right edge line
        CGContextMoveToPoint(context, self.bounds.size.width - (self.borderWidth / 2), 0.0f); //start at this point
        CGContextAddLineToPoint(context, self.bounds.size.width - (self.borderWidth / 2), self.bounds.size.height); //draw to this point

        //stroke solid line
        CGContextStrokePath(context);

        //draw dotted line
        CGFloat dashPattern[] = {1.0, 1.0};
        CGContextSetLineDash(context, 0.0, dashPattern, 2);

        CGContextMoveToPoint(context, 0 , self.bounds.size.height -  (DOT_RADIUS / 2)); //start at this point
        CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height - (DOT_RADIUS / 2)); //draw to this point

        break;
    }

Secondly, add UIViewAutoResizingMaskFlexibleWidth and Height, so that custom view autoresizes when cell bounds changed.
Finally, insert this view below the custom UITableViewCell's contentView.
[cell insertSubview:borderView belowSubview:cell.contentView];

I actually do this in UITableViewCell subclass.
I thought this is a good way to accomplish what I want because it's reusable and easy to use. I can specify the border type in cellForRowAtIndexPath method for each single rows.
However, somehow the border is sometimes off, disappear, extended when I use cell with dynamic height. Especially for dotted lines, dots are extended to vertical lines.
I would like to know if there is a way to fix this issue, or any better approach to accomplish adding borders to views. Thanks in advance!


text:
Q: How do I denote and handle the restriction of function from a disjoint union of the same set? I need to construct a homeomorphism between $\mathbb{R}^2\sqcup\mathbb{R}^2$ and $\mathbb{S}=\{(x,y,z)\in \mathbb{R}^2| x^2-y^2-z^2=1\}$.
The general idea I have is to define
$g:\mathbb{R}^2\rightarrow \mathbb{S}$ to have the rule of assignment $g:(y,z)\longmapsto (\sqrt{y^2+z^2+1},y,z)$
and define
$h:\mathbb{R}^2\rightarrow \mathbb{S}$ to have the rule of assignment $h:(y,z)\longmapsto (-\sqrt{y^2+z^2+1},y,z)$.
But how do I denote the restrictions of my new continuous function  $f:\mathbb{R}^2\sqcup \mathbb{R}^2\rightarrow \mathbb{S}$ formed on the basis of the Universal Property of Disjoint Unions?
And have I even defined the proper functions $g$ and $h$ to get a homeomorphism?
Thank you. Let me know if you need any clarifications.
Edit: I realized that I said something incorrect and deleted that part.

A: Your solution is OK. The space $\Bbb S$ consists of two open disjoint parts and each of the maps $f$ and $g$ provides a homeomorphism of a copy of the plane $\Bbb R^2$ with the respective part. These maps are homeomorphisms, because they are continuous are their inverse maps are projections onto two last coordinates, so continuous too. You can describe the constructed homeomorphism $h$ formally by putting its domain $\{-1,1\}\times \Bbb R^2$ and $h(x,y,z)=(x\sqrt{y^2+z^2+1},y,z)$ for each $(x,y,z)$.


text:
Q: Calculate Network Time Protocol (offset) in objective C I would like to calculate NTP offset in Objective-C. Are there any APIs available to accomplish the same in objective-C?

A: Check out the ios-ntp project; hopefully you'll be able to see how the author of the project is accessing the NTP servers.


text:
Q: Derivative of $f(x) := \min(H(a+x),H(b-x))$ in the sense of distributions (Schwarz) Let $a$ and $b$ be real numbers and consider the function $f:\mathbb R \to \mathbb R$ defined by $$f(x) := \min(H(a+x),H(b-x)),$$ where $H:\mathbb R \to \mathbb R$ is the Heaviside function defined by
$$
H(u) = \begin{cases}0,&\mbox{ if }u \le 0,\\
1,&\mbox{ if }u>0.
\end{cases}
$$

Question. In the sense of distributions, what is the derivative of $f$ ?

I know that $H$ is locally-integrable and its derivative is the well-known Dirac distribution $\delta$. However, I'm very new to the theory of distributions, and I don't quite know how to go about the above problem.

A: $$ f^{\prime}(x)~=~H(a+b) [\delta(x+a)-\delta(x-b)] .$$


text:
Q: Setting up git branches Hi I have setup git on my local machine.
So I can now fully develop locally and push my files to master origin.
but I'd like to be able to commit my files from local to a stage folder on remote, and then from there create a branch with all the files that goes to production. any ideas on how i can establish this
? I am very new to git. (just learned hot to commit, that new lol)

A: You don't really on your remote. You make changes locally and push them to the remote. So in your case, you set the branches up the way you want in your local repository and push the ones you want to to the remote.


text:
Q: Scraping a HTML table using python selenium I have a written a code for scraping a HTML table by using python selenium.
but the issue is, it was returning an empty object from which I was written.  Thank you.  I can scrape any values but not in the table. I have tried on td, tr, span tags. those returning empty object
import requests
import lxml.html as lh
import urllib2
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as BSoup
import pyodbc
import datetime
from django.utils.encoding import smart_str, smart_unicode
import sys
import re

reload(sys)
sys.setdefaultencoding('utf8')

browser =  webdriver.Firefox()
browser.get("https://www.cbsl.gov.lk/measures-of-consumer-price-inflation")

wait = WebDriverWait(browser, 5)
bs_obj = BSoup(browser.page_source, 'html.parser')
table  = bs_obj.findAll('table')

print(table)

A: Using pandas library to get Consumer Price Inflation table data.
Inspect webpage, you will see Consumer Price Inflation table data inside iframe and it's source url is https://www.cbsl.gov.lk/cbsl_custom/inflation/inflationwindow.php and not required selenium library to scrape data. you can also get table data by requests library with pandas, it's response time less then selenium library.
import requests
import pandas as pd

url = "https://www.cbsl.gov.lk/cbsl_custom/inflation/inflationwindow.php"
res = requests.get(url)
tables = pd.read_html(res.text)

print(tables[0])


text:
Q: Drawing 3D points in Java My question is - how to draw 3D points in java? I would like to make some plot in simply way. I' ve tried to used it:
http://jmathtools.berlios.de/doku.php
but there is no documentation.

A: The Java 3D API is an application programming interface used for writing three-dimensional graphics applications and applets.
for more details go there http://download.java.net/media/java3d/javadoc/1.4.0/javax/media/j3d/doc-files/intro.html
example
http://download.java.net/media/java3d/javadoc/1.4.0/javax/media/j3d/doc-files/HelloUniverse.html


text:
Q: Can't link libpqxx in MinGW Using MSYS, I compiled libpq (from compiling postgres).  I then compiled libpqxx.  Now, I want to create a client that will use libpqxx.  libpq seemed to work fine.  And, I can compile code with libpqxx.  However, linking the libpq client application fails.
Here's my code:

#include <pqxx/pqxx>
#include <iostream>
using namespace std;
using namespace pqxx;

int main() {
    connection Conn("dbname=test");
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

I added a bunch of libs to the link in a vain hope it would suddenly work.  Here's what I have so far:

g++ -IC:\msys\1.0\local\pgsql\include -IC:\msys\1.0\local\include -O0 -g3 -Wall -c -fmessage-length=0 -osrc\Controller.o ..\src\Controller.cpp
g++ -LC:\MinGW\lib -LC:\msys\1.0\local\pgsql\lib -LC:\msys\1.0\local\lib -oController.exe src\Controller.o -lws2_32 -lole32 -lpqxx -lpq -loleaut32 -luuid
C:\msys\1.0\local\lib/libpqxx.a(connection_base.o): In function `ZN45_GLOBAL__N__ZN4pqxx16encrypt_passwordERKSsS1_7wait_fdEibP7timeval':
C:/msys/1.0/home/rsolomon/libpqxx/libpqxx-3.0.2/src/connection_base.cxx:1434: undefined reference to `select@20'
C:\msys\1.0\local\lib/libpqxx.a(connection_base.o): In function `ZN4pqxx15connection_base12check_resultERKNS_6resultE':
C:/msys/1.0/home/rsolomon/libpqxx/libpqxx-3.0.2/src/connection_base.cxx:420: undefined reference to `select@20'
collect2: ld returned 1 exit status
Build error occurred, build is stopped
Time consumed: 1770  ms.

I'm thinking the -lws2_32 should've gave me the "select@20".  Why is the linker so uppity?

A: The Unix linker traditionally processes libraries from left to right. So it first considers ws2_32, finds that it has not much use, then goes on to pqxx, and sees that select is undefined and doesn't get defined by any of the later libraries. IOW, try moving ws2_32 to the end of the command line.


text:
Q: How to get only a text from a XML file? I tried this code:
    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string xmlString = System.IO.File.ReadAllText(@"d:\adilipman1937067724.xml");

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlString);
            string t = doc.InnerText;

            textBox1.Text = t;
        }
    }
}

But getting error:
error: Invalid URI: The Uri string is too long. The file im trying to read is xml of chat history in my messenger with my brother. The file size is: 492kb .
Getting error exception message:
System.UriFormatException was unhandled
  Message=Invalid URI: The Uri string is too long.
  Source=System
  StackTrace:
       at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
       at System.Uri..ctor(String uriString, UriKind uriKind)
       at System.Xml.XmlResolver.ResolveUri(Uri baseUri, String relativeUri)
       at System.Xml.XmlUrlResolver.ResolveUri(Uri baseUri, String relativeUri)
       at System.Xml.XmlTextReaderImpl..ctor(String url, XmlNameTable nt)
       at System.Xml.XmlDocument.Load(String filename)
       at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in D:\C-Sharp\AnimatedGifEditor\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 25
       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 WindowsFormsApplication1.Program.Main() in D:\C-Sharp\AnimatedGifEditor\WindowsFormsApplication1\WindowsFormsApplication1\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:

A: Couple of things.
Easiest way to see whether the format of an xml document is correct is to open it in Internet Explorer. It'll tell you if there are problems.
An easy way to view the contents of an xml document, with all xml tags stripped away:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\tt.xml");
string xmlString = doc.InnerText;

The above method will also tell you if there problems with your xml document.
The syntax of your call looks correct, so I assume there must be a problem with your xml document. Fix that first (one problem at a time!), then have another go.

A: Firstly the compile error you are getting is correct, you need to close your string literal.
string xmlString = System.IO.File.ReadAllText(@"C:\tt.xml");

The method that you are using reads all the text from the file so of course you see the tags !!
If you just want the node values then load the xml into an XmlDocument and use the InnerText
property.
        var doc = new XmlDocument();
        doc.Load(@"C:\tt.xml");
        var str = doc.InnerText;

The variable str will contain the text, minus the xml tags.


text:
Q: Using String's enumerateLines function in Swift The enumerateLines function of Swift's String type is declared like this:
enumerateLines(body: (line: String, inout stop: Bool) -> ())

As I understand it, this declaration means: "enumerateLines is a function taking a closure, body, which is handed two variables, line and stop, and returns void."
According to the Swift Programming Language book, I believe I should thus be able to call enumerateLines in a nice terse fashion with a trailing closure, like this:
var someString = "Hello"

someString.enumerateLines()
{
    // Do something with the line here
}

..but that results in a compiler error:
Tuple types '(line: String, inout stop: Bool)' and '()' have a different number of elements (2 vs. 0)
So then I try explicitly putting in the arguments, and doing away with the trailing closure:
addressString.enumerateLines((line: String, stop: Bool)
{
    // Do something with the line here
})

...but that results in the error:
'(() -> () -> $T2) -> $T3' is not identical to '(line: String.Type, stop: Bool.Type)'
In short, no syntax that I've tried has resulted in anything that will successfully compile.
Could anybody point out the error in my understanding and provide a syntax that will work please? I'm using Xcode 6 Beta 4.

A: The closure expression syntax has the general form
{ (parameters) -> return type in
    statements
}

In this case:
addressString.enumerateLines ({
    (line: String, inout stop: Bool) -> () in
    println(line)
})

Or, using the trailing closure syntax:
addressString.enumerateLines {
    (line: String, inout stop: Bool) in
    println(line)
}

Due to automatic type inference, this can be shortened to
addressString.enumerateLines {
    line, stop in
    println(line)
}

Update for Swift 3:
addressString.enumerateLines { (line, stop) in
    print(line)

    // Optionally:
    if someCondition { stop = true }
}

Or, if you don't need the "stop" parameter:
addressString.enumerateLines { (line, _) in
    print(line)
}


text:
Q: How to import .ipr file for configuring Apache Kafka with Intellij IDEA? I am trying to debug Kafka's source code with IntelliJ IDEA and for that I have to setup the IDE first. The official documentation of Kafka provides with the steps and so far, I have completed all of them to run Kafka from the source.
Then there is a step named Building IDE Project which has the command:
./gradlew idea

The output of the above successful command is:
> Configure project :
Starting build with version 3.0.0-SNAPSHOT using Gradle 6.8.3, Java 1.8 and Scala 2.13.5

> Task :idea
Generated IDEA project at file:///Users/aviralsrivastava/dev/kafka/kafka.ipr

I installed Intellij IDEA but unable to figure out how do I import the above file and what purpose does it serve?

A: You should be able to open the ipr file from File menu
However, as the docs state

Note that this is not strictly necessary (IntelliJ IDEA has good built-in support for Gradle projects, for example).

You can just open the root build.gradle file in Intellij, and it'll prompt you to import the folder as a project


text:
Q: Can we create a full dynamic web-site using just CMS like Joomla,Drupal,etc..?or should know some programming like php,jsp beforehand? Should one need to learn php(or jsp) to create dynamic web-sites or just to use CMS ?.I am new to web-development...

A: If you just use the CMS without understanding how it works then you are limited by what the CMS will do out of the box or with plugins. You will have little scope for customisation, and not be  able to fix things if anything breaks.
It really depends what you want to achieve. If a CMS does everything you need it to do, then you can probably get away with just using it out of the box.
(And now I will resist the urge to start a language war and just say that there are other languages beyond PHP and Java).

A: No, you can use cms without knowledge about php, css or even html.

A: Depends on what you want to do in what scope. If you're looking to set up a web site for your band (for example), there's no need to learn PHP. There are plenty of CMSes that can be set up without deep PHP knowledge.
If you want to start a web development career, however, learning a server-side language is pretty mandatory.

A: CMS Made Simple does not require much technical knowledge. Some is benefecient. But in the old days I used to work with complete lack of php/js.


text:
Q: Why the concept of starting and stopping beans in spring There are different ways in which a bean initializaiton/cleanup can be done. Also there are other event mechanisms. Along with all this why does spring have the concept of starting the context which I believe invokes the respective start and stop methods of beans.
To test this, I have a piece of code that looks like this -
public class Car implements InitializingBean, DisposableBean, SmartLifecycle {

     private Engine engine;

     private volatile boolean isRunning = false;

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.debug("Car -- afterPropertiesSet");
    }

    @Override
    public void destroy() throws Exception {
        logger.debug("Car -- destroy");
    }

    @PostConstruct
    public void postConstruction() {
        logger.debug("Car -- postConstruct");
    }

    @PreDestroy
    public void preDestruction() {
        logger.debug("Car -- preDestroy");
    }

    @Override
    public void stop() {
        //Note that this stop notification is not guaranteed to come before destruction: On regular shutdown,
        //Lifecycle beans will first receive a stop notification before the general destruction callbacks are being propagated;
        //however, on hot refresh during a context's lifetime or on aborted refresh attempts, only destroy methods will be called.
        logger.debug("Car -- stop");
        isRunning = false;
    }

    @Override
    public boolean isRunning() {
        //Check whether this component is currently running.
        //In the case of a container, this will return true only if all components that apply are currently running.
        logger.debug("Car -- isRunning");
        return isRunning;
    }

    @Override
    public int getPhase() {
        //Return the phase value of this object.
        logger.debug("Car -- getPhase");
        return 10;
    }

    @Override
    public boolean isAutoStartup() {
        //Returns true if this Lifecycle component should get started automatically by the container
        //A value of false indicates that the component is intended to be started through an explicit start() call instead,
        //analogous to a automatic Lifecycle.
        logger.debug("Car -- isAutoStartup");
        return false;
    }

    @Override
    public void stop(Runnable callback) {
        logger.debug("Car -- stop -  async");
        isRunning = false;
         try {

           //Sleeping for 10 seconds so that all threads
           //get enough time to do their cleanup
           TimeUnit.SECONDS.sleep(10);
           logger.debug("Wait over");
           //Shudown complete. Regular shutdown will continue.
           callback.run();
       } catch (final InterruptedException e) {
           //Looks like we got exception while shutting down,
           //log it or do something with it
       }
    }

    @Override
    public void start() {
        //Start this component.
        //Should not throw an exception if the component is already running.
        logger.debug("Car -- start");
        isRunning = true;
    }
}

First I return true value for isAutoStartUp then I try returning false. The image below is a comparison of the log files of the 2 runs.

And irrespective of whether autostartup is true/false, the code runs fine.

A: This is for when your beans are related to services. You may want to know when they have started successfully, and also have a correct shutdown procedure/ cleanup/ teardown on a routine application shutdown.


text:
Q: How to italicize and underline a particular part of circular text? I have drawn two concentric circles and divided them into three sectors containing some text. How do I decorate the text?
\documentclass[tikz]{standalone}
\usetikzlibrary{decorations.text}

\begin{document}
  \begin{tikzpicture}
    \draw [thick] (0,0) circle (10cm); %outer circle

    \foreach \i/\j in {0/text-1, 120/text-2, 240/text-3}
    {
        \draw [black] (0,0) -- (\i:10cm);
        \draw [black] (0,0) -- (\i+1:10cm);

        \path
        [
        decorate,
        decoration={
            text along path,
            reverse path,
            text={\j},
            text align=center
        }
        ] (\i:10mm) arc (\i:{\i+120}:10mm);
    }

    \draw [thick] (0,0) circle (5cm); %inner most circle

    \foreach \k/\m in {0/Text in Italics: Some text here., 120/Text to be underlined: Some text here too., 240/Text to be underlined and then italicized: Some more text here.}
    {
        \path
        [
        decorate,
        decoration={
            text along path,
            reverse path,
            text={\m},
            text align=center
        }
        ] (\k:65mm) arc (\k:{\k+120}:65mm);
    }
\end{tikzpicture}
\end{document}

A: This does the italics, which is easy:
\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{decorations.text}

\begin{document}
\begin{tikzpicture}
  \draw [thick] (0,0) circle (10cm); %outer circle

  \foreach \i/\j in {0/text-1, 120/text-2, 240/text-3}
  {
      \draw [black] (0,0) -- (\i:10cm);
      \draw [black] (0,0) -- (\i+1:10cm);

      \path
      [
      decorate,
      decoration={
          text along path,
          reverse path,
          text={\j},
          text align=center
      }
      ] (\i:10mm) arc (\i:{\i+120}:10mm);
  }

  \draw [thick] (0,0) circle (5cm); %inner most circle

  \foreach \k/\m in {0/|\itshape|Text in Italics||: Some text here., 120/Text to be underlined: Some text here too., 240/Text to be underlined and |\itshape|then italicized||: Some more text here.}
  {
      \path
      [
      decorate,
      decoration={
          text along path,
          reverse path,
          text={\m},
          text align=center
      }
      ] (\k:65mm) arc (\k:{\k+120}:65mm);
  }
\end{tikzpicture}
\end{document}

For underlining, you have to make choices.

*

*Pick some other effect rather than underlining and proceed as above. Straightforward and typographically preferable, too boot. That is, it is easy and aesthetically better. It doesn't meet your desiderata, but you shouldn't want to underline text, so it meets the desiderata you ought to have. Sadly, this may not be much help.

*Figure out the relevant points and draw the arcs manually. Straightforward but fiddly. Tricky maintenance. Inelegant. Meets desiderata.

*Switch to text effects along path, which allows you to handle every character in the sequence as an independent node. More powerful, but very slow. If you need to do this a lot in a document, it makes a significant difference to compilation times. On the other hand, PGF/TikZ is already very slow, so compilation time is probably not a major concern.
Of these, option 1 would be my recommended and preferred option. Failing that, option 3.

A: Maybe something lighter, based on @cfr solution: the foreach can be replaced by something like this:
\path
[
decorate,
decoration={text along path,
            raise=.7ex,
            text align={align=left},
            text={Some |\bfseries|Bold|| and \itshape|italics|| text}
           }
] (0:65mm) arc (0:120:65mm);


text:
Q: Java Console Game Development | Methods Alright, allow me to elaborate on my dilemma.
I'm making a Console Game with Java. It's not going to be super simple, but I don't want it to be really advanced either. I'm just trying to test my skills using the basics that I've learned. I've started a few times, but constantly ran into the same "problem".
It's not exactly a problem though, just something I could do better. The best way to explain it is to just show some example code.
Here is my Main class. We'll call it "Main.java".
package com.mattkx4.cgamedev.main;

public class Main {
    public static void main(String[] args) {

    }
}

Ok, now let's make a new method in our Main.java. We'll call this method "Start". Our Main class now looks like so:
package com.mattkx4.cgamedev.main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

    }

    public static void start() {
        System.out.println("This is the start.");
        Scanner s = new Scanner(System.in);
        System.out.println("Enter \"NEXT\" to continue.");
        String in = s.nextLine();

        if(in.equalsIgnoreCase("NEXT")) {
        }else{
            System.out.println("Please input \"NEXT\".");
            start();
        }
    }
}

Now we'll add two more methods. We'll call them "middle" and "end". Our finished class now looks like so:
package com.mattkx4.cgamedev.main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        start();
    }

    public static void start() {
        System.out.println("This is the start.");
        Scanner s = new Scanner(System.in);
        System.out.println("Enter \"NEXT\" to continue.");
        String in = s.nextLine();

        if(in.equalsIgnoreCase("NEXT")) {
            middle();
            s.close();
            System.exit(0);
        }else{
            System.out.println("Please input \"NEXT\".");
            start();
        }
    }

    public static void middle() {
        System.out.println("This is the middle.");
        System.out.println("Let's move on to the end.");
        end();
    }

    public static void end() {
        System.out.println("This is the end.\nFinishing up, and heading back to the start() method to close program.");
    }
}

What I've written here is in my opinion a very inefficient program. Inefficient to code with that is. There's has to be another way to doing this program, rather than calling methods inside of other methods to move along the program.
A summary of my question: Is the above code the most efficient way to write a console game?
Thanks in advance! If you have any questions I'll be happy to answer them.
-Matthew

A: There are many kinds of answers to your question.  I'll just enumerate some basic things.

*

*Your design is linear and completely rigid.  Unflexible.  Most applications like this, rather than chaining any methods or the like, store a state somehow.  This is often achieved with an enum.  It's important to understand how state-based programming works.  So you might have something like:
public enum GameState {
    LOAD, START, STOP, BEGIN, MIDDLE, END, GAME_OVER // ... and so on
}

*You're using a bunch of static methods.  This is certainly not what you want to do.  It completely abandons any object-orientation.  If you're making a game world, you will, ideally, have a class for every distinct object in your world, and they will be arranged in a logical hierarchy, by extends-ing each other or implements-ing different interfaces.

*You will need to learn concurrency.  Your user input will almost necessarily come asynchronously to the rendering of your game, if it has any sophistication at all.  At the very, very least, you'll probably at least need Swing to create a GUI.
So, just with those three very basic notes, you will need to study up on object-orientation, polymorphism, concurrency, and all the various data structures available to you.  Your example, to be frank, has the sophistication of a Java 101 project.  (I'm not saying that to be mean.)  If you plan to make a real game, you'll need a lot more of the basics under your belt before you can make real headway.
It's good that you're thinking big, and it's good that your goals for programming are big.  But break that big dream up into manageable chunks.  It will get your farther, faster, and it will also prevent you from getting discouraged.
Best of luck to you!

As a side note, if you start coding up some simple games (even something as simple as a console-based Hangman or Tic-Tac-Toe), please come around to the Code Review Beta.  We'll be more than happy to give you a detailed review of your code and help you along the path to becoming a veteran programmer!  It's a good community with a lot of very constructive criticism.  I've both helped people there (with Java) and received a good amount of help as I learned Python.

A: Well, I don't quite get what this has to do with performance or optimization. But normally you use classes and methods to structure your program.
That being said, there is a huge mistake in your start method. You should axoid the unnecessary recursion and use a loop instead, and remove the exit call:
public static void start() {
    System.out.println("This is the start.");
    Scanner s = new Scanner(System.in);
    System.out.println("Enter \"NEXT\" to continue.");
    String in = s.nextLine();

    if(in.equalsIgnoreCase("NEXT")) {
        middle();
        s.close();
        System.exit(0);
    }else{
        System.out.println("Please input \"NEXT\".");
        start();  // <-- recursion!
    }
}

Better do it like this:
public static void start() {
    System.out.println("This is the start.");
    Scanner s = new Scanner(System.in);

    System.out.println("Enter \"NEXT\" to continue.");

    while ( !s.nextLine().equals("NEXT")) {
        System.out.println("Please input \"NEXT\".");
    }

    middle();

    // you probably also want to put "end();" here - it is not called in the original code
    s.close();
}

A: I guess what you are trying to build up is an main skeleton of the application. I suggest to search for "Game Loop". There a lots of good articles down there about that.
For a general solution, the algorithm is, at big scales, more or less like this:
while (notExit()) {
   event = getNextEvent(); // this can be the user keyboard input or mouse
   renderGame(); // display the graphics on the screen
   doGameLogic(event); // do the game logic according to the events occurred
}

Later, you must take into account how many times per seconds you draw on the screen (FPS) and how many times you compute changes (Physic Frames per second).
Any analogy to the GUI programming is just pure coincidence. I was joking, it is not coincidence, is a fact that GUI and Game Programming shared a thread that fulfill the role of event dispatch thread.
For more information i suggest to read this tutorials : http://sol.gfxile.net/gp/index.html.
Hope it helps!

A: It really depends on the type of application/game how you want to structure it.
In this case, you may find it useful to have some kind of control method which runs the functions in the correct order and has your "flow" logic.
In a more complicated game this method would deal with user input that directs them to different rooms/levels/etc. And you may even have smaller control methods that deal with sub parts.
For instance,
You could have a playGame method that calls registerPlayer(), which would process getting the player's name and any other information. When that method returns then playGame would call a levelOne() method and so on and so forth.
Just try to break it up into logical units for your game!

A: solution from top of my head,
create class
class Location{
public Location( String locationId, String desctiption, List<String> exit){
//populate fields
}

private final String locationId;
private final String desctiption;
private final List<String> exits;
//getters ommited
}

then you could have 3 locations;
start = new Location("START","This is the start.",Arrays.asList("middle"));
middle= new Location("middle","This is the middle.\nLet's move on to the end.",Arrays.asList("end"));
end= new Location("end","This is the end.",null);

now your launcher class
public class Game {
    Map locations = new HashMap();
public Game() {
    locations.put("START", new Location("START", "This is the start.",
            Arrays.asList("middle")));
    locations.put("middle",
            new Location("middle",
                    "This is the middle.\nLet's move on to the end.",
                    Arrays.asList("end")));
    locations.put("end", new Location("end", "This is the end.", null));
}

public static void main(String[] args) {
    Game game = new Game();
    game.start();

}

private void start() {
    visitLocation(locations.get("START"));

}

public void visitLocation(Location location) {
    System.out.println(location.getDescription());

    if (location.getExits().isEmpty()) {
        return;
    }

    Scanner s = new Scanner(System.in);
    String in = "";
    do {
        System.out.println("Choose exit from location : ");
        for (String exit : location.getExits())
            System.out.print(exit + " ");
        in = s.nextLine();
    } while (!location.getExits().contains(in));
    s.close();

    visitLocation(locations.get(in));
}

}
this is still not best but i think it will give you some ideas,


text:
Q: Chrome extension to inject JS into a sandboxed iframe I am working on a Chrome extension to block WebRTC against this flaw: https://github.com/diafygi/webrtc-ips
All good with the current code until until a few days ago when the exploit was updated to include this: iframe.sandbox = 'allow-same-origin';
Since the  sandbox attribute was added, I am getting the error Blocked script execution in 'about:blank' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.
What to do?
Relevant code from manifest.json:
    "content_scripts": [
    {
        "matches": ["<all_urls>"],
        "run_at": "document_start",
        "all_frames": true,
        "match_about_blank": true,
        "js": ["webrtc.js"]
    }
],
 "permissions": [ "tabs", "<all_urls>", "webRequest", "webRequestBlocking"],

My webrtc.js:
 var inject = '(' + function() {
        if (typeof window.RTCPeerConnection !== "undefined") {
            window.RTCPeerConnection = undefined;
        }
        if (typeof window.webkitRTCPeerConnection !== "undefined") {
            window.webkitRTCPeerConnection = undefined;
        }
    } + ')();';
var isInIFrame = window.frameElement && window.frameElement.nodeName == "IFRAME";
    if(isInIFrame==true){
        var script = document.createElement('script');
        script.textContent = inject;
        (document.head || document.documentElement)
        .appendChild(script);
        script.parentNode.removeChild(script);
    }
else
    {
        var script = document.createElement('script');
        script.textContent = inject;
        (document.head || document.documentElement)
        .appendChild(script);
        script.parentNode.removeChild(script);
    }

LE:  I forgot to add that the extension doesn't block WebRTC in latest stable build  40.0.2214.111, but it seems to do so in the Canary 42.0.2304.0.


text:
Q: How can I use my action and programmatically transition to a view controller as defined in the storyboard? I have a sent Action, as follows:
    @IBAction func showSettings(sender: AnyObject) {
     let settingsPicker = SettingsViewController()
     settingsPicker.setDelegate(self)
     let navigationController = UINavigationController (rootViewController: settingsPicker)
     self.presentViewController(navigationController, animated: true, completion: nil)
     }

The method creates a controller, sets a reference to the delegate, and creates a navigation controller.
All this works, however the widgets defined in the story board do not appear. The SettingsViewController should manage a ui which is defined in a story board. I presume becuase I create it programmatically none of the widgets appear. The SettingsViewController does not programmatically create widgets, the are declaratively defined in the story board.
If I link (in the storyboard) the two controllers with a segue, then the widgets appear, but my action is not being used.
How can I use my action and present the view controller / ui as defined in the storyboard?

A: When you create a segue between your UIViewControllers, you should define an identifier, eg: "settingsSegue".
In your code you can then perform that segue by calling the segue with the identifier:
@IBAction func showSetting(sender: AnyObject) {
    performSegueWithIdentifier("settingsSegue", sender: nil)
}

To set up the SettingsViewController you should implement the following:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if let settingsController = segue.destinationViewController as? SettingsViewController {
        settingsController.delegate = self
    }
}

Interacting with Storyboard and Segues

A: If you want to invoke a segue through code, see Laffen's answer.
If you want to create a view controller that's defined in your storyboard and then display it programmatically, use instantiateViewControllerWithIdentifier to create a new instance of your view controller, then display it to the screen as desired (present it modally, push it onto your navigation stack, or whatever you want to do.)


text:
Q: linear programming for bus tickets Hi I work as a programmer at a bus company and I need to implement a ride initialization request. I think it might be a linear programming problem but I'm not sure and I ask for some help :)
A passenger sends my server a request to initialize a bus ride.
The request includes the different entities for the ride. For example a request might be :
Request = [2 Adults, 3 Children, 1 Dog, 2 Bikes]

My server knows what are the different tickets the passenger has. Each ticket has a cost (the price the passenger bought it with) and a list of entities it enables a ride for.
For example, a passenger might possess :
Ticket1- cost 10, enables [1 Adult, 1 Bike]
Ticket2- cost 20, enables [1 Child]
Ticket3- cost 10, enables [1 Adult, 1 Dog]

I would love some help designing an algorithm that finds the optimal collection of tickets to use for the ride (optimal being the cheapest combination), or return error if the ride isn't feasible.
I think this could be represented as a linear programming problem and then I can just use the simplex algorithm to find the optimal solution. But I'm not sure how to do it... please help me I'm not much of a math expert :/
Thank you!

A: The example you have given can be turned very easily into a linear programming problem.
Version 1:
Let Num1 be the number of Ticket1, Num2 be the number of Ticket 2 etc.

Minimise TotalCost
st
TotalCost = 10 Num1 + 20 Num2 + 10Num3
Num1+Num3 $\ge 2$ (this ensures the correct number of adults)
Num2 $\ge 3$ (this ensures the correct number of children)
Num3 $\ge 1$ (this ensures the correct number of dogs)
Num1 $\ge 2$ (this ensures the correct number of bikes)

Version 2:
Reading your comments, I have realised the subtlety that a passenger already holds a certain number of tickets. Let's use the variable NumHeld1, NumHeld2 etc to represent these numbers.
We can assume that a passenger would prefer to use up held tickets (presumably prepaid) before buying new ones, but would also prefer to go for a least cost model. This preference can be modelled by setting an objective function where already held tickets appear to cost less than new tickets:

TotalCost = 10 Num1usingNew + 9 Num1usingHeld + 20 Num2usingNew +
  18Num1usingHeld + 10Num3usingNew + 9Num3usingHeld

(I've reduced the apparent cost of the held tickets by 10% but you can alter that depending on how difficult it is for customers to buy new tickets or how desperate they are to use up their existing stock)

Num1+Num3 $\ge 2$ (this ensures the correct number of adults)
Num2 $\ge 3$ (this ensures the correct number of children)
Num3 $\ge 1$ (this ensures the correct number of dogs)
Num1 $\ge 2$ (this ensures the correct number of bikes)
Num1=Num1usingNew + Num1usingHeld
Num2=Num2usingNew + Num2usingHeld
Num3=Num3usingNew + Num3usingHeld
Num1usingHeld $\le$ NumHeld1
Num2usingHeld $\le$ NumHeld2
Num3usingHeld $\le$ NumHeld3


text:
Q: Limit on Number of Attributes in Table DynamoDB? Hi I currently have a list of dictionaries I am trying to insert into DynamoDB (each dict as an item). Each item having a hashkey and label1,label2,...label3000 key/value pairs with label# being the key and a string as the value pair. Some of my items have up to label fields. Is this a problem when using put_item in DynamoDB? Currently, the label# keys within each dictionary are unordered, and when I go to insert each item it is only adding 19 of the fields.

A: There is no limit to the number of attributes but the total item size is limited to 400kb.

Items
Item Size
The maximum item size in DynamoDB is 400 KB, which includes both
  attribute name binary length (UTF-8 length) and attribute value
  lengths (again binary length). The attribute name counts towards the
  size limit.
For example, consider an item with two attributes: one attribute named
  "shirt-color" with value "R" and another attribute named "shirt-size"
  with value "M". The total size of that item is 23 bytes.
Attributes
Attribute Name-Value Pairs Per Item
The cumulative size of attributes per item must fit within the maximum
  DynamoDB item size (400 KB).
Number of Values in List, Map, or Set
There is no limit on the number of values in a List, a Map, or a Set,
  as long as the item containing the values fits within the 400 KB item
  size limit.

Docs

A: A Dynamodb table can have any number of attributes but while writing a particular row the number of attributes is limited as the cumulative size of an attribute name and attribute value should not exceed 400KB.
Mathematically speaking if the row you are writing has an average attribute size of 7 bytes and the corresponding value for it has a size of 6 bytes then you can have approximately 400 * 1024/13 ~ 31507 attributes for that entry.
If you make another such entry with an entirely different attribute name set then overall your table will have 63014 attributes.
Keep in mind each entry has a limit of 400KB, but the table can have any number of attributes.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-attributes

A: The "limit" is just in view, by default is 20 columns.
You can select to view all columns using the settings button.


text:
Q: htaccess redirect with php variables ... I'm using this format in my htaccess to redirect several pages/links:
RewriteEngine On
RewriteRule special.php http://www.mysite.com [R=301]
...
...
RewriteRule http://www.mysite.com/special.php?t=master http://www.mysite.com/index.php?q=former [R=301, L]

I noticed, first, that only the top line is catching anything, and in fact the others, like the bottom line, did nothing until I put in that top line. Any ideas why?
Second, mysite.com/special.php?t=grave is redirected, by the above top line, to mysite.com/?t=grave , thus retaining the variables in the URL. I don't want this, I simply want it to go to mysite.com with no variables. How do I do this?
Thanks,
Derek

A: First, your first rule catches any URI with special.php in it, even if it is followed by a bunch of characters. To limit it to only and exactly special.php, and to make sure the query string is discarded, change it to
RewriteRule ^special.php$ http://www.mysite.com/? [L, R=301]

Secondly, rewrite rules only match the part after http://www.mysite.com/ (note the last slash) and before the query string (the part after the question mark). So if you change the format of those rules to
RewriteCond %{QUERY_STRING} t=master
RewriteRule ^special.php$ index.php?q=former [R=301, L]

you should be good to go.


text:
Q: What path to put executable to run on Android 29? My Android app includes a set of executables that are extracted to app directory (/data/data/%package%/) on the first run. It worked just fine if targeted to Android 28 (targetSdkVersion). Since November 2, 2020 it not allowed in Google Play and all the apps must target to 29. So it stopped working with permission exception.
What directory should executables be put to now?
PS. Some similar apps have the same issue.

A: https://developer.android.com/about/versions/10/behavior-changes-10#execute-permission
When targeting API 29 (Android 10 / Q) or above, it is not possible anymore to have execute permission for files stored within the app's home directory (data), which is exactly what you are describing (/data/data/%package%/).
This Android 10 modification was introduced in commit: https://android-review.googlesource.com/c/platform/system/sepolicy/+/804149 and was then confirmed officially by Google here: https://issuetracker.google.com/issues/128554619
This significant change is being discussed by various projects, in termux/termux-app#1072 for instance. One recommended and (hopefully) future-proof way is to extract program binaries into the application's native lib directory (with android:extractNativeLibs=true), where files can still be executed but are stored read-only for improved security.
Here are examples showing how to handle this change, in Termux with commit f6c3b6f in the android-10 branch or in this other project showing how to run the Erlang runtime on Android by exctrating all the files from a .zip archive into the jniLibs/"abi" subdirectory ("abi" being arm64-v8a for 64-bit ARM, armeabi-v7a for 32-bit ARM, etc.) with the imposed lib___.so filename format expected by the Android platform. Executable files can simply be moved in the right project folder manually, the important part is to use the lib___.so format for the filenames.
In the Android Manifest file, setting the attribute android:extractNativeLibs="true" will get these lib___.so files extracted at installation time in the right native lib directory, with support for execute permission. Symlinks can finally be created if needed in the usual app directory to use the regular executable names, instead of the harder-to-manipulate lib___.so versions.
Thanks, Jérôme


text:
Q: ¿Por qué no se me crean las tablas en la base de datos desde Spring? ¿Alguién sabe por qué? Tengo mi configuración de esta manera
En mi application.properties:
/**
        spring.jpa.database=MYSQL
        spring.jpa.show-sql=true
        spring.jpa.hibernate.ddl-auto=update
        spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
        spring.datasource.url=jdbc:mysql://localhost:3306/restspring
        spring.datasource.username=root
        spring.datasource.password=root
        **/

    package com.crudrest.models;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

    @Entity
    public class Persona {

        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer id;

        @Column
        private String nombre;

        @Column
        private String apellido;

        @Column
        private Integer edad;

    }


text:
Q: Can't POST data through Angular $resource? I'm trying to figure out how to pass data to an API through Angular's $resource.  I can GET or query any data from my test server currently, but I also want to see how to POST new data to the server.  I am using this code that I've adapted from the AngularJS docs:
.factory("ResourceTest", function($resource) {
    return $resource("http://mywebsite.com/api/:id", {id:'1'}, {
        charge: {method:'POST', params:{charge:true}}
    });
});

When I run ResourceTest.charge(); in my controller, it works fine, and I see a POST request in my server logs.  But when I try to pass any parameters when I call the function (eg ResourceTest.charge({test:false});), the request will not go through, and I can't see any request in the logs. (same happens with .save(), in case anyone is wondering)
Anyone know if it's just a code error I'm making here? I'm pretty new to AngularJS.  Thanks!

A: It appears that you are pulling from the angular docs to try and get resource up and running.  I had quite a time myself and didn't find the docs to very helpful in understanding ngResource and how to correctly implement it.
This article clears things up quite a bit:
http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/

A: Finally figured it out.  The request headers needed to be changed, apparently.  Here's the code I added to make it work, hope it helps someone else out.
.config(function($httpProvider) {
    $httpProvider.defaults.headers.post  = {'Content-Type': 'application/x-www-form-urlencoded'};
})

A: What did you expect the $resource object to do?
If you pass in a data object to the $resource charge function it will send the data as the request payload to the url you defined. See working example below.
myApp.factory("ResourceTest", function($resource) {
    return $resource("http://mywebsite.com/api/:id", {id:'1'}, {
        charge: {method:'POST', params:{charge:true}}
    });
});
myApp.controller('MyCtrl', function($scope, ResourceTest) {
    $scope.name = 'Superhero';
    $scope.test = function (userInput) {
        console.log("check the browser console Network > XHR to see the request payload");
        ResourceTest.charge({'userInput':userInput});
    }
});

fiddle example


text:
Q: Truncate portions of a string to limit the whole string's length in Ruby Suppose you want to generate dynamic page titles that look like this:
"It was all a dream, I used to read word up magazine" from "Juicy" by The Notorious B.I.G
I.e., "LYRICS" from "SONG_NAME" by ARTIST
However, your title can only be 69 characters total and this template will sometimes generate titles that are longer.
One strategy for solving this problem is to truncate the entire string to 69 characters. However, a better approach is to truncate the less important parts of the string first. I.e., your algorithm might look something like this:

*

*Truncate the lyrics until the entire string is <= 69 characters

*If you still need to truncate, truncate the artist name until the entire string is <= 69 characters

*If you still need to truncate, truncate the song name until the entire string is <= 69 characters

*If all else fails, truncate the entire string to 69 characters

Ideally the algorithm would also limit the amount each part of the string could be truncated. E.g., step 1 would really be "Truncate the lyrics to a minimum of 10 characters until the entire string is <= 69 characters"
Since this is such a common situation, I was wondering if someone has a library or code snippet that can take care of it.

A: I had a similar problem with truncating titles to put them into a tweet. I ended up putting everything in an array and joining it. Code is reasonably readable. Here's a version that's modified to do what you're looking for.
message = [lyrics, " from ", song_name, " by ", artist]
[0, 2, 4].each do |index|
  length = message.join.length
  message[index] = message[index][0...(69-length)]
end
message = message.join

You might also want to append an ellipsis when you truncate, so that people know it's been cut.

A: This is a reasonably full implementation
#!/usr/bin/ruby

MIN_WORD_SIZE = 10
MAX_STRING_SIZE = 55  # 69 - 14 characters for punctuation spacing and conjunctions

def smart_trunc_words(lyrics, artist, title)

  words = [lyrics, artist, title]

  words.each_index do |idx|
    total_length = words.to_s.length
    if ( words[idx].length > MIN_WORD_SIZE and total_length > MAX_STRING_SIZE )
      other_words = total_length - words[idx].length
      max_word_size = [MAX_STRING_SIZE - other_words, MIN_WORD_SIZE].max
      words[idx] = truncate_word words[idx], max_word_size
    end
  end

  words

end

def truncate_word(word, sub_size)
  # Enhance by adding ellipses here or break on a word boundary
  word[0, sub_size]

end

def smart_trunc(lyrics, artist, title)
  lyrics, artist, title  = smart_trunc_words lyrics, artist, title
  '"%s" from "%s" by %s' % [lyrics, title, artist]
end

test_data = [
  [ "It was all a dream, I used to read word up magazine",  "The Notorious B.I.G", "Juicy"],
  [ "Ground Control to Major Tom, your circuits dead there's something wrong",  "David Bowie", "Space Oddity"],
  [ "Back Home they'll be thinking about us", "The England world cup squad (1970)" , "Back Home"],
  [ "I'm the new cancer", "Panic at the disco", "Theres A Good Reason These Tables Are Numbered Honey, You Just Havent Thought Of It Yet"],
  [ "Short lyrics", "short band", "short song"],
  [ "VeryLongLyrics VeryLongLyrics VeryLongLyrics VeryLongLyrics VeryLongLyrics",
    "VeryLongBandName VeryLongBandName VeryLongBandName VeryLongBandName VeryLongBandName",
    "VeryLongTitle VeryLongTitle VeryLongTitle VeryLongTitle VeryLongTitle"]
]

test_data.each do |td|
  lyrics = td[0]
  artist = td[1]
  title = td[2]
  puts 'Original string : "%s" from "%s" by %s' % [lyrics, title, artist]
  puts "New string      : #{smart_trunc lyrics, artist, title}"
end

That produces the following results

Original string : "It was all a dream, I used to read word up magazine" from "Juicy" by The Notorious B.I.G
New string      : "It was all a dream, I used to r" from "Juicy" by The Notorious B.I.G
Original string : "Ground Control to Major Tom, your circuits dead there's something wrong" from "Space Oddity" by David Bowie
New string      : "Ground Control to Major Tom, you" from "Space Oddity" by David Bowie
Original string : "Back Home they'll be thinking about us" from "Back Home" by The England world cup squad (1970)
New string      : "Back Home th" from "Back Home" by The England world cup squad (1970)
Original string : "I'm the new cancer" from "Theres A Good Reason These Tables Are Numbered Honey, You Just Havent Thought Of It Yet" by Panic at the disco
New string      : "I'm the ne" from "Theres A Good Reason These Tables A" by Panic at t
Original string : "Short lyrics" from "short song" by short band
New string      : "Short lyrics" from "short song" by short band
Original string : "VeryLongLyrics VeryLongLyrics VeryLongLyrics VeryLongLyrics VeryLongLyrics" from "VeryLongTitle VeryLongTitle VeryLongTitle VeryLongTitle VeryLongTitle" by VeryLongBandName VeryLongBandName VeryLongBandName VeryLongBandName VeryLongBandName
New string      : "VeryLongLy" from "VeryLongTitle VeryLongTitle VeryLon" by VeryLongBa

No doubt some of the ruby gurus will make it shorter and/or more idiomatic


text:
Q: how do I look an array to extract data Hi all Im trying to query a database and store the results ($searchResults[]) as an array :
<?php

if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
    {
        $_POST['industryList'] = $selected;
        $locationListResults = $_POST['locationList'];

        $results = mysqli_query($con,"SELECT * FROM currentListings
WHERE location = '$locationListResults' AND industry = '$selected'");

        $searchResults = array();

        while($row = mysqli_fetch_array($results))
            {
                $searchResults[] = $row['industry'];
                $searchResults[] = $row['location'];
                $searchResults[] = $row['title'];
                $searchResults[] = $row['description'];
            }

    }
                mysqli_close($con);
}

?>

the problem im getting is when I try to echo the result:
<?php

echo $searchResults[0];

?>

its only bringing back 1 result not displaying all the results in the arrray as i want it to.
Could anybody please point out what it is im doing wrong.
Any help would be greatly appreciated

A: Do like this
<?php
print_r($searchResults); // Prints all array elements
?>

Alternatively, you can make use of a for loop to echo all elements too..
foreach($searchResults as $k=>$v)
{
 echo $v;
 echo "<br>";
}

A: Your code puts your data into 1D array. You probably want sth else so instead of this:
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];

do this:
$tmp = array();

$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];

$searchResults[] = $tmp;

or just this (thanks to Barmar):
$searchResults[] = $row;

This way you store your data as 2D array. So every row you obtain remains in one subarray.
To print the row (which is now in 2D array) iterate over subarrayw:
foreach($one_of_searchResult_rows as $k => $v)
{
    // do whatever you need with $k and $v
}

A: Lets make it simple :
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);

Reference : mysqli_fetch_all

A: I think you want a 2d array. Try this code snippet :
$searchResults = array();

    while($row = mysqli_fetch_array($results))
        {
            array_push($searchResults,$row);
        }

This should push each row as an associative array in every cell of your final searchResuts array. You could then access the values like:
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result