Programs & Examples On #Apache chainsaw

Chainsaw is a free, open source, java-based log viewer tool, mainly intended as a log4j companion.

Converting newline formatting from Mac to Windows

Here's a really simple approach, worked well for me, courtesy Davy Schmeits's Weblog:

cat foo | col -b > foo2

Where foo is the file that has the Control+M characters at the end of the line, and foo2 the new file you are creating.

Sorting by date & time in descending order?

SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY date ASC

"DESC" stands for descending but you need ascending order ("ASC").

Ways to implement data versioning in MongoDB

Here's another solution using a single document for the current version and all old versions:

{
    _id: ObjectId("..."),
    data: [
        { vid: 1, content: "foo" },
        { vid: 2, content: "bar" }
    ]
}

data contains all versions. The data array is ordered, new versions will only get $pushed to the end of the array. data.vid is the version id, which is an incrementing number.

Get the most recent version:

find(
    { "_id":ObjectId("...") },
    { "data":{ $slice:-1 } }
)

Get a specific version by vid:

find(
    { "_id":ObjectId("...") },
    { "data":{ $elemMatch:{ "vid":1 } } }
)

Return only specified fields:

find(
    { "_id":ObjectId("...") },
    { "data":{ $elemMatch:{ "vid":1 } }, "data.content":1 }
)

Insert new version: (and prevent concurrent insert/update)

update(
    {
        "_id":ObjectId("..."),
        $and:[
            { "data.vid":{ $not:{ $gt:2 } } },
            { "data.vid":2 }
        ]
    },
    { $push:{ "data":{ "vid":3, "content":"baz" } } }
)

2 is the vid of the current most recent version and 3 is the new version getting inserted. Because you need the most recent version's vid, it's easy to do get the next version's vid: nextVID = oldVID + 1.

The $and condition will ensure, that 2 is the latest vid.

This way there's no need for a unique index, but the application logic has to take care of incrementing the vid on insert.

Remove a specific version:

update(
    { "_id":ObjectId("...") },
    { $pull:{ "data":{ "vid":2 } } }
)

That's it!

(remember the 16MB per document limit)

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

How to remove unwanted space between rows and columns in table?

Just adding on top of Jacob's answer, for img in td,

body {line-height: 0;}
img {display: block; vertical-align: bottom;}

This works for most email clients, including Gmail. But not Outlook. For outlook, you need to do two steps more:

table {border-collapse: collapse;}

and set every td elements to have the same height and width as its contained images. For example,

<td width="600" height="80" style="line-height: 80px;">
    <img height="80" src="http://www.website.com/images/Nature_01.jpg" width="600" />
</td>

How do I copy the contents of one ArrayList into another?

You need to clone() the individual object. Constructor and other methods perform shallow copy. You may try Collections.copy method.

In SQL how to compare date values?

Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.

If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.

How to resolve the C:\fakepath?

If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.

How to check if a URL exists or returns 404 with Java?

Use HttpUrlConnection by calling openConnection() on your URL object.

getResponseCode() will give you the HTTP response once you've read from the connection.

e.g.

   URL u = new URL("http://www.example.com/"); 
   HttpURLConnection huc = (HttpURLConnection)u.openConnection(); 
   huc.setRequestMethod("GET"); 
   huc.connect() ; 
   OutputStream os = huc.getOutputStream(); 
   int code = huc.getResponseCode(); 

(not tested)

JavaScript string and number conversion

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100


Step (4) Covert 223 into "223"

 (223).toString() 


Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()

SQL - How to select a row having a column with max value

Answer is to add a having clause:

SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)

this should work and gets rid of the neccesity of having an extra sub select in the date clause.

Render partial from different folder (not shared)

Just include the path to the view, with the file extension.

Razor:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

substring index range

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

How to find the number of days between two dates

DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay

Installing a dependency with Bower from URL and specify version

Installs package from git and save to your bower.json dependency block.

  1. bower register package-name git-endpoint#version
  2. install package-name --save

(--save will save the package name version in the bower.json file inside the dependency block).

Reference

Trimming text strings in SQL Server 2008

No Answer is true

The true Answer is Edit Column to NVARCHAR and you found Automatically trim Execute but this code UPDATE Table SET Name = RTRIM(LTRIM(Name)) use it only with Nvarchar if use it with CHAR or NCHAR it will not work

Returning value from called function in a shell script

I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)

# Syntax _w (wrapReturn)
# arg1 : method to wrap
# arg2 : variable to set
_w(){
eval $1
read $2 <<EOF
$?
EOF
eval $2=\$$2
}

as in (yep, the example is somewhat silly, it's just an.. example)

getDay(){
  d=`date '+%d'`
  [ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
  return $d
}

dayzToSalary(){
  daysLeft=0
  if [ $1 -lt 26 ]; then 
      daysLeft=`expr 25 - $1`
  else
     lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
     rest=`expr $lastDayInMonth - 25`
     daysLeft=`expr 25 + $rest`
  fi
  echo "Mate, it's another $daysLeft days.."
}

# main
_w getDay DAY # call getDay, save the result in the DAY variable
dayzToSalary $DAY

In DB2 Display a table's definition

Right-click the table in DB2 Control Center and chose Generate DDL... That will give you everything you need and more.

How to Convert Int to Unsigned Byte and Back

If you want to use the primitive wrapper classes, this will work, but all java types are signed by default.

public static void main(String[] args) {
    Integer i=5;
    Byte b = Byte.valueOf(i+""); //converts i to String and calls Byte.valueOf()
    System.out.println(b);
    System.out.println(Integer.valueOf(b));
}

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

Convert MFC CString to integer

i've written a function that extract numbers from string:

int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
   // get startIndex
   int startIndex = src.Find(str) + CString(str).GetLength();
   // cut the string
   CString toreturn = src.Mid(startIndex, length);
   // convert to number
   return _wtoi(toreturn); // atoi(toreturn)
}

Usage:

CString str = _T("digit:1, number:102");
int  digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);

Switching a DIV background image with jQuery

If you use a CSS sprite for the background images, you could bump the background offset +/- n pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.

How to script FTP upload and download?

I had this same issue, and solved it with a solution similar to what Cheeso provided, above.

"doesn't work, says password is srequire, tried it a couple different ways "

Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.

Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).

Regardless, as doing a WebClient.DownloadFile is the way to go.

Positioning <div> element at center of screen

I would do this in CSS:

div.centered {
  position: fixed; 
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

then in HTML:

<div class="centered"></div>

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

Add ArrayList to another ArrayList in java

Your Problem

Mainly, you've got 2 major problems:

You are using adding a List of Strings. You want a List containing Lists of Strings.

Note as well that when you invoke this:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.

You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.

So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

  • i = 0

    nodes: [PropertyStart,a,b,c,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd]]
    
  • i = 1

    nodes: [PropertyStart,d,e,f,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
    
  • i = 2

    nodes: [PropertyStart,g,h,i,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
    
  • and so on...

Some Other Corrections

Follow the Java Naming Conventions

Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).

Learn a Bit More About Types

You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.

There's a difference between a type, an interface, and an implementation.

Use Generics for Stronger Typing in Collections

Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.

So your code becomes:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code

You could do away with the nodeList entirely, and write the following once you've fixed your types:

list.add(nodes);

Use the Right Scope

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).

SSCCE

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

MySQL Cannot Add Foreign Key Constraint

My problem was that I was trying to create the relation table before other tables!

DATEDIFF function in Oracle

We can directly subtract dates to get difference in Days.

    SET SERVEROUTPUT ON ;
    DECLARE
        V_VAR NUMBER;
    BEGIN
         V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
         DBMS_OUTPUT.PUT_LINE(V_VAR);
    END;

Using C++ base class constructors?

No, that's not how it is done. Normal way to initialize the base class is in the initialization list :

class A
{
public: 
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};


void main()
{
    B b(10);
}

How to implement onBackPressed() in Fragments?

In activity life cycle, always android back button deals with FragmentManager transactions when we used FragmentActivity or AppCompatActivity.

To handle the backstack we don't need to handle its backstack count or tag anything but we should keep focus while adding or replacing a fragment. Please find the following snippets to handle the back button cases,

    public void replaceFragment(Fragment fragment) {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.activity_menu_fragment_container, fragment).commit();
    }

Here, I won't add back stack for my home fragment because it's home page of my application. If add addToBackStack to HomeFragment then app will wait to remove all the frament in acitivity then we'll get blank screen so I'm keeping the following condition,

if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
}

Now, you can see the previously added fragment on acitvity and app will exit when reaching HomeFragment. you can also look on the following snippets.

@Override
public void onBackPressed() {

    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        closeDrawer();
    } else {
        super.onBackPressed();
    }
}

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

SQL Error: ORA-00913: too many values

You should specify column names as below. It's good practice and probably solve your problem

insert into abc.employees (col1,col2) 
select col1,col2 from employees where employee_id=100; 

EDIT:

As you said employees has 112 columns (sic!) try to run below select to compare both tables' columns

select * 
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME 
                               and  ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'

and than you should upgrade your tables to have the same structure.

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Eclipse will not open due to environment variables

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.standard.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
**-vm
C:/Program Files (x86)/Java/jdk1.7.0_45/bin/javaw.exe** =>false
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m
-vm
C:\Program Files (x86)\Java\jdk1.7.0_45\bin\javaw.exe

Proper way to rename solution (and directories) in Visual Studio

Remove/add project file method

This method is entirely aimed at renaming the directory for the project, as viewed in Windows Explorer.

  1. Backup your entire project using something like GIT, SVN, or WinZip (important!).
  2. Within the solution in Visual Studio, remove the project.
  3. Rename the directory in Windows Explorer.
  4. Add the project back in again within Visual Studio.

Advantages

  • You can make the directory within Windows Explorer match the project name within the solution.

Disadvantages

  • If you remove a library, it removes any references to the said library from other projects. The solution may not compile after this until you add the references to said library back in (this is quite easy). This is the reason why step 1 (backup) is so important.
  • If you have source control, you will lose the history of the file.

Right-clicking on a project and selecting "Open Folder in Windows Explorer" is useful to keep track of where the project is stored while you are performing this process.

The difference in months between dates in MySQL

PERIOD_DIFF calculates months between two dates.

For example, to calculate the difference between now() and a time column in your_table:

select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;

How to change style of a default EditText

You have a few options.

  1. Use Android assets studios Android Holo colors generator to generate the resources, styles and themes you need to add to your app to get the holo look across all devices.

  2. Use holo everywhere library.

  3. Use the PNG for the holo text fields and set them as background images yourself. You can get the images from the Android assets studios holo color generator. You'll have to make a drawable and define the normal, selected and disabled states.

UPDATE 2016-01-07

This answer is now outdated. Android has tinting API and ability to theme on controls directly now. A good reference for how to style or theme any element is a site called materialdoc.

Apply vs transform on a group object

I am going to use a very simple snippet to illustrate the difference:

test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']

The DataFrame looks like this:

    id  price   
0   1   1   
1   2   2   
2   3   3   
3   1   2   
4   2   3   
5   3   1   
6   1   3   
7   2   1   
8   3   2   

There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.

Now, I want to find the minimum payment made by each customer. There are two ways of doing it:

  1. Using apply:

    grouping.min()

The return looks like this:

id
1    1
2    1
3    1
Name: price, dtype: int64

pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
  1. Using transform:

    grouping.transform(min)

The return looks like this:

0    1
1    1
2    1
3    1
4    1
5    1
6    1
7    1
8    1
Name: price, dtype: int64

pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9    

Both methods return a Series object, but the length of the first one is 3 and the length of the second one is 9.

If you want to answer What is the minimum price paid by each customer, then the apply method is the more suitable one to choose.

If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment, then you want to use transform, because:

test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row

Apply does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

To make it a bit more user-friendly: After you've unpacked it, go into the directory, and run bin/pycharm.sh. Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...

Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)

To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)

(Unless you are trying to debug an application, you usually do not need to see the output of it.)

Spring 3 RequestMapping: Get path value

Building upon Fabien Kruba's already excellent answer, I thought it would be nice if the ** portion of the URL could be given as a parameter to the controller method via an annotation, in a way which was similar to @RequestParam and @PathVariable, rather than always using a utility method which explicitly required the HttpServletRequest. So here's an example of how that might be implemented. Hopefully someone finds it useful.

Create the annotation, along with the argument resolver:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WildcardParam {

    class Resolver implements HandlerMethodArgumentResolver {

        @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
            return methodParameter.getParameterAnnotation(WildcardParam.class) != null;
        }

        @Override
        public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
            HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
            return request == null ? null : new AntPathMatcher().extractPathWithinPattern(
                    (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
                    (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
        }

    }

}

Register the method argument resolver:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new WildcardParam.Resolver());
    }

}

Use the annotation in your controller handler methods to have easy access to the ** portion of the URL:

@RestController
public class SomeController {

    @GetMapping("/**")
    public void someHandlerMethod(@WildcardParam String wildcardParam) {
        // use wildcardParam here...
    }

}

How To Get Selected Value From UIPickerView

       NSInteger SelectedRow;
                   SelectedRow = [yourPickerView selectedRowInComponent:0];
                   selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
                   self.YourTextField.text= selectedPickerString;

    // if  you want to move pickerview to selected row then 
 for (int i = 0; I<YourPickerArray.count; i++) {
  if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) { 
[yourPickerView selectRow:i inComponent:0 animated:NO];
 }
}

Best Practices for Custom Helpers in Laravel 5

instead of including your custom helper class, you can actually add to your config/app.php file under aliases.

should be look like this.

 'aliases' => [ 
    ...
    ...
    'Helper' => App\Http\Services\Helper::class,
 ]

and then to your Controller, include the Helper using the method 'use Helper' so you can simply call some of the method on your Helper class.

eg. Helper::some_function();

or in resources view you can directly call the Helper class already.

eg. {{Helper::foo()}}

But this is still the developer coding style approach to be followed. We may have different way of solving problems, and i just want to share what i have too for beginners.

How can I schedule a job to run a SQL query daily?

I made an animated GIF of the steps in the accepted answer. This is from MSSQL Server 2012

Schedule SQL Job

Twitter Bootstrap - full width navbar

Put the navbar out of your container:

<div class="navbar">
    <div class="navbar-inner">
               <!-- nav bar items here -->
     </div>
</div>
<div class="container">

</div>

EDIT:

Here is one that I did with responsive navbar. The code fits the document body:

    <div class="navbar navbar-fixed-top">
        <div class="navbar-inner">
        <div class="container">

          <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          </a>

          <!-- Be sure to leave the brand out there if you want it shown -->
          <a class="brand" href="#">Project name</a>


          <!-- Everything you want hidden at 940px or less, place within here -->
          <div class="nav-collapse">
          <!-- .nav, .navbar-search, .navbar-form, etc -->
          <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li class="divider-vertical"></li>
              <li><a href="#">Link</a></li>
              <li class="divider-vertical"></li>
              <li><a href="#">Link</a></li>
            </ul>
          <ul class="nav pull-right">
            <li><a href="#">Log out</a></li>
          </ul>
          </div>

          </div>
        </div>

    </div>
  <div class="container">
    <div class="row">
      <div class="span12">

      </div>
    </div>


  </div> <!-- end container -->
  <script type="text/javascript" src="/assets/js/jquery-1.8.2.min.js"></script>
  <script type="text/javascript" src="/assets/js/bootstrap.min.js"></script>

Html5 Full screen video

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

Change DataGrid cell colour based on values

In my case convertor must return string value. I don't why, but it works.

*.xaml (common style file, which is included in another xaml files)

<Style TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>

*.cs

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
    return "#" + color.Name;
}

LINQ Group By into a Dictionary Object

The following worked for me.

var temp = ctx.Set<DbTable>()
  .GroupBy(g => new { g.id })
  .ToDictionary(d => d.Key.id);

Automatic vertical scroll bar in WPF TextBlock?

You can use

ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"

These are attached property of wpf. For more information

http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html

SimpleDateFormat parsing date with 'Z' literal

tl;dr

Instant.parse ( "2010-04-05T17:16:00Z" )

ISO 8601 Standard

Your String complies with the ISO 8601 standard (of which the mentioned RFC 3339 is a profile).

Avoid java.util.Date

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.

Instead use either the Joda-Time library or the new java.time package in Java 8. Both use ISO 8601 as their defaults for parsing and generating string representations of date-time values.

java.time

The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

The Instant class in java.time represents a moment on the timeline in UTC time zone.

The Z at the end of your input string means Zulu which stands for UTC. Such a string can be directly parsed by the Instant class, with no need to specify a formatter.

String input = "2010-04-05T17:16:00Z";
Instant instant = Instant.parse ( input );

Dump to console.

System.out.println ( "instant: " + instant );

instant: 2010-04-05T17:16:00Z

From there you can apply a time zone (ZoneId) to adjust this Instant into a ZonedDateTime. Search Stack Overflow for discussion and examples.

If you must use a java.util.Date object, you can convert by calling the new conversion methods added to the old classes such as the static method java.util.Date.from( Instant ).

java.util.Date date = java.util.Date.from( instant );

Joda-Time

Example in Joda-Time 2.5.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ):
DateTime dateTime = new DateTime( "2010-04-05T17:16:00Z", timeZone );

Convert to UTC.

DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );

Convert to a java.util.Date if necessary.

java.util.Date date = dateTime.toDate();

Save Dataframe to csv directly to s3 Python

You can also use the AWS Data Wrangler:

import awswrangler as wr
    
wr.s3.to_csv(
    df=df,
    path="s3://...",
)

Note that it will handle multipart upload for you to make the upload faster.

Easiest way to toggle 2 classes in jQuery

Here is a simplified version: (albeit not elegant, but easy-to-follow)

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'

}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'

});

Alternatively, a similar solution:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});

Origin http://localhost is not allowed by Access-Control-Allow-Origin

I fixed this (for development) with a simple nginx proxy...

# /etc/nginx/sites-enabled/default
server {
  listen 80;
  root /path/to/Development/dir;
  index index.html;

  # from your example
  location /search {
    proxy_pass http://api.master18.tiket.com;
  }
}

Manually put files to Android emulator SD card

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)enter image description here

How to stop C# console applications from closing automatically?

Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.

How can I check MySQL engine type for a specific table?

SHOW CREATE TABLE <tablename>\G

will format it much nicer compared to the output of

SHOW CREATE TABLE <tablename>;

The \G trick is also useful to remember for many other queries/commands.

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

Fixed height and width for bootstrap carousel

set style="height:300px !important;" and "imgBanner" for img tag.

<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">

then if you want responsive image, so you can use jquery as:

$.(function(){
   $(window).resize(respWhenResize);
   respWhenResize();
 })



respWhenResize(){
 
       if (pagesize < 578) {
         $('.imgBanner').css('height','200px')
        } else if (pagesize > 578 ) {
            $('.imgBanner').css('height','300px')
        }
     }

How to run Selenium WebDriver test cases in Chrome

You should download the chromeDriver in a folder, and add this folder in your PATH environment variable.

You'll have to restart your console to make it work.

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

MySQL vs MySQLi when using PHP

What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.

Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.

PHP Redirect to another page after form submit

First give your input type submit a name, like this name='submitform'.

and then put this in your php file

if (isset($_POST['submitform']))
    {   
    ?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>      
    <?php
    }

Don't forget to change the url to yours.

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

I used ubuntu 12.04 I solved that problem by installing redis-server

redis-server installation for ubuntu 12.04

some configuration will new root permission Also listed manuals for other OS

Thanks

How to clear an EditText on click?

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});

How to check whether a string is a valid HTTP URL?

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Here url is the string you have to test.

Laravel Eloquent groupBy() AND also return count of each group

This is working for me:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

Set up DNS based URL forwarding in Amazon Route53

Update

While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.

  • Implementing an automated solution to generate such redirects is left as an exercise for the reader, but please pay tribute to Vivek's epic answer by publishing your solution ;)

Original Answer

Nettica must be running a custom redirection solution for this, here is the problem:

You could create a CNAME alias like aws.example.com for myaccount.signin.aws.amazon.com, however, DNS provides no official support for aliasing a subdirectory like console in this example.

  • It's a pity that AWS doesn't appear to simply do this by default when hitting https://myaccount.signin.aws.amazon.com/ (I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.

For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.

So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.

How to serve .html files with Spring

Background of the problem

First thing to understand is following: it is NOT spring which renders the jsp files. It is JspServlet (org.apache.jasper.servlet.JspServlet) which does it. This servlet comes with Tomcat (jasper compiler) not with spring. This JspServlet is aware how to compile jsp page and how to return it as html text to the client. The JspServlet in tomcat by default only handles requests matching two patterns: *.jsp and *.jspx.

Now when spring renders the view with InternalResourceView (or JstlView), three things really takes place:

  1. get all the model parameters from model (returned by your controller handler method i.e. "public ModelAndView doSomething() { return new ModelAndView("home") }")
  2. expose these model parameters as request attributes (so that it can be read by JspServlet)
  3. forward request to JspServlet. RequestDispatcher knows that each *.jsp request should be forwarded to JspServlet (because this is default tomcat's configuration)

When you simply change the view name to home.html tomcat will not know how to handle the request. This is because there is no servlet handling *.html requests.

Solution

How to solve this. There are three most obvious solutions:

  1. expose the html as a resource file
  2. instruct the JspServlet to also handle *.html requests
  3. write your own servlet (or pass to another existing servlet requests to *.html).

For complete code examples how to achieve this please reffer to my answer in another post: How to map requests to HTML file in Spring MVC?

Comparing two strings, ignoring case in C#

My general answer to this kind of question on "efficiency" is almost always, which ever version of the code is most readable, is the most efficient.

That being said, I think (val.ToLowerCase() == "astringvalue") is pretty understandable at a glance by most people.

The efficience I refer to is not necesseraly in the execution of the code but rather in the maintanance and generally readability of the code in question.

Delete rows containing specific strings in R

You can use stri_detect_fixed function from stringi package

stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1]  TRUE FALSE

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

How to suppress scientific notation when printing float values?

Another option, if you are using pandas and would like to suppress scientific notation for all floats, is to adjust the pandas options.

import pandas as pd
pd.options.display.float_format = '{:.2f}'.format

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Wrote this because I had requirements for up to a specific length (9). Pads the left with the @pattern ONLY when the input needs padding. Should always return length defined in @pattern.

declare @charInput as char(50) = 'input'

--always handle NULL :)
set @charInput = isnull(@charInput,'')

declare @actualLength as int = len(@charInput)

declare @pattern as char(50) = '123456789'
declare @prefLength as int = len(@pattern)

if @prefLength > @actualLength
    select Left(Left(@pattern, @prefLength-@actualLength) + @charInput, @prefLength)
else
    select @charInput

Returns 1234input

What does %s mean in a python format string?

Here is a good example in Python3.

  >>> a = input("What is your name?")
  What is your name?Peter

  >>> b = input("Where are you from?")
  Where are you from?DE

  >>> print("So you are %s of %s" % (a, b))
  So you are Peter of DE

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How do I capture all of my compiler's output to a file?

Assume you want to hilight warning and error from build ouput:

make |& grep -E "warning|error"

Convert list of dictionaries to a pandas DataFrame

How do I convert a list of dictionaries to a pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.


DataFrame(), DataFrame.from_records(), and .from_dict()

Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.

Consider a very contrived example.

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

This list consists of "records" with every keys present. This is the simplest case you could encounter.

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Word on Dictionary Orientations: orient='index'/'columns'

Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".

orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.

For example, data above is in the "columns" orient.

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Note: If you are using pd.DataFrame.from_records, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.

orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict.

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

This case is not considered in the OP, but is still useful to know.

Setting Custom Index

If you need a custom index on the resultant DataFrame, you can set it using the index=... argument.

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

This is not supported by pd.DataFrame.from_dict.

Dealing with Missing Keys/Columns

All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

Reading Subset of Columns

"What if I don't want to read in every single column"? You can easily specify this using the columns=... parameter.

For example, from the example dictionary of data2 above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

This is not supported by pd.DataFrame.from_dict with the default orient "columns".

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'

Reading Subset of Rows

Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2 above, you can use:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

The Panacea: json_normalize for Nested Data

A strong, robust alternative to the methods outlined above is the json_normalize function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
pd.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

Again, keep in mind that the data passed to json_normalize needs to be in the list-of-dictionaries (records) format.

As mentioned, json_normalize can also handle nested dictionaries. Here's an example taken from the documentation.

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]
pd.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

For more information on the meta and record_path arguments, check out the documentation.


Summarising

Here's a table of all the methods discussed above, along with supported features/functionality.

enter image description here

* Use orient='columns' and then transpose to get the same effect as orient='index'.

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

change the date format in laravel view page

There are 3 ways that you can do:

1) Using Laravel Model

$user = \App\User::find(1);

$newDateFormat = $user->created_at->format('d/m/Y');

dd($newDateFormat);

2) Using PHP strtotime

$user = \App\User::find(1);

$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));

dd($newDateFormat2);

3) Using Carbon

$user = \App\User::find(1);

$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');

dd($newDateFormat3);

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

Creating a Facebook share button with customized url, title and image

Crude, but it works on our system:

<div class="block-share spread-share p-t-md">
  <a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!" 
     target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span> 
      Share on Facebook
    </button>
  </a>

  <a href="https://www.facebook.com/FarmersForBritain" target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span>
      Like  on Facebook
    </button>
  </a>
</div>

Get current time as formatted string in Go?

As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:

msec := time.Now().UnixNano() / 1000000

Resource: https://gobyexample.com/epoch

How to fix: Error device not found with ADB.exe

This worked for me, my AVG anti virus was deleting my adb.exe file. If you have AVG try: 1) opening the program 2) go to options 3) go to the virus vault and click on it 4) find your adb program, click on it, and press RESTORE at the bottom This will move the file back to its original place. However, unless you turn off the AVG it will delete the file again.
After this android studio located the file. Good luck.

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

In PHP with PDO, how to check the final SQL parametrized query?

I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):

Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:

SET GLOBAL general_log = 'ON';

In a terminal, tail your log file. Mine was here:

>sudo tail -f /usr/local/mysql/data/myMacComputerName.log

You can search for your mysql files with this terminal command:

>ps auxww|grep [m]ysqld

I found that PDO escapes everything, so you can't write

$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();

Because it creates:

SELECT * FROM `example` WHERE `'userName'` = 'mick' ;

Which did not create an error, just an empty result. Instead I needed to use

$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";

to get

SELECT * FROM `example` WHERE `userName` = 'mick' ;

When you are done execute:

SET GLOBAL general_log = 'OFF';

or else your logs will get huge.

Create a button with rounded border

Use StadiumBorder shape

              OutlineButton(
                onPressed: () {},
                child: Text("Follow"),
                borderSide: BorderSide(color: Colors.blue),
                shape: StadiumBorder(),
              )

How to read barcodes with the camera on Android?

Here is sample code using camera api

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;

public class MainActivity extends AppCompatActivity {

TextView barcodeInfo;
SurfaceView cameraView;
CameraSource cameraSource;

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

    cameraView = (SurfaceView) findViewById(R.id.camera_view);
      barcodeInfo = (TextView) findViewById(R.id.txtContent);


    BarcodeDetector barcodeDetector =
            new BarcodeDetector.Builder(this)
                    .setBarcodeFormats(Barcode.CODE_128)//QR_CODE)
                    .build();

    cameraSource = new CameraSource
            .Builder(this, barcodeDetector)
            .setRequestedPreviewSize(640, 480)
            .build();

    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {

            try {
                cameraSource.start(cameraView.getHolder());
            } catch (IOException ie) {
                Log.e("CAMERA SOURCE", ie.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            cameraSource.stop();
        }
    });


    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {
        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {

            final SparseArray<Barcode> barcodes = detections.getDetectedItems();

            if (barcodes.size() != 0) {
                barcodeInfo.post(new Runnable() {    // Use the post method of the TextView
                    public void run() {
                        barcodeInfo.setText(    // Update the TextView
                                barcodes.valueAt(0).displayValue
                        );
                    }
                });
            }
        }
    });
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gateway.cameraapibarcode.MainActivity">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <SurfaceView
        android:layout_width="640px"
        android:layout_height="480px"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/camera_view"/>

    <TextView
        android:text=" code reader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtContent"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Process"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imgview"/>
</LinearLayout>
</RelativeLayout>

build.gradle(Module:app)

add compile 'com.google.android.gms:play-services:7.8.+' in dependencies

Convert seconds to HH-MM-SS with JavaScript?

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

Example:

_x000D_
_x000D_
let totalSeconds = 28565;_x000D_
let hours = Math.floor(totalSeconds / 3600);_x000D_
totalSeconds %= 3600;_x000D_
let minutes = Math.floor(totalSeconds / 60);_x000D_
let seconds = totalSeconds % 60;_x000D_
_x000D_
console.log("hours: " + hours);_x000D_
console.log("minutes: " + minutes);_x000D_
console.log("seconds: " + seconds);_x000D_
_x000D_
// If you want strings with leading zeroes:_x000D_
minutes = String(minutes).padStart(2, "0");_x000D_
hours = String(hours).padStart(2, "0");_x000D_
seconds = String(seconds).padStart(2, "0");_x000D_
console.log(hours + ":" + minutes + ":" + seconds);
_x000D_
_x000D_
_x000D_

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Try to make pairs of numbers from the set. The first + the last; the second + the one before last. It means n-1 + 1; n-2 + 2. The result is always n. And since you are adding two numbers together, there are only (n-1)/2 pairs that can be made from (n-1) numbers.

So it is like (N-1)/2 * N.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

May be this will make it more clear, and of course makes sense too.

@Entity
@Table(name = "users")

/**
 * 
 * @author Ram Srinvasan
 * Use class name in NamedQuery
 * Use table name in NamedNativeQuery
 */
@NamedQueries({ @NamedQuery(name = "findUserByName", query = "from User u where u.name= :name") })

@NamedNativeQueries({ @NamedNativeQuery(name = "findUserByNameNativeSQL", query = "select * from users u where u.name= :name", resultClass = User.class) })
public class User implements Principal {
...
}

How to display image from URL on Android

I've same issue. I test this code and works well. This code Get Image from URL and put in - "bmpImage"

URL url = new URL("http://your URL");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60000 /* milliseconds */);
            conn.setConnectTimeout(65000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            //Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();


            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);

            Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);

creating array without declaring the size - java

How about this

    private Object element[] = new Object[] {};

What are the differences between the BLOB and TEXT datatypes in MySQL?

Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

PHP $_POST not working?

try this
html code

  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
          <input type="text" name="firstname">
          <input type="submit" name="submit" value="Submit">
        </form>

php code:

if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;

}

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

How to get current domain name in ASP.NET

Here is a quick easy way to just get the name of the url.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

Proper way to handle multiple forms on one page in Django

Wanted to share my solution where Django Forms are not being used. I have multiple form elements on a single page and I want to use a single view to manage all the POST requests from all the forms.

What I've done is I have introduced an invisible input tag so that I can pass a parameter to the views to check which form has been submitted.

<form method="post" id="formOne">
    {% csrf_token %}
   <input type="hidden" name="form_type" value="formOne">

    .....
</form>

.....

<form method="post" id="formTwo">
    {% csrf_token %}
    <input type="hidden" name="form_type" value="formTwo">
   ....
</form>

views.py

def handlemultipleforms(request, template="handle/multiple_forms.html"):
    """
    Handle Multiple <form></form> elements
    """
    if request.method == 'POST':
        if request.POST.get("form_type") == 'formOne':
            #Handle Elements from first Form
        elif request.POST.get("form_type") == 'formTwo':
            #Handle Elements from second Form

WCF change endpoint address at runtime

We store our URLs in a database and load them at runtime.

public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
    public TChannel Create(string url)
    {
        this.Endpoint.Address = new EndpointAddress(new Uri(url));
        return this.Channel;
    }
}

Implementation

var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);

How do you append to a file?

if you want to append to a file

with open("test.txt", "a") as myfile:
    myfile.write("append me")

We declared the variable myfile to open a file named test.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file

here is file mode options

Mode    Description

'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing. 
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode. 
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

Eclipse not recognizing JVM 1.8

JRE is a Run-Time Environment for running Java stuffs on your machine. What Eclipse needs is JDK as a Development Kit.

Install the latest JDK (and not JRE) from http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html and you should be good on Mac!

Connect Android Studio with SVN

  1. Run Android Studio.
  2. From the menu bar, select Android Studio
  3. Under IDE Settings, click Plugins and then select Search Subversion Integration
  4. Check SubVersion.
  5. Restart Android Studio.

How to print struct variables in console?

Another way is, create a func called toString that takes struct, format the fields as you wish.

import (
    "fmt"
)

type T struct {
    x, y string
}

func (r T) toString() string {
    return "Formate as u need :" + r.x + r.y
}

func main() {
    r1 := T{"csa", "ac"}
    fmt.Println("toStringed : ", r1.toString())
}

Localhost : 404 not found

you need to stop that service running on this port .check service running on specific port by "netstat -ano".then in window search type services.exe and search that process and stop that process .to change port of that process check this http://seankilleen.com/2012/11/how-to-stop-sql-server-reporting-services-from-using-port-80-on-your-server-field-notes/

TortoiseSVN icons overlay not showing after updating to Windows 10

The following steps worked for me:

  1. TortoiseSVN -> Settings -> IconOverlays -> Icon Set
  2. Choose "Win10" icon set
  3. Restart computer.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

This answer simply applies the type=date attribute to the HTML input element and relies on the browser to supply a date picker. Note that even in 2017, not all browsers provide their own date picker, so you may want to provide a fall back.

All you have to do is add attributes to the property in the view model. Example for variable Ldate:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Public DateTime Ldate {get;set;}

Assuming you're using MVC 5 and Visual Studio 2013.

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:


If t is a Tensor object, t.eval() is shorthand for sess.run(t) (where sess is the current default session. The two following snippets of code are equivalent:

sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)

c = tf.constant(5.0)
with tf.Session():
  print c.eval()

In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run().

I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

What is the maximum characters for the NVARCHAR(MAX)?

The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage.

Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.

Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX) column.

Is that enough space for your needs? :-)

Python `if x is not None` or `if not x is None`?

The answer is simpler than people are making it.

There's no technical advantage either way, and "x is not y" is what everybody else uses, which makes it the clear winner. It doesn't matter that it "looks more like English" or not; everyone uses it, which means every user of Python--even Chinese users, whose language Python looks nothing like--will understand it at a glance, where the slightly less common syntax will take a couple extra brain cycles to parse.

Don't be different just for the sake of being different, at least in this field.

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

powershell mouse move does not prevent idle mode

Try this: (source: http://just-another-blog.net/programming/powershell-and-the-net-framework/)

Add-Type -AssemblyName System.Windows.Forms 

$position = [System.Windows.Forms.Cursor]::Position  
$position.X++  
[System.Windows.Forms.Cursor]::Position = $position 

    while(1) {  
    $position = [System.Windows.Forms.Cursor]::Position  
    $position.X++  
    [System.Windows.Forms.Cursor]::Position = $position  

    $time = Get-Date;  
    $shorterTimeString = $time.ToString("HH:mm:ss");  

    Write-Host $shorterTimeString "Mouse pointer has been moved 1 pixel to the right"  
    #Set your duration between each mouse move
    Start-Sleep -Seconds 150  
    }  

m2eclipse not finding maven dependencies, artifacts not found

I had problems with using m2eclipse (i.e. it did not appear to be installed at all) but I develop a project using IAM - maven plugin for eclipse supported by Eclipse Foundation (or hosted or something like that).

I had sometimes problems as sometimes some strange error appeared for project (it couldn't move something) but simple command (run from eclipse as task or from console) + refresh (F5) solved all problems:

mvn clean

However please note that I created project in eclipse. However I modified pom.xml by hand.

How to add colored border on cardview?

I would like to improve the solution proposed by Amit. I'm utilizing the given resources without adding additional shapes or Views. I'm giving CardView a background color and then nested layout, white color to overprint yet with some leftMargin...

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardElevation="2dp"
    card_view:cardBackgroundColor="@color/some_color"
    card_view:cardCornerRadius="5dp">


    <!-- The left margin decides the width of the border -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:layout_marginLeft="5dp"
        android:background="#fff"
        android:orientation="vertical">

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Headline"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Title" />

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Body1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Content here" />

    </LinearLayout>

</android.support.v7.widget.CardView>

How do I copy the contents of a String to the clipboard in C#?

Use try-catch, even if it has an error it will still copy.

Try
   Clipboard.SetText("copy me to clipboard")
Catch ex As Exception

End Try

If you use a message box to capture the exception, it will show you error, but the value is still copied to clipboard.

Call a Class From another class

Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

CSS disable hover effect

Do this Html and the CSS is in the head tag. Just make a new class and in the css use this code snippet:

pointer-events:none;

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .buttonDisabled {
        pointer-events: none;
      }
    </style>
  </head>
  <body>
    <button class="buttonDisabled">Not-a-button</button>
  </body>
</html>

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Simply remove "DEFINER=your user name@localhost" and run the SQL from phpmyadminwill works fine.

Convert a positive number to negative in C#

Converting a number from positive to negative, or negative to positive:

public static decimal Reverse(this decimal source)
{
     return source * decimal.MinusOne;
}

How to add one column into existing SQL Table

Its work perfectly

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;

But if you want more precise in table then you can try AFTER.

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;

It will add LastUpdate column after specified column name (column_name).

How should we manage jdk8 stream for null values

Although the answers are 100% correct, a small suggestion to improve null case handling of the list itself with Optional:

 List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList) will allow you to handle nicely the case when listOfStuff is null and return an emptyList instead of failing with NullPointerException.

How to extend available properties of User.Identity

For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):

@using Microsoft.AspNetCore.Identity

@using <namespaceWhereYouHaveYourAppUser>

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

@if (SignInManager.IsSignedIn(User)) {
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" 
          method="post" id="logoutForm" 
          class="form-inline my-2 my-lg-0">

        <ul class="nav navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
                    Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
                    <!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
                </a>
            </li>
            <li class="nav-item">
                <button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>
            </li>
        </ul>

    </form>
} else {
    <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>
    </ul>
}

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

In my case it was because I had another folder that contained xampp and all it's files (htdocs, php e.t.c). Like I installed Xampp twice in different directories and for some reason the configurations of the other one was affecting my current xampp directory and so I had to change the memory size in the php.ini file of the other directory too.

Add new item in existing array in c#.net

Very old question, but still wanted to add this.

If you're looking for a one-liner, you can use the code below. It combines the list constructor that accepts an enumerable and the "new" (since question raised) initializer syntax.

myArray = new List<string>(myArray) { "add this" }.ToArray();

How can I set the form action through JavaScript?

Do as Rabbott says, or if you refuse jQuery:

<script type="text/javascript">
function get_action() { // inside script tags
  return form_action;
}
</script>

<form action="" onsubmit="this.action=get_action();">
...
</form>

Mongoose: Get full list of users

This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);

    server.get('/usersList', (req, res) => 
        User.find({}, (err, users) => 
            res.send(users.reduce((userMap, item) => {
                userMap[item.id] = item
                return userMap
            }, {}));
        );
    );

cheers!

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

I think you have 2 separate problems, 1. with restoring and 2. with creating

For 1. you could try checking to see if the file was transferred properly (one easy way would be to check the md5 of the file on the server and again on the local environment to see if they match).

Date format in the json output using spring boot

If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.dateFormat(new ISO8601DateFormat());        
        }           
    };
}

Convert base64 string to image

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;


def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

how to use math.pi in java

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^

How to print GETDATE() in SQL Server with milliseconds in time?

Try Following

DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Loop code for each file in a directory

Looks for the function glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

Eclipse returns error message "Java was started but returned exit code = 1"

I had the same issue which was caused due to crash shutdown of my windows 10. Earlier in the path I had Oracle path ie the path inserted by Oracle at the time of installation of JDK. I removed it and changed the path to the JDK location. This solved the problem.

How do I check to see if a value is an integer in MySQL?

Suppose we have column with alphanumeric field having entries like

a41q
1458
xwe8
1475
asde
9582
.
.
.
.
.
qe84

and you want highest numeric value from this db column (in this case it is 9582) then this query will help you

SELECT Max(column_name) from table_name where column_name REGEXP '^[0-9]+$'

Android Fragment onClick button Method

Your activity must have

public void insertIntoDb(View v) {
...
} 

not Fragment .

If you don't want the above in activity. initialize button in fragment and set listener to the same.

<Button
    android:id="@+id/btn_conferma" // + missing

Then

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

   View view = inflater.inflate(R.layout.fragment_rssitem_detail,
    container, false);
   Button button = (Button) view.findViewById(R.id.btn_conferma);
   button.setOnClickListener(new OnClickListener()
   {
             @Override
             public void onClick(View v)
             {
                // do something
             } 
   }); 
   return view;
}

ERROR 1064 (42000): You have an error in your SQL syntax;

Try this:

Use back-ticks for NAME

CREATE TABLE `teachers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `addr` varchar(255) NOT NULL,
  `phone` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

placeholder for select tag

EDIT: This did/does work at the time I wrote it, but as Blexen pointed out, it's not in the spec.

Add an option like so:

<option default>Select Your Beverage</option>

The correct way:

<option selected="selected">Select Your Beverage</option>

How can I change the Java Runtime Version on Windows (7)?

If you are using windows 10 or windows server 2012, the steps to change the java runtime version is this:

  1. Open regedit using 'Run'
  2. Navigate to HKEY_LOCAL_MACHINE -> SOFTWARE -> JavaSoft -> Java Runtime Environment
  3. Here you will see all the versions of java you installed on your PC. For me I have several versions of java 1.8 installed, so the folder displayed here are 1.8, 1.8.0_162 and 1.8.0_171
  4. Click the '1.8' folder, then double click the JavaHome and RuntimeLib keys, Change the version number inside to whichever Java version you want your PC to run on. For example, if the Value data of the key is 'C:\Program Files\Java\jre1.8.0_171', you can change this to 'C:\Program Files\Java\jre1.8.0_162'.
  5. You can then verify the version change by typing 'java -version' on the command line.

How to write a caption under an image?

CSS is your friend; there is no need for the center tag (not to mention it is quite depreciated) nor the excessive non-breaking spaces. Here is a simple example:

CSS

.images {
    text-align:center;
}
.images img {
    width:100px;
    height:100px;
}
.images div {
    width:100px;
    text-align:center;
}
.images div span {
    display:block;
}
.margin_right {
    margin-right:50px;
}
.float {
    float:left;
}
.clear {
    clear:both;
    height:0;
    width:0;
}

HTML

<div class="images">
    <div class="float margin_right">
        <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px" /></a>
        <span>This is some text</span>
    </div>
    <div class="float">
        <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px" /></a>
        <span>And some more text</span>
    </div>
    <span class="clear"></span>
</div>

Error:java: javacTask: source release 8 requires target release 1.8

This looks like the kind of error that Maven generates when you don't have the compiler plugin configured correctly. Here's an example of a Java 8 compiler config.

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<!-- ... -->

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

<!-- ... -->

</project>

MySQL export into outfile : CSV escaping chars

What happens if you try the following?

Instead of your double REPLACE statement, try:

REPLACE(IFNULL(ts.description, ''),'\r\n', '\n')

Also, I think it should be LINES TERMINATED BY '\r\n' instead of just '\n'

Are there such things as variables within an Excel formula?

Not related to variables, your example will also be solved by MOD:

=Mod(VLOOKUP(A1, B:B, 1, 0);10)

JavaScript for detecting browser language preference

_x000D_
_x000D_
let lang = window.navigator.languages ? window.navigator.languages[0] : null;_x000D_
    lang = lang || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage;_x000D_
_x000D_
let shortLang = lang;_x000D_
if (shortLang.indexOf('-') !== -1)_x000D_
    shortLang = shortLang.split('-')[0];_x000D_
_x000D_
if (shortLang.indexOf('_') !== -1)_x000D_
    shortLang = shortLang.split('_')[0];_x000D_
_x000D_
console.log(lang, shortLang);
_x000D_
_x000D_
_x000D_

I only needed the primary component for my needs, but you can easily just use the full string. Works with latest Chrome, Firefox, Safari and IE10+.

How do I install the ext-curl extension with PHP 7?

If you are using PHP7.1 ( try php -version to find your PHP version)

sudo apt-get install php7.1-curl

then restart apache

sudo service apache2 restart

What is function overloading and overriding in php?

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.

In PHP, you can only overload methods using the magic method __call.

An example of overriding:

<?php

class Foo {
   function myFoo() {
      return "Foo";
   }
}

class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}

$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"
?>

How to remove backslash on json_encode() function?

As HungryDB said the easier way for do that is:

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

Have a look at your php version because this parameter has been added in version 5.4.0

json_encode documentation

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;

@end


@implementation YourObject


-(id) copyWithZone: (NSZone *) zone
{
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre: self.name];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;
}

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

Lock, mutex, semaphore... what's the difference?

Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have acquire()/release() operations, both cause zero or more threads to become blocked/suspected... Really, the crucial difference lies solely on how they lock and unlock.

  • A lock (or mutex) has two states (0 or 1). It can be either unlocked or locked. They're often used to ensure only one thread enters a critical section at a time.
  • A semaphore has many states (0, 1, 2, ...). It can be locked (state 0) or unlocked (states 1, 2, 3, ...). One or more semaphores are often used together to ensure that only one thread enters a critical section precisely when the number of units of some resource has/hasn't reached a particular value (either via counting down to that value or counting up to that value).

For both locks/semaphores, trying to call acquire() while the primitive is in state 0 causes the invoking thread to be suspended. For locks - attempts to acquire the lock is in state 1 are successful. For semaphores - attempts to acquire the lock in states {1, 2, 3, ...} are successful.

For locks in state state 0, if same thread that had previously called acquire(), now calls release, then the release is successful. If a different thread tried this -- it is down to the implementation/library as to what happens (usually the attempt ignored or an error is thrown). For semaphores in state 0, any thread can call release and it will be successful (regardless of which thread previous used acquire to put the semaphore in state 0).

From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore).


What causes a lot of confusion is that, in practice they are many variations of this high-level definition.

Important variations to consider:

  • What should the acquire()/release() be called? -- [Varies massively]
  • Does your lock/semaphore use a "queue" or a "set" to remember the threads waiting?
  • Can your lock/semaphore be shared with threads of other processes?
  • Is your lock "reentrant"? -- [Usually yes].
  • Is your lock "blocking/non-blocking"? -- [Normally non-blocking are used as blocking locks (aka spin-locks) cause busy waiting].
  • How do you ensure the operations are "atomic"?

These depends on your book / lecturer / language / library / environment.
Here's a quick tour noting how some languages answer these details.


C, C++ (pthreads)

  • A mutex is implemented via pthread_mutex_t. By default, they can't be shared with any other processes (PTHREAD_PROCESS_PRIVATE), however mutex's have an attribute called pshared. When set, so the mutex is shared between processes (PTHREAD_PROCESS_SHARED).
  • A lock is the same thing as a mutex.
  • A semaphore is implemented via sem_t. Similar to mutexes, semaphores can be shared between threasds of many processes or kept private to the threads of one single process. This depends on the pshared argument provided to sem_init.

python (threading.py)

  • A lock (threading.RLock) is mostly the same as C/C++ pthread_mutex_ts. Both are both reentrant. This means they may only be unlocked by the same thread that locked it. It is the case that sem_t semaphores, threading.Semaphore semaphores and theading.Lock locks are not reentrant -- for it is the case any thread can perform unlock the lock / down the semaphore.
  • A mutex is the same as a lock (the term is not used often in python).
  • A semaphore (threading.Semaphore) is mostly the same as sem_t. Although with sem_t, a queue of thread ids is used to remember the order in which threads became blocked when attempting to lock it while it is locked. When a thread unlocks a semaphore, the first thread in the queue (if there is one) is chosen to be the new owner. The thread identifier is taken off the queue and the semaphore becomes locked again. However, with threading.Semaphore, a set is used instead of a queue, so the order in which threads became blocked is not stored -- any thread in the set may be chosen to be the next owner.

Java (java.util.concurrent)

  • A lock (java.util.concurrent.ReentrantLock) is mostly the same as C/C++ pthread_mutex_t's, and Python's threading.RLock in that it also implements a reentrant lock. Sharing locks between processes is harder in Java because of the JVM acting as an intermediary. If a thread tries to unlock a lock it doesn't own, an IllegalMonitorStateException is thrown.
  • A mutex is the same as a lock (the term is not used often in Java).
  • A semaphore (java.util.concurrent.Semaphore) is mostly the same as sem_t and threading.Semaphore. The constructor for Java semaphores accept a fairness boolean parameter that control whether to use a set (false) or a queue (true) for storing the waiting threads.

In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

A quick workaround for this is to use numpy.core.defchararray. I also faced the same warning message and was able to resolve it using above module.

import numpy.core.defchararray as npd
resultdataset = npd.equal(dataset1, dataset2)

How to change the Content of a <textarea> with JavaScript

If you can use jQuery, and I highly recommend you do, you would simply do

$('#myTextArea').val('');

Otherwise, it is browser dependent. Assuming you have

var myTextArea = document.getElementById('myTextArea');

In most browsers you do

myTextArea.innerHTML = '';

But in Firefox, you do

myTextArea.innerText = '';

Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)

Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.

Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.

MySQL - Operand should contain 1 column(s)

In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:

SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;

And has to be:

SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;

Sounds silly, but it was causing this error and it took some time to figure it out.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

Splitting string into multiple rows in Oracle

REGEXP_COUNT wasn't added until Oracle 11i. Here's an Oracle 10g solution, adopted from Art's solution.

SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
  FROM dual
CONNECT BY LEVEL <=
  LENGTH('Err1, Err2, Err3')
    - LENGTH(REPLACE('Err1, Err2, Err3', ',', ''))
    + 1;

Best tool for inspecting PDF files?

There is also another option. Adobe Acrobat Pro is also able to display the internal tree structure of the PDF.

  1. Open Preflight
  2. Go to Options (right upper corner)
  3. Internal PDF Structure

On top Adobe Acrobat Pro can also display the internal structure of the Document Fonts in the PDF most of other "PDF tree structure viewer" don't have this otion

enter image description here

jQuery’s .bind() vs. .on()

The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"

The .delegate is superior to .on because of the argument's order:

$(elem).delegate( ".selector", {
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
});

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:

$(elem).on({
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

Failed to run sdkmanager --list with Java 9

As we read in the previous comments this error is occurring because the current SDK version is incompatible with the newest Java versions: 9 and 10.

So, to solve it, you can downgrade your java version to Java 8, or as a workaround, you can export the following option on your terminal:

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

If this does not work try to exports the java.xml.bind instead.

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

This will solve this error for the sdkmanager

And to make it saved permanently you can export the JAVA_OPTS in your profile file on Linux (.zshrc, .bashrc and etc.) or add it as an environment variable permanently on Windows.


ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.

Ref: JDK 11: End of the road for Java EE modules

Select tableview row programmatically

Like Jaanus told:

Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.

So you just have to call the delegate method yourself.

For example:

Swift 3 version:

let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

ObjectiveC version:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath 
                            animated:YES 
                      scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

Swift 2.3 version:

 let indexPath = NSIndexPath(forRow: 0, inSection: 0);
 self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
 self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Another solution to avoid inserting html into data-title is to create independant div with tooltip html content, and refer to this div when creating your tooltip :

<!-- Tooltip link -->
<p><span class="tip" data-tip="my-tip">Hello world</span></p>

<!-- Tooltip content -->
<div id="my-tip" class="tip-content hidden">
    <h2>Tip title</h2>
    <p>This is my tip content</p>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        // Tooltips
        $('.tip').each(function () {
            $(this).tooltip(
            {
                html: true,
                title: $('#' + $(this).data('tip')).html()
            });
        });
    });
</script>

This way you can create complex readable html content, and activate as many tooltips as you want.

live demo here on codepen

INSERT INTO TABLE from comma separated varchar-list

Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin       
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return       
end  

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

CSS How to set div height 100% minus nPx

If you need to support IE6, use JavaScript so manage the size of the wrapper div (set the position of the element in pixels after reading the window size). If you don't want to use JavaScript, then this can't be done. There are workarounds but expect a week or two to make it work in every case and in every browser.

For other modern browsers, use this css:

position: absolute;
top: 60px;
bottom: 0px;

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

The ^ negates a character class:

SELECT * FROM mytable WHERE REGEXP_LIKE(column_1, '[^A-Za-z]')

git with IntelliJ IDEA: Could not read from remote repository

in pyCharm,

file|
    v-->settings|
                v-->Version Control|
                                   v-->Git

Here change SSH executable from Built-in into Native

then press apply and close

New self vs. new static

In addition to others' answers :

static:: will be computed using runtime information.

That means you can't use static:: in a class property because properties values :

Must be able to be evaluated at compile time and must not depend on run-time information.

class Foo {
    public $name = static::class;

}

$Foo = new Foo;
echo $Foo->name; // Fatal error

Using self::

class Foo {
    public $name = self::class;

}
$Foo = new Foo;
echo $Foo->name; // Foo

Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

Using GCC to produce readable assembly?

Did you try gcc -S -fverbose-asm -O source.c then look into the generated source.s assembler file ?

The generated assembler code goes into source.s (you could override that with -o assembler-filename ); the -fverbose-asm option asks the compiler to emit some assembler comments "explaining" the generated assembler code. The -O option asks the compiler to optimize a bit (it could optimize more with -O2 or -O3).

If you want to understand what gcc is doing try passing -fdump-tree-all but be cautious: you'll get hundreds of dump files.

BTW, GCC is extensible thru plugins or with MELT (a high level domain specific language to extend GCC; which I abandoned in 2017)

How can I properly handle 404 in ASP.NET MVC?

I went through most of the solutions posted on this thread. While this question might be old, it is still very applicable to new projects even now, so I spent quite a lot of time reading up on the answers presented here as well as else where.

As @Marco pointed out the different cases under which a 404 can happen, I checked the solution I compiled together against that list. In addition to his list of requirements, I also added one more.

  • The solution should be able to handle MVC as well as AJAX/WebAPI calls in the most appropriate manner. (i.e. if 404 happens in MVC, it should show the Not Found page and if 404 happens in WebAPI, it should not hijack the XML/JSON response so that the consuming Javascript can parse it easily).

This solution is 2 fold:

First part of it comes from @Guillaume at https://stackoverflow.com/a/27354140/2310818. Their solution takes care of any 404 that were caused due to invalid route, invalid controller and invalid action.

The idea is to create a WebForm and then make it call the NotFound action of your MVC Errors Controller. It does all of this without any redirect so you will not see a single 302 in Fiddler. The original URL is also preserved, which makes this solution fantastic!


Second part of it comes from @Germán at https://stackoverflow.com/a/5536676/2310818. Their solution takes care of any 404 returned by your actions in the form of HttpNotFoundResult() or throw new HttpException()!

The idea is to have a filter look at the response as well as the exception thrown by your MVC controllers and to call the appropriate action in your Errors Controller. Again this solution works without any redirect and the original url is preserved!


As you can see, both of these solutions together offer a very robust error handling mechanism and they achieve all the requirements listed by @Marco as well as my requirements. If you would like to see a working sample or a demo of this solution, please leave in the comments and I would be happy to put it together.

CakePHP select default value in SELECT input

If you are using cakephp version 3.0 and above, then you can add default value in select input using empty attribute as given in below example.

echo $this->Form->input('category_id', ['options'=>$categories,'empty'=>'Choose']);

In Bootstrap 3,How to change the distance between rows in vertical?

If it was me I would introduce new CSS class and use along with unmodified bootstrap row class.

HTML

<div class="row extra-bottom-padding" id="a">
   <img>...</img>
<div>
<div class="row" id="b">
   <button>..</button>
<div>

CSS

.row.extra-bottom-padding{
   margin-bottom: 20px;
}

Find IP address of directly connected device

Your Best Approach is to install Wireshark, reboot the device wait for the TCP/UDP stream , broadcasts will announce the IP address for both Ethernet ports This is especially useful when the device connected does not have DHCP Client enabled, then you can go from there.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

How to center a (background) image within a div?

Use background-position:

background-position: 50% 50%;

Get Element value with minidom with Python

It's a tree, and there may be nested elements. Try:

def innerText(self, sep=''):
    t = ""
    for curNode in self.childNodes:
        if (curNode.nodeType == Node.TEXT_NODE):
            t += sep + curNode.nodeValue
        elif (curNode.nodeType == Node.ELEMENT_NODE):
            t += sep + curNode.innerText(sep=sep)
    return t

How to show google.com in an iframe?

Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

How can one display images side by side in a GitHub README.md?

This is the best way to make add images/screenshots of your app and keep your repository look clean.

Create a screenshot folder in your repository and add the images you want to display.

Now go to README.md and add this HTML code to form a table.

#### Flutter App Screenshots

<table>
  <tr>
    <td>First Screen Page</td>
     <td>Holiday Mention</td>
     <td>Present day in purple and selected day in pink</td>
  </tr>
  <tr>
    <td><img src="screenshots/Screenshot_1582745092.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745125.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745139.png" width=270 height=480></td>
  </tr>
 </table>

In the <td><img src="(COPY IMAGE PATH HERE)" width=270 height=480></td>

** To get the image path --> Go to the screenshot folder and open the image and on the right most side, you will find Copy path button.

You will get a table like this in your repository--->

enter image description here

split string only on first instance - java

As many other answers suggest the limit approach, This can be another way

You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output

String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));

How can I add or update a query string parameter?

Use this function to add, remove and modify query string parameter from URL based on jquery

/**
@param String url
@param object param {key: value} query parameter
*/
function modifyURLQuery(url, param){
    var value = {};

    var query = String(url).split('?');

    if (query[1]) {
        var part = query[1].split('&');

        for (i = 0; i < part.length; i++) {
            var data = part[i].split('=');

            if (data[0] && data[1]) {
                value[data[0]] = data[1];
            }
        }
    }

    value = $.extend(value, param);

    // Remove empty value
    for (i in value){
        if(!value[i]){
            delete value[i];
        }
    }

    // Return url with modified parameter
    if(value){
        return query[0] + '?' + $.param(value);
    } else {
        return query[0];
    }
}

Add new and modify existing parameter to url

var new_url = modifyURLQuery("http://google.com?foo=34", {foo: 50, bar: 45});
// Result: http://google.com?foo=50&bar=45

Remove existing

var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
// Result: http://google.com?foo=50

Find in Files: Search all code in Team Foundation Server

We have set up a solution for Team Foundation Server Source Control (not SourceSafe as you mention) similar to what Grant suggests; scheduled TF Get, Search Server Express. However the IFilter used for C# files (text) was not giving the results we wanted, so we convert source files to .htm files. We can now add additional meta-data to the files such as:

  • Author (we define it as the person that last checked in the file)
  • Color coding (on our todo-list)
  • Number of changes indicating potential design problems (on our todo-list)
  • Integrate with the VSTS IDE like Koders SmartSearch feature
  • etc.

We would however prefer a protocolhandler for TFS Source Control, and a dedicated source code IFilter for a much more targeted solution.

jQuery Form Validation before Ajax submit

I think that i first validate form and if validation will pass, than i would make ajax post. Dont forget to add "return false" at the end of the script.

Service will not start: error 1067: the process terminated unexpectedly

This is a problem related permission. Make sure that the current user has access to the folder which contains installation files.

How to change folder with git bash?

Simply type cd then copy and paste the file path.

Example of changing directory:

example of changing directory

Repeat string to certain length

def extended_string (word, length) :

    extra_long_word = word * (length//len(word) + 1)
    required_string = extra_long_word[:length]
    return required_string

print(extended_string("abc", 7))

Pycharm/Python OpenCV and CV2 install error

On Windows : !pip install opencv-python

XML Schema (XSD) validation tool?

There's a plugin for Notepad++ called XML Tools that offers XML verification and validation against an XSD.

You can see how to use it here.

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Determine device (iPhone, iPod Touch) with iOS

You can use the UIDevice class like this:

NSString *deviceType = [UIDevice currentDevice].model;

if([deviceType isEqualToString:@"iPhone"])
    // it's an iPhone

Date object to Calendar [Java]

Here is a full example on how to transform your date in different types:

Date date = Calendar.getInstance().getTime();

    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with day name in a short format
    formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with a short day and month name
    formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Formatting date with full day and month name and show time up to
    // milliseconds with AM/PM
    formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    today = formatter.format(date);
    System.out.println("Today : " + today);

Is it still valid to use IE=edge,chrome=1?

<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>

worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>, or it won't work!

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

Check input value length

<input type='text' minlength=3 /><br />

if browser supports html5,

it will automatical be validate attributes(minlength) in tag

but Safari(iOS) doesn't working

Strip HTML from strings in Python

You can write your own function:

def StripTags(text):
     finished = 0
     while not finished:
         finished = 1
         start = text.find("<")
         if start >= 0:
             stop = text[start:].find(">")
             if stop >= 0:
                 text = text[:start] + text[start+stop+1:]
                 finished = 0
     return text