Programs & Examples On #Weblogic11g

The 11.x (July 2009) release of WebLogic Server, a Java EE application server suite from Oracle. It's part of their Oracle Fusion Middleware product.

How to lookup JNDI resources on WebLogic?

I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:

      Context ctx = new InitialContext();
      DataSource dataSource;

      try {
        dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
        response.getWriter().println("A " +dataSource);
      }catch(Exception e) {
        response.getWriter().println("A " + e.getMessage() + e.getCause());
      }

      //or

      try {
        dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
        response.getWriter().println("F "+dataSource);
      }catch(Exception e) {
        response.getWriter().println("F " + e.getMessage() + e.getCause());
      }

      //use your datasource
      conn = datasource.getConnection();

That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.

how to change listen port from default 7001 to something different?

That file has a listen-port element - that should be what you need to change, although it is currently set to 8080, not 7001.

Difference between View and table in sql

Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.

View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are

  • We can combine columns/rows from multiple table or another view and have a consolidated view.
  • Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view
  • It acts as abstract layer to downstream systems, so any change in schema is not exposed and hence the downstream systems doesn't get affected.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

You're mixing up HTML with XHTML.

Usually a <!DOCTYPE> declaration is used to distinguish between versions of HTMLish languages (in this case, HTML or XHTML).

Different markup languages will behave differently. My favorite example is height:100%. Look at the following in a browser:

XHTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

... and compare it to the following: (note the conspicuous lack of a <!DOCTYPE> declaration)

HTML (quirks mode)

<html>
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

You'll notice that the height of the table is drastically different, and the only difference between the 2 documents is the type of markup!

That's nice... now, what does <html xmlns="http://www.w3.org/1999/xhtml"> do?

That doesn't answer your question though. Technically, the xmlns attribute is used by the root element of an XHTML document: (according to Wikipedia)

The root element of an XHTML document must be html, and must contain an xmlns attribute to associate it with the XHTML namespace.

You see, it's important to understand that XHTML isn't HTML but XML - a very different creature. (ok, a kind of different creature) The xmlns attribute is just one of those things the document needs to be valid XML. Why? Because someone working on the standard said so ;) (you can read more about XML namespaces on Wikipedia but I'm omitting that info 'cause it's not actually relevant to your question!)

But then why is <html xmlns="http://www.w3.org/1999/xhtml"> fixing the CSS?

If structuring your document like so... (as you suggest in your comment)

<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
[...]

... is fixing your document, it leads me to believe that you don't know that much about CSS and HTML (no offense!) and that the truth is that without <html xmlns="http://www.w3.org/1999/xhtml"> it's behaving normally and with <html xmlns="http://www.w3.org/1999/xhtml"> it's not - and you just think it is, because you're used to writing invalid HTML and thus working in quirks mode.

The above example I provided is an example of that same problem; most people think height:100% should result in the height of the <table> being the whole window, and that the DOCTYPE is actually breaking their CSS... but that's not really the case; rather, they just don't understand that they need to add a html, body { height:100%; } CSS rule to achieve their desired effect.

How do I get the current GPS location programmatically in Android?

I have published a small library that can make it easy to get location data in Android, it even takes care of Android M runtime permissions.

You might check it out here: https://github.com/julioromano/RxLocation and use it or its source code as examples for your implementation.

Runtime vs. Compile time

Basically if your compiler can work out what you mean or what a value is "at compile time" it can hardcode this into the runtime code. Obviously if your runtime code has to do a calculation every time it will run slower, so if you can determine something at compile time it is much better.

Eg.

Constant folding:

If I write:

int i = 2;
i += MY_CONSTANT;

The compiler can perform this calulation at compile time because it knows what 2 is, and what MY_CONSTANT is. As such it saves itself from performing a calculation every single execution.

Insert php variable in a href

Try using printf function or the concatination operator

http://php.net/manual/en/function.printf.php

How do you do a limit query in JPQL or HQL?

The setFirstResult and setMaxResults Query methods

For a JPA and Hibernate Query, the setFirstResult method is the equivalent of OFFSET, and the setMaxResults method is the equivalent of LIMIT:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "order by p.createdOn ")
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

The LimitHandler abstraction

The Hibernate LimitHandler defines the database-specific pagination logic, and as illustrated by the following diagram, Hibernate supports many database-specific pagination options:

LimitHandler implementations

Now, depending on the underlying relational database system you are using, the above JPQL query will use the proper pagination syntax.

MySQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?, ?

PostgreSQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

SQL Server

SELECT p.id AS id1_0_,
       p.created_on AS created_on2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
OFFSET ? ROWS 
FETCH NEXT ? ROWS ONLY

Oracle

SELECT *
FROM (
    SELECT 
        row_.*, rownum rownum_
    FROM (
        SELECT 
            p.id AS id1_0_,
            p.created_on AS created_on2_0_,
            p.title AS title3_0_
        FROM post p
        ORDER BY p.created_on
    ) row_
    WHERE rownum <= ?
)
WHERE rownum_ > ?

The advantage of using setFirstResult and setMaxResults is that Hibernate can generate the database-specific pagination syntax for any supported relational databases.

And, you are not limited to JPQL queries only. You can use the setFirstResult and setMaxResults method seven for native SQL queries.

Native SQL queries

You don't have to hardcode the database-specific pagination when using native SQL queries. Hibernate can add that to your queries.

So, if you're executing this SQL query on PostgreSQL:

List<Tuple> posts = entityManager
.createNativeQuery(
    "SELECT " +
    "   p.id AS id, " +
    "   p.title AS title " +
    "from post p " +
    "ORDER BY p.created_on", Tuple.class)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

Hibernate will transform it as follows:

SELECT p.id AS id,
       p.title AS title
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

Cool, right?

Beyond SQL-based pagination

Pagination is good when you can index the filtering and sorting criteria. If your pagination requirements imply dynamic filtering, it's a much better approach to use an inverted-index solution, like ElasticSearch.

How can I control the width of a label tag?

label {
  width:200px;
  display: inline-block;
}

OR 

label {
  width:200px;
  display: inline-flex;
}

OR 

label {
  width:200px;
  display: inline-table;
}

How to install mysql-connector via pip

execute following command from your terminal

sudo pip install --allow-external mysql-connector-python mysql-connector-python

C# Help reading foreign characters using StreamReader

for Arabic, I used Encoding.GetEncoding(1256). it is working good.

Which Python memory profiler is recommended?

Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.

Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.

Questions every good Java/Java EE Developer should be able to answer?

Advantages and disadvantages of thread-safe classes and explicitly synchronized code and examples of good applications of both. It is often not correct to trust on thread-safe classes as guarantees for data consistency in multi-threaded applications.

Numpy matrix to array

This will convert the matrix into array

A = np.ravel(M).T

Work on a remote project with Eclipse via SSH

The very simplest way would be to run Eclipse CDT on the Linux Box and use either X11-Forwarding or remote desktop software such as VNC.

This, of course, is only possible when you Eclipse is present on the Linux box and your network connection to the box is sufficiently fast.

The advantage is that, due to everything being local, you won't have synchronization issues, and you don't get any awkward cross-platform issues.

If you have no eclipse on the box, you could thinking of sharing your linux working directory via SMB (or SSHFS) and access it from your windows machine, but that would require quite some setup.

Both would be better than having two copies, especially when it's cross-platform.

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

Return JSON with error status code MVC

You have to return JSON error object yourself after setting the StatusCode, like so ...

if (BadRequest)
{
    Dictionary<string, object> error = new Dictionary<string, object>();
    error.Add("ErrorCode", -1);
    error.Add("ErrorMessage", "Something really bad happened");
    return Json(error);
}

Another way is to have a JsonErrorModel and populate it

public class JsonErrorModel
{
    public int ErrorCode { get; set;}

    public string ErrorMessage { get; set; }
}

public ActionResult SomeMethod()
{

    if (BadRequest)
    {
        var error = new JsonErrorModel
        {
            ErrorCode = -1,
            ErrorMessage = "Something really bad happened"
        };

        return Json(error);
    }

   //Return valid response
}

Take a look at the answer here as well

Portable way to check if directory exists [Windows/Linux, C]

Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

Display filename before matching line

How about this, which I managed to achieve thanks, in part, to this post.

You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE), inside several directories with a pattern (e.g. /logsapp1, /logsapp2). Each file has a pattern you want to grep (e.g. "init time"), and you want to have the "init time" of each file, but knowing which file it belongs to.

find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt

Then the outputfilename.txt would be something like

./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms

In general

find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt

Explanation:

find command will search the filenames based in the pattern

then, pipe xargs -I{} will redirect the find output to the {}

which will be the input for grep ""pattern" {}

Then the trick to make grep display the filenames \dev\null

and finally, write the output in file with tee outputfile.txt

This worked for me in grep version 9.0.5 build 1989.

json_decode to array

try this

$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);

glob exclude pattern

You can't exclude patterns with the glob function, globs only allow for inclusion patterns. Globbing syntax is very limited (even a [!..] character class must match a character, so it is an inclusion pattern for every character that is not in the class).

You'll have to do your own filtering; a list comprehension usually works nicely here:

files = [fn for fn in glob('somepath/*.txt') 
         if not os.path.basename(fn).startswith('eph')]

Remove everything after a certain character

If you also want to keep "?" and just remove everything after that particular character, you can do:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?

Fatal error: Namespace declaration statement has to be the very first statement in the script in

If you look this file Namespace is not the first statement.

<?php
class BulletProofException extends Exception{}

namespace BulletProof;

You can try to move the namespace over the class definition.

ADB Driver and Windows 8.1

I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.

I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"

A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.

Also I can use the phone as storage device.
Good luck

Javascript/jQuery detect if input is focused

With pure javascript:

this === document.activeElement // where 'this' is a dom object

or with jquery's :focus pseudo selector.

$(this).is(':focus');

Will Google Android ever support .NET?

Since this is one of the first links on Google when search for Android and .net support, it is only fitting to post this here.

The mono project is working on a SDK to develop Android applications using CIL languages such as C#. The down side is it will be a commercial product. monodroid

How to name Dockerfiles

dev.Dockerfile, test.Dockerfile, build.Dockerfile etc.

On VS Code I use <purpose>.Dockerfile and it gets recognized correctly.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

I got this error by mixing install/update methods: installed node via downloading package from website and later I used brew to update.

I fixed by uninstalling the brew version :

brew uninstall --ignore-dependencies node

Then I went back to node website and downloaded and installed via the package manager: https://nodejs.org/en/download/ For some reason, no amount of trying to reinstall via brew worked.

Adding subscribers to a list using Mailchimp's API v3

I got it working. I was adding the authentication to the header incorrectly:

$apikey = '<api_key>';
            $auth = base64_encode( 'user:'.$apikey );

            $data = array(
                'apikey'        => $apikey,
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array(
                    'FNAME' => $name
                )
            );
            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                        'Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

            $result = curl_exec($ch);

            var_dump($result);
            die('Mailchimp executed');

Meaning of $? (dollar question mark) in shell scripts

It has the last status code (exit value) of a command.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Losing scope when using ng-include

I've figured out how to work around this issue without mixing parent and sub scope data. Set a ng-if on the the ng-include element and set it to a scope variable. For example :

<div ng-include="{{ template }}" ng-if="show"/>

In your controller, when you have set all the data you need in your sub scope, then set show to true. The ng-include will copy at this moment the data set in your scope and set it in your sub scope.

The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.

Max

MySQL - Make an existing Field Unique

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

For MySQL 5.7.4 or later:

ALTER TABLE mytbl ADD UNIQUE (columnName);

As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error.

So, make sure to remove duplicate entries first as IGNORE keyword is no longer supported.

Reference

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;

into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

Creating a new dictionary in Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

The replace method in Javascript returns a value, and does not act upon the existing string object. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

In your example, you will have to do

$(this).attr("src", $(this).attr("src").replace(...))

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

any tool for java object to object mapping?

I'm happy to add Moo as an option, although clearly I'm biased towards it: http://geoffreywiseman.github.com/Moo/

It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.cs file.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Then all done.

Java Scanner class reading strings

You could have simply replaced

names[i] = in.nextLine(); with names[i] = in.next();

Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Firebase FCM notifications click_action payload

In Web, simply add the url you want to open:

{  
  "condition": "'test-topic' in topics || 'test-topic-2' in topics",  
  "notification": {
            "title": "FCM Message with condition and link",
            "body": "This is a Firebase Cloud Messaging Topic Message!",            
            "click_action": "https://yoururl.here"
        }
}

How to extract file name from path?

I am using this function... VBA Function:

Function FunctionGetFileName(FullPath As String) As String
'Update 20140210
Dim splitList As Variant
splitList = VBA.Split(FullPath, "\")
FunctionGetFileName = splitList(UBound(splitList, 1))
End Function

Now enter

=FunctionGetFileName(A1) in youe required cell.

or You can use these...

=MID(A1,FIND("*",SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))

X close button only using css

As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.

The content code is \00d7.

Example

div:after{
  display: inline-block;
  content: "\00d7"; /* This will render the 'X' */
}

You can then style and position the pseudo selector in any way you want. Hope this helps someone :).

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

For my case, the culprit was the semicolon and double quotes in the password for prod DB. Our IT team use some tool to generate passwords, so it generated one with the semicolon and double quotes Connectionstring looks like

<add key="BusDatabaseConnectionString" value="Data Source=myserver;Initial Catalog=testdb;User Id=Listener;Password=BlaBla"';[]qrk/>

Got the password changed and it worked.

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

Is there a REAL performance difference between INT and VARCHAR primary keys?

The question is about MySQL so I say there is a significant difference. If it was about Oracle (which stores numbers as string - yes, I couldn't believe it at first) then not much difference.

Storage in the table is not the issue but updating and referring to the index is. Queries involving looking up a record based on its primary key are frequent - you want them to occur as fast as possible because they happen so often.

The thing is a CPU deals with 4 byte and 8 byte integers naturally, in silicon. It's REALLY fast for it to compare two integers - it happens in one or two clock cycles.

Now look at a string - it's made up of lots of characters (more than one byte per character these days). Comparing two strings for precedence can't be done in one or two cycles. Instead the strings' characters must be iterated until a difference is found. I'm sure there are tricks to make it faster in some databases but that's irrelevant here because an int comparison is done naturally and lightning fast in silicon by the CPU.

My general rule - every primary key should be an autoincrementing INT especially in OO apps using an ORM (Hibernate, Datanucleus, whatever) where there's lots of relationships between objects - they'll usually always be implemented as a simple FK and the ability for the DB to resolve those fast is important to your app' s responsiveness.

How can I get a list of all classes within current module in Python?

I was able to get all I needed from the dir built in plus getattr.

# Works on pretty much everything, but be mindful that 
# you get lists of strings back

print dir(myproject)
print dir(myproject.mymodule)
print dir(myproject.mymodule.myfile)
print dir(myproject.mymodule.myfile.myclass)

# But, the string names can be resolved with getattr, (as seen below)

Though, it does come out looking like a hairball:

def list_supported_platforms():
    """
        List supported platforms (to match sys.platform)

        @Retirms:
            list str: platform names
    """
    return list(itertools.chain(
        *list(
            # Get the class's constant
            getattr(
                # Get the module's first class, which we wrote
                getattr(
                    # Get the module
                    getattr(platforms, item),
                    dir(
                        getattr(platforms, item)
                    )[0]
                ),
                'SYS_PLATFORMS'
            )
            # For each include in platforms/__init__.py 
            for item in dir(platforms)
            # Ignore magic, ourselves (index.py) and a base class.
            if not item.startswith('__') and item not in ['index', 'base']
        )
    ))

Clear back stack using fragments

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Are email addresses case sensitive?

Way late to this post, but I've got something slightly different to say...

>> "Are email addresses case sensitive?"

Well, "It Depends..." (TM)

Some organizations actually think that's a good idea and their email servers enforce case sensitivity.

So, for those crazy places, "Yes, Emails are case sensitive."

Note: Just because a specification says you can do something does not mean it is a good idea to do so.

The principle of KISS suggests that our systems use case insensitive emails.

Whereas the Robustness principle suggests that we accept case sensitive emails.

Solution:

  • Store emails with case sensitivity
  • Send emails with case sensitivity
  • Perform internal searches with case insensitivity

This would mean that if this email already exists: [email protected]

... and another user comes along and wants to use this email: [email protected]

... that our case insensitive searching logic would return a "That email already exists" error message.

Now, you have a decision to make: Is that solution adequate in your case?

If not, you could charge a convenience fee to those clients that demand support for their case sensitive emails and implement custom logic that allows the [email protected] into your system, even if [email protected] already exists.

In which case your email search/validation logic might look like something this pseudocode:

if (user.paidEmailFee) {
   // case sensitive email
   query = "select * from users where email LIKE ' + user.email + '"
} else {
   // case insensitive email
   query = "select * from users where email ILIKE ' + user.email + '"
}

This way, you are mostly enforcing case insensitivity but allowing customers to pay for this support if they are using email systems that support such nonsense.

p.s. ILIKE is a PostgreSQL keyword: http://www.postgresql.org/docs/9.2/static/functions-matching.html

How to remove the bottom border of a box with CSS

You can either set

border-bottom: none;

or

border-bottom: 0;

One sets the border-style to none.
One sets the border-width to 0px.

_x000D_
_x000D_
div {_x000D_
  border: 3px solid #900;_x000D_
_x000D_
  background-color: limegreen; _x000D_
  width:  28vw;_x000D_
  height: 10vw;_x000D_
  margin:  1vw;_x000D_
  text-align: center;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.stylenone {_x000D_
  border-bottom: none;_x000D_
}_x000D_
.widthzero {_x000D_
  border-bottom: 0;_x000D_
}
_x000D_
<div>_x000D_
(full border)_x000D_
</div>_x000D_
<div class="stylenone">_x000D_
(style)<br><br>_x000D_
_x000D_
border-bottom: none;_x000D_
</div>_x000D_
<div class="widthzero">_x000D_
(width)<br><br>_x000D_
border-bottom: 0;_x000D_
</div>
_x000D_
_x000D_
_x000D_

Side Note:
If you ever have to track down why a border is not showing when you expect it to, It is also good to know that either of these could be the culprit. Also verify the border-color is not the same as the background-color.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

I had the same issue with the aws-sdk and I solved it by using "target": "es2015". This is my tsconfig.json file.

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es2015"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

JSON array get length

The below snippet works fine for me(I used the size())

String itemId;
            for (int i = 0; i < itemList.size(); i++) {
            JSONObject itemObj = (JSONObject)itemList.get(i);
            itemId=(String) itemObj.get("ItemId");
            System.out.println(itemId);
            }

If it is wrong to use use size() kindly advise

How does functools partial do what it does?

partials are incredibly useful.

For instance, in a 'pipe-lined' sequence of function calls (in which the returned value from one function is the argument passed to the next).

Sometimes a function in such a pipeline requires a single argument, but the function immediately upstream from it returns two values.

In this scenario, functools.partial might allow you to keep this function pipeline intact.

Here's a specific, isolated example: suppose you want to sort some data by each data point's distance from some target:

# create some data
import random as RND
fnx = lambda: RND.randint(0, 10)
data = [ (fnx(), fnx()) for c in range(10) ]
target = (2, 4)

import math
def euclid_dist(v1, v2):
    x1, y1 = v1
    x2, y2 = v2
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

To sort this data by distance from the target, what you would like to do of course is this:

data.sort(key=euclid_dist)

but you can't--the sort method's key parameter only accepts functions that take a single argument.

so re-write euclid_dist as a function taking a single parameter:

from functools import partial

p_euclid_dist = partial(euclid_dist, target)

p_euclid_dist now accepts a single argument,

>>> p_euclid_dist((3, 3))
  1.4142135623730951

so now you can sort your data by passing in the partial function for the sort method's key argument:

data.sort(key=p_euclid_dist)

# verify that it works:
for p in data:
    print(round(p_euclid_dist(p), 3))

    1.0
    2.236
    2.236
    3.606
    4.243
    5.0
    5.831
    6.325
    7.071
    8.602

Or for instance, one of the function's arguments changes in an outer loop but is fixed during iteration in the inner loop. By using a partial, you don't have to pass in the additional parameter during iteration of the inner loop, because the modified (partial) function doesn't require it.

>>> from functools import partial

>>> def fnx(a, b, c):
      return a + b + c

>>> fnx(3, 4, 5)
      12

create a partial function (using keyword arg)

>>> pfnx = partial(fnx, a=12)

>>> pfnx(b=4, c=5)
     21

you can also create a partial function with a positional argument

>>> pfnx = partial(fnx, 12)

>>> pfnx(4, 5)
      21

but this will throw (e.g., creating partial with keyword argument then calling using positional arguments)

>>> pfnx = partial(fnx, a=12)

>>> pfnx(4, 5)
      Traceback (most recent call last):
      File "<pyshell#80>", line 1, in <module>
      pfnx(4, 5)
      TypeError: fnx() got multiple values for keyword argument 'a'

another use case: writing distributed code using python's multiprocessing library. A pool of processes is created using the Pool method:

>>> import multiprocessing as MP

>>> # create a process pool:
>>> ppool = MP.Pool()

Pool has a map method, but it only takes a single iterable, so if you need to pass in a function with a longer parameter list, re-define the function as a partial, to fix all but one:

>>> ppool.map(pfnx, [4, 6, 7, 8])

How can we redirect a Java program console output to multiple files?

You could use a "variable" inside the output filename, for example:

/tmp/FetchBlock-${current_date}.txt

current_date:

Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.

Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)

How to concatenate two numbers in javascript?

I converted back to number like this..

const timeNow = '' + 12 + 45;
const openTime = parseInt(timeNow, 10);

output 1245

-- edit --

sorry,

for my use this still did not work for me after testing . I had to add the missing zero back in as it was being removed on numbers smaller than 10, my use is for letting code run at certain times May not be correct but it seems to work (so far).

h = new Date().getHours();
m = new Date().getMinutes();
isOpen: boolean;

timeNow = (this.m < 10) ? '' + this.h + 0 + this.m : '' + this.h + this.m;

openTime = parseInt(this.timeNow);


closed() {

(this.openTime >= 1450 && this.openTime <= 1830) ? this.isOpen = true : 
this.isOpen = false;
(this.openTime >= 715 && this.openTime <= 915) ? this.isOpen = true : 
this.isOpen = false;

}

The vote down was nice thank you :)

I am new to this and come here to learn from you guys an explanation of why would of been nice.

Anyways updated my code to show how i fixed my problem as this post helped me figure it out.

Flutter.io Android License Status Unknown

Refer--https://robbinespu.gitlab.io/blog/2020/03/03/flutter-issue-fixed-android-license-status-unknown-on-windows/

So here the solution, open your SDK manager then uncheck Hide Obsolete Packages

enter image description here

Now you’ll see Android SDK Tools (Obsolete) 26.1.1 appears. Tick that package and hit apply button then ok button. it will download sdk. then restart Android studio

Nice, now if you run flutter doctor, you should get positive result as below

PS D:\Workplace\flutter_projects> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale en-MY)

[v] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[v] Android Studio (version 3.6)
[v] VS Code (version 1.42.1)
[v] Connected device (1 available)

• No issues found!

PS D:\Workplace\flutter_projects> flutter doctor --android-licenses -v
All SDK package licenses accepted.======] 100% Computing updates...

Run flutter doctor --android-licenses and enter Y when is asked

if needed we can download package manually here https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip (for Windows user). Hope this tutorial help people who looking for solution

The right way of setting <a href=""> when it's a local file

Try swapping your colon : for a bar |. that should do it

<a href="file://C|/path/to/file/file.html">Link Anchor</a>

show/hide html table columns using css

if you're looking for a simple column hide you can use the :nth-child selector as well.

#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
    display: none;
}

I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.

How do I convert an object to an array?

Careful:

$array = (array) $object;

does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.

If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }

    return $new;
}

How to multi-line "Replace in files..." in Notepad++

This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!

Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.

To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).

How to select an item in a ListView programmatically?

        int i=99;//is what row you want to select and focus
        listViewRamos.FocusedItem = listViewRamos.Items[0];
        listViewRamos.Items[i].Selected = true;
        listViewRamos.Select();
        listViewRamos.EnsureVisible(i);//This is the trick

How to use HTML to print header and footer on every printed page of a document?

I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here

<style> 
    @media screen {
        .only_print{
            display:none;
        }
    }
    @media print {
        .no-print {
            display: none !important;
        }
    }
    TABLE{border-collapse: collapse;}
    TH, TD {border:1px solid grey;}
</style>
<div class="no-print">  <!-- This is header for screen and will not be printed -->
    <div>COMPANY NAME FOR SCREEN</div>
    <div>DESCRIPTION FOR SCREEN</div>
</div>

<table>
    <thead>
        <tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
            <td colspan="100" style="border: 0px;">
                <div>COMPANY NAME FOR PRINT</div>
                <div>DESCRIPTION FOR PRINT</div>
            </td>
        </tr>
        <!-- From here Actual Data of table start -->
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1-1</td>
            <td>1-2</td>
            <td>1-3</td>
        </tr>
        <tr>
            <td>2-1</td>
            <td>2-2</td>
            <td>2-3</td>
        </tr>
    </tbody>
</table>

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

SQL Query to find the last day of the month

Declare @GivenDate datetime 
Declare @ResultDate datetime 
DEclare @EOMDate datetime 
Declare @Day int 
set @GivenDate=getdate() 
set @GivenDate= (dateadd(mm,1,@GivenDate)) 
set @Day =day(@GivenDate) 
set @ResultDate=dateadd(dd,-@Day+1,@GivenDate) 
select @EOMDate =dateadd(dd,-1 ,@ResultDate) 
select @EOMDate 

Interface naming in Java

There may be several reasons Java does not generally use the IUser convention.

  1. Part of the Object-Oriented approach is that you should not have to know whether the client is using an interface or an implementation class. So, even List is an interface and String is an actual class, a method might be passed both of them - it doesn't make sense to visually distinguish the interfaces.

  2. In general, we will actually prefer the use of interfaces in client code (prefer List to ArrayList, for instance). So it doesn't make sense to make the interfaces stand out as exceptions.

  3. The Java naming convention prefers longer names with actual meanings to Hungarian-style prefixes. So that code will be as readable as possible: a List represents a list, and a User represents a user - not an IUser.

Request format is unrecognized for URL unexpectedly ending in

In html you have to enclose the call in a a form with a GET with something like

<a href="/service/servicename.asmx/FunctionName/parameter=SomeValue">label</a>

You can also use a POST with the action being the location of the web service and input the parameter via an input tag.

There are also SOAP and proxy classes.

ES6 modules implementation, how to load a json file

Found this thread when I couldn't load a json-file with ES6 TypeScript 2.6. I kept getting this error:

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import suburbs from 'json-loader!./suburbs.json';

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

How to launch Safari and open URL from iOS app

In Swift 1.2, try this:

let pth = "http://www.google.com"
    if let url = NSURL(string: pth){
        UIApplication.sharedApplication().openURL(url)

Flask Python Buttons

Apply (different) name attribute to both buttons like

<button name="one">

and catch them in request.data.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

I have been using makeaclickablemap for my province maps for some time now and it turned out to be a really good fit.

How often should you use git-gc?

Recent versions of git run gc automatically when required, so you shouldn't have to do anything. See the Options section of man git-gc(1): "Some git commands run git gc --auto after performing operations that could create many loose objects."

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below
   <Window.DataContext>
      <local:Employee/>
   </Window.DataContext>

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
    {
        Employee e = (Employee) DataContext;
    }
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
    {
       Employee employee = new Employee();
    
       public MainWindow()
       {
           InitializeComponent();
    
           DataContext = employee;
       }
    }
    

Align vertically using CSS 3

Note: This example uses the draft version of the Flexible Box Layout Module. It has been superseded by the incompatible modern specification.

Center the child elements of a div box by using the box-align and box-pack properties together.

Example:

div
{
width:350px;
height:100px;
border:1px solid black;

/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;

/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;

/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;

/* W3C */
display:box;
box-pack:center;
box-align:center;
} 

Git Checkout warning: unable to unlink files, permission denied

I ran into this problem whenever running "git repack" or "git gc" on my OS X machines, even when running git with admin privileges, and I finally solved it after coming across this page: http://hints.macworld.com/comment.php?mode=view&cid=1734

The fix is to open a terminal, go to your git repo, cd into the .git folder, and then do:

chflags -R nouchg *

If that was the issue, then after that, your git commands will work as normal.

What is a singleton in C#?

using System;
using System.Collections.Generic;
class MainApp
{
    static void Main()
    {
        LoadBalancer oldbalancer = null;
        for (int i = 0; i < 15; i++)
        {
            LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();

            if (oldbalancer == balancerNew && oldbalancer != null)
            {
                Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
            }
            oldbalancer = balancerNew;
        }
        Console.ReadKey();
    }
}

class LoadBalancer
{
    private static LoadBalancer _instance;
    private List<string> _servers = new List<string>();
    private Random _random = new Random();

    private static object syncLock = new object();

    private LoadBalancer()
    {
        _servers.Add("ServerI");
        _servers.Add("ServerII");
        _servers.Add("ServerIII");
        _servers.Add("ServerIV");
        _servers.Add("ServerV");
    }

    public static LoadBalancer GetLoadBalancer()
    {
        if (_instance == null)
        {
            lock (syncLock)
            {
                if (_instance == null)
                {
                    _instance = new LoadBalancer();
                }
            }
        }

        return _instance;
    }

    public string Server
    {
        get
        {
            int r = _random.Next(_servers.Count);
            return _servers[r].ToString();
        }
    }
}

I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.

If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.

Additionally there is double check locking here

if (_instance == null)
            {
                lock (syncLock)
                {
                    if (_instance == null)

since from MSDN

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.

Hopefully it helps in clearing more.

And please comment if I my understanding is directing wrong ways.

NGINX - No input file specified. - php Fast/CGI

use in windows

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

wasn't putting -b

php-cgi.exe -b 127.0.0.1:9000

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Select row and element in awk

To expand on Dennis's answer, use awk's -v option to pass the i and j values:

# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'

Module is not available, misspelled or forgot to load (but I didn't)

You are improperly declaring your main module, it requires a second dependencies array argument when creating a module, otherwise it is a reference to an existing module

Change:

var app = angular.module("MesaViewer");

To:

var app = angular.module("MesaViewer",[]);

Working Version

Copy all values from fields in one class to another through reflection

I think you can try dozer. It has good support for bean to bean conversion. Its also easy to use. You can either inject it into your spring application or add the jar in class path and its done.

For an example of your case :

 DozerMapper mapper = new DozerMapper();
A a= new A();
CopyA copyA = new CopyA();
a.set... // set fields of a.
mapper.map(a,copyOfA); // will copy all fields from a to copyA

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

Create a new txt file using VB.NET

open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()

This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...

DataGridView changing cell background color

Similar as shown and mentioned:

Notes: Take into consideration that Cells will change their color (only) after the DataGridView Control is Visible. Therefore one practical solution would be using the:

VisibleChanged Event

In case you wish to keep your style when creating new Rows; also subscribe the:

RowsAdded Event


Example bellow:

///<summary> Instantiate the DataGridView Control. </summary>
private DataGridView dgView = new DataGridView;

///<summary> Method to configure DataGridView Control. </summary>
private void DataGridView_Configuration()
{
    // In this case the method just contains the VisibleChanged event subscription.

    dgView.VisibleChanged += DgView_VisibleChanged;

    // Uncomment line bellow in case you want to keep the style when creating new rows.
    // dgView.RowsAdded += DgView_RowsAdded;
}

///<summary> The actual Method that will re-design (Paint) DataGridView Cells. </summary>
 private void DataGridView_PaintCells()
 {
     int nrRows = dgView.Rows.Count;
     int nrColumns = dgView.Columns.Count;
     Color green = Color.LimeGreen;

     // Iterate over the total number of Rows
     for (int row = 0; row < nrRows; row++)
     {
         // Iterate over the total number of Columns
         for (int col = 0; col < nrColumns; col++) 
         {
             // Paint cell location (column, row)
             dgView[col, row].Style.BackColor = green;
         }
     }
 }

///<summary> The DataGridView VisibleChanged Event. </summary>
private void DataGridView_VisibleChanged(object sender, EventArgs e)
{
    DataGridView_PaintCells();
}

/// <summary> Occurrs when a new Row is Created. </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{ 
    DataGridView_PaintCells(); 
}


Finally: Just call the DataGridView_Configuration() (method)
i.e: Form Load Event.

How to redraw DataTable with new data

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

How to check if a string array contains one string in JavaScript?

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.

SQL Server - copy stored procedures from one db to another

Late one but gives more details that might be useful…

Here is a list of things you can do with advantages and disadvantages

Generate scripts using SSMS

  • Pros: extremely easy to use and supported by default
  • Cons: scripts might not be in the correct execution order and you might get errors if stored procedure already exists on secondary database. Make sure you review the script before executing.

Third party tools

  • Pros: tools such as ApexSQL Diff (this is what I use but there are many others like tools from Red Gate or Dev Art) will compare two databases in one click and generate script that you can execute immediately
  • Cons: these are not free (most vendors have a fully functional trial though)

System Views

  • Pros: You can easily see which stored procedures exist on secondary server and only generate those you don’t have.
  • Cons: Requires a bit more SQL knowledge

Here is how to get a list of all procedures in some database that don’t exist in another database

select *
from DB1.sys.procedures P
where P.name not in 
 (select name from DB2.sys.procedures P2)

Delay/Wait in a test case of Xcode UI testing

sleep will block the thread

"No run loop processing occurs while the thread is blocked."

you can use waitForExistence

let app = XCUIApplication()
app.launch()

if let label = app.staticTexts["Hello, world!"] {
label.waitForExistence(timeout: 5)
}

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

How can I do an OrderBy with a dynamic string parameter?

Another solution from codeConcussion (https://stackoverflow.com/a/7265394/2793768)

var param = "Address";    
var pi = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => pi.GetValue(x, null));

Setting Action Bar title and subtitle

You can set the title in action-bar using AndroidManifest.xml. Add label to the activity

<activity
            android:name=".YourActivity"
            android:label="Your Title" />

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

Spring get current ApplicationContext

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org

SQL recursive query on self referencing table (Oracle)

It's a little on the cumbersome side, but I believe this should work (without the extra join). This assumes that you can choose a character that will never appear in the field in question, to act as a separator.

You can do it without nesting the select, but I find this a little cleaner that having four references to SYS_CONNECT_BY_PATH.

select id, 
       parent_id, 
       case 
         when lvl <> 1 
         then substr(name_path,
                     instr(name_path,'|',1,lvl-1)+1,
                     instr(name_path,'|',1,lvl)
                      -instr(name_path,'|',1,lvl-1)-1) 
         end as name 
from (
  SELECT id, parent_id, sys_connect_by_path(name,'|') as name_path, level as lvl
  FROM tbl 
  START WITH id = 1 
  CONNECT BY PRIOR id = parent_id)

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

How do you change the width and height of Twitter Bootstrap's tooltips?

BS3:

.tooltip-inner { width:400px; max-width: 400px; }

How can I do division with variables in a Linux shell?

I believe it was already mentioned in other threads:

calc(){ awk "BEGIN { print "$*" }"; }

then you can simply type :

calc 7.5/3.2
  2.34375

In your case it will be:

x=20; y=3;
calc $x/$y

or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:

#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }

AES Encrypt and Decrypt

Code provided by SHS didn't work for me, but this one apparently did (I used a Bridging Header: #import <CommonCrypto/CommonCrypto.h>):

extension String {

    func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = self.data(using: String.Encoding.utf8),
            let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {


            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)



            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
                return base64cryptString


            }
            else {
                return nil
            }
        }
        return nil
    }

    func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
            let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCDecrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      data.bytes, data.length,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
                return unencryptedMessage
            }
            else {
                return nil
            }
        }
        return nil
    }


}

From my ViewController:

 let encoded = message.aesEncrypt(key: keyString, iv: iv)
 let unencode = encoded?.aesDecrypt(key: keyString, iv: iv)

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

How to allow only one radio button to be checked?

They need to all have the same name.

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

Advantages of SQL Server 2008 over SQL Server 2005?

Someone with more reputation can copy this into the main answer:

  • Change Tracking. Allows you to get info on what changes happened to which rows since a specific version.
  • Change Data Capture. Allows all changes to be captured and queried. (Enterprise)

Embed Google Map code in HTML with marker

The element that you posted looks like it's just copy-pasted from the Google Maps embed feature.

If you'd like to drop markers for the locations that you have, you'll need to write some JavaScript to do so. I'm learning how to do this as well.

Check out the following: https://developers.google.com/maps/documentation/javascript/overlays

It has several examples and code samples that can be easily re-used and adapted to fit your current problem.

Rename a dictionary key

You can use this OrderedDict recipe written by Raymond Hettinger and modify it to add a rename method, but this is going to be a O(N) in complexity:

def rename(self,key,new_key):
    ind = self._keys.index(key)  #get the index of old key, O(N) operation
    self._keys[ind] = new_key    #replace old key with new key in self._keys
    self[new_key] = self[key]    #add the new key, this is added at the end of self._keys
    self._keys.pop(-1)           #pop the last item in self._keys

Example:

dic = OrderedDict((("a",1),("b",2),("c",3)))
print dic
dic.rename("a","foo")
dic.rename("b","bar")
dic["d"] = 5
dic.rename("d","spam")
for k,v in  dic.items():
    print k,v

output:

OrderedDict({'a': 1, 'b': 2, 'c': 3})
foo 1
bar 2
c 3
spam 5

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Remove file extension from a file name string

String.LastIndexOf would work.

string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
 fileName= fileName.Substring(0, fileExtPos);

Is there a css cross-browser value for "width: -moz-fit-content;"?

Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.

.mydiv {  
  ...
  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
  ...
}

Adapted from: MDN

Angular.js programmatically setting a form field to dirty

Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

HTML -- two tables side by side

<div style="float: left;margin-right:10px">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>
<div style="float: left">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

C++ Dynamic Shared Library on Linux

The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:

shared.h defines the class:

class myclass {
   int myx;

  public:

    myclass() { myx=0; }
    void setx(int newx);
    int  getx();
};

shared.cpp defines the getx/setx functions:

#include "shared.h"

void myclass::setx(int newx) { myx = newx; }
int  myclass::getx() { return myx; }

main.cpp uses the class,

#include <iostream>
#include "shared.h"

using namespace std;

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

  cout << m.getx() << endl;
  m.setx(10);
  cout << m.getx() << endl;
}

and the makefile that generates libshared.so and links main with the shared library:

main: libshared.so main.o
    $(CXX) -o main  main.o -L. -lshared

libshared.so: shared.cpp
    $(CXX) -fPIC -c shared.cpp -o shared.o
    $(CXX) -shared  -Wl,-soname,libshared.so -o libshared.so shared.o

clean:
    $rm *.o *.so

To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).

The following specifies the current directory as the search path for libraries and runs main (bash syntax):

export LD_LIBRARY_PATH=.
./main

To see that the program is linked with libshared.so you can try ldd:

LD_LIBRARY_PATH=. ldd main

Prints on my machine:

  ~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
    linux-gate.so.1 =>  (0xb7f88000)
    libshared.so => ./libshared.so (0xb7f85000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
    libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
    libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
    /lib/ld-linux.so.2 (0xb7f89000)

Using ListView : How to add a header view?

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

Add Favicon with React and Webpack

I will give simple steps to add favicon :-)

  • Create your logo and save as logo.png
  • Change logo.png to favicon.ico

    Note : when you save it is favicon.ico make sure it's not favicon.ico.png

  • It might take some time to update

    change icon size in manifest.json if you can't wait

Java sending and receiving file (byte[]) over sockets

The correct way to copy a stream in Java is as follows:

int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

Wish I had a dollar for every time I've posted that in a forum.

Emulator error: This AVD's configuration is missing a kernel file

Following the accepted answer by ChrLipp using Android Studio 1.2.2 in Ubuntu 14.04:

  • Install "ARM EABI v7a System Image" package from Android SDK manager.
  • Delete the non functional Virtual Device.
  • Add a new device with Application Binary Interface(ABI) as armeabi-v7a.
  • Boot into the new device.

This worked for me. Try rebooting your system if it is not working for you.

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

Looking for a short & simple example of getters/setters in C#

well here is common usage of getter setter in actual use case,

public class OrderItem 
{
public int Id {get;set;}
public int quantity {get;set;}
public int Price {get;set;}
public int TotalAmount {get {return this.quantity *this.Price;}set;}
}

Turn on torch/flash on iPhone

//import fremework in .h file 

#import <AVFoundation/AVFoundation.h>
{
 AVCaptureSession *torchSession;
}

@property(nonatomic,retain)AVCaptureSession *torchSession;


-(IBAction)onoff:(id)sender;

//implement in .m file

@synthesize torchSession;

-(IBAction)onoff:(id)sender
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash])
    {
        if (device.torchMode == AVCaptureTorchModeOff) 
        {
            [button setTitle:@"OFF" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];

            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
            AVCaptureSession *session = [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
            [session addInput:flashInput];
            [session addOutput:output];
            [device unlockForConfiguration];
            [output release];
            [session commitConfiguration];
            [session startRunning];
            [self setTorchSession:session];
            [session release];
        }
        else 
        {
            [button setTitle:@"ON" forState:UIControlStateNormal];
            [torchSession stopRunning];
        }
    }
}

- (void)dealloc
{
    [torchSession release];
    [super dealloc];
}

What's the difference between session.persist() and session.save() in Hibernate?

Here is the difference:

  1. save:

    1. will return the id/identifier when the object is saved to the database.
    2. will also save when the object is tried to do the same by opening a new session after it is detached.
  2. Persist:

    1. will return void when the object is saved to the database.
    2. will throw PersistentObjectException when tried to save the detached object through a new session.

How to get column values in one comma separated value

You tagged the question with both sql-server and plsql so I will provide answers for both SQL Server and Oracle.

In SQL Server you can use FOR XML PATH to concatenate multiple rows together:

select distinct t.[user],
  STUFF((SELECT distinct ', ' + t1.department
         from yourtable t1
         where t.[user] = t1.[user]
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') department
from yourtable t;

See SQL Fiddle with Demo.

In Oracle 11g+ you can use LISTAGG:

select "User",
  listagg(department, ',') within group (order by "User") as departments
from yourtable
group by "User"

See SQL Fiddle with Demo

Prior to Oracle 11g, you could use the wm_concat function:

select "User",
  wm_concat(department) departments
from yourtable
group by "User"

How do I make a composite key with SQL Server Management Studio?

Highlight both rows in the table design view and click on the key icon, they will now be a composite primary key.

I'm not sure of your question, but only one column per table may be an IDENTITY column, not both.

What does `ValueError: cannot reindex from a duplicate axis` mean?

For people who are still struggling with this error, it can also happen if you accidentally create a duplicate column with the same name. Remove duplicate columns like so:

df = df.loc[:,~df.columns.duplicated()]

Convert number of minutes into hours & minutes using PHP

check this link for better solution. Click here

How to convert hh:mm:ss to minutes

$minutes=$item['time_diff'];
$hours =   sprintf('%02d',intdiv($minutes, 60)) .':'. ( sprintf('%02d',$minutes % 60));

How can I print to the same line?

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):

public class BackSpaceCharacterTest
{
    // the exception comes from the use of accessing the main thread
    public static void main(String[] args) throws InterruptedException
    {
        /*
            Notice the user of print as opposed to println:
            the '\b' char cannot go over the new line char.
        */
        System.out.print("Start[          ]");
        System.out.flush(); // the flush method prints it to the screen

        // 11 '\b' chars: 1 for the ']', the rest are for the spaces
        System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
        System.out.flush();
        Thread.sleep(500); // just to make it easy to see the changes

        for(int i = 0; i < 10; i++)
        {
            System.out.print("."); //overwrites a space
            System.out.flush();
            Thread.sleep(100);
        }

        System.out.print("] Done\n"); //overwrites the ']' + adds chars
        System.out.flush();
    }
}

How to delete or add column in SQLITE?

I've wrote a Java implementation based on the Sqlite's recommended way to do this:

private void dropColumn(SQLiteDatabase db,
        ConnectionSource connectionSource,
        String createTableCmd,
        String tableName,
        String[] colsToRemove) throws java.sql.SQLException {

    List<String> updatedTableColumns = getTableColumns(tableName);
    // Remove the columns we don't want anymore from the table's list of columns
    updatedTableColumns.removeAll(Arrays.asList(colsToRemove));

    String columnsSeperated = TextUtils.join(",", updatedTableColumns);

    db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");

    // Creating the table on its new format (no redundant columns)
    db.execSQL(createTableCmd);

    // Populating the table with the data
    db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
            + columnsSeperated + " FROM " + tableName + "_old;");
    db.execSQL("DROP TABLE " + tableName + "_old;");
}

To get the table's column, I used the "PRAGMA table_info":

public List<String> getTableColumns(String tableName) {
    ArrayList<String> columns = new ArrayList<String>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = getDB().rawQuery(cmd, null);

    while (cur.moveToNext()) {
        columns.add(cur.getString(cur.getColumnIndex("name")));
    }
    cur.close();

    return columns;
}

I actually wrote about it on my blog, you can see more explanations there:

http://udinic.wordpress.com/2012/05/09/sqlite-drop-column-support/

Matching an empty input box using CSS

If you're happy not not supporting IE or pre-Chromium Edge (which might be fine if you are using this for progressive enhancement), you can use :placeholder-shown as Berend has said. Note that for Chrome and Safari you actually need a non-empty placeholder for this to work, though a space works.

_x000D_
_x000D_
*,_x000D_
 ::after,_x000D_
 ::before {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
label.floating-label {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 2.2em;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input {_x000D_
  font-size: 1em;_x000D_
  height: 2.2em;_x000D_
  padding-top: 0.7em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  background-clip: padding-box;_x000D_
  border: 1px solid #ced4da;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:focus {_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  border-color: #80bdff;_x000D_
  outline: 0;_x000D_
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);_x000D_
}_x000D_
_x000D_
label.floating-label input+span {_x000D_
  position: absolute;_x000D_
  top: 0em;_x000D_
  left: 0;_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  font-size: 0.66em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  border: 1px solid transparent;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: font-size 0.1s ease-in-out, top 0.1s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown {_x000D_
  padding-top: 0;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown+span {_x000D_
  top: 0.3em;_x000D_
  font-size: 1em;_x000D_
}
_x000D_
<fieldset>_x000D_
  <legend>_x000D_
    Floating labels example (no-JS)_x000D_
  </legend>_x000D_
  <label class="floating-label">_x000D_
    <input type="text" placeholder=" ">_x000D_
    <span>Username</span>_x000D_
  </label>_x000D_
  <label class="floating-label">_x000D_
    <input type="Password" placeholder=" ">_x000D_
    <span>Password</span>_x000D_
  </label>_x000D_
</fieldset>_x000D_
<p>_x000D_
  Inspired by Bootstrap's <a href="https://getbootstrap.com/docs/4.0/examples/floating-labels/">floating labels</a>._x000D_
</p>
_x000D_
_x000D_
_x000D_

Automate scp file transfer using a shell script

The command scp can be used like a traditional UNIX cp. SO if you do :

scp -r myDirectory/ mylogin@host:TargetDirectory

will work

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

What is an AssertionError? In which case should I throw it from my own code?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

assert(x>10);

Output:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

Maven error: Not authorized, ReasonPhrase:Unauthorized

You have an old password in the settings.xml. It is trying to connect to the repositories, but is not able to, since the password is not updated. Once you update and re-run the command, you should be good.

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

How can I check if some text exist or not in the page using Selenium?

JUnit+Webdriver

assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");

If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.

How to get correct timestamp in C#

Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

"TIME" is the DateTime object that you would like to get the unix timestamp for.

jQuery dialog popup

It's quite simple, first HTML must be added:

<div id="dialog"></div>

Then, it must be initialized:

<script type="text/javascript">
  jQuery( document ).ready( function() {
    jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
  });
</script>

After this you can show it by code:

jQuery( '#dialog' ).dialog( 'open' );

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

How to show full column content in a Spark Dataframe?

try this command :

df.show(df.count())

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

PHP array: count or sizeof?

According to the website, sizeof() is an alias of count(), so they should be running the same code. Perhaps sizeof() has a little bit of overhead because it needs to resolve it to count()? It should be very minimal though.

How to call a web service from jQuery

EDIT:

The OP was not looking to use cross-domain requests, but jQuery supports JSONP as of v1.5. See jQuery.ajax(), specificically the crossDomain parameter.

The regular jQuery Ajax requests will not work cross-site, so if you want to query a remote RESTful web service, you'll probably have to make a proxy on your server and query that with a jQuery get request. See this site for an example.

If it's a SOAP web service, you may want to try the jqSOAPClient plugin.

Best way to disable button in Twitter's Bootstrap

Building off jeroenk's answer, here's the rundown:

$('button').addClass('disabled'); // Disables visually
$('button').prop('disabled', true); // Disables visually + functionally

$('input[type=button]').addClass('disabled'); // Disables visually
$('input[type=button]').prop('disabled', true); // Disables visually + functionally

$('a').addClass('disabled'); // Disables visually
$('a').prop('disabled', true); // Does nothing
$('a').attr('disabled', 'disabled'); // Disables visually

See fiddle

How to find server name of SQL Server Management Studio

Step1: Ensure SQLEXPRESS and LocalDB installed on your system Go to SQL SERVER Configuration Manager => SQL Server Service

If nothing listed for SQL Server services, install below components (for 64 bit OS) 1. SqlLocalDB 2. SQLEXPR_x64_ENU 3. SQLEXPRADV_x64_ENU 4. SQLEXPRWT_x64_ENU

Step2: Open Management Studios Enter . (Dot) as server name and click on Connect [enter image description here][2] Else Enter .\SQLEXPRESS as server name and click on connect

JSLint is suddenly reporting: Use the function form of "use strict"

There's nothing innately wrong with the string form.

Rather than avoid the "global" strict form for worry of concatenating non-strict javascript, it's probably better to just fix the damn non-strict javascript to be strict.

Why my $.ajax showing "preflight is invalid redirect error"?

My problem was that POST requests need trailing slashes '/'.

jQuery ID starts with

try:

$("td[id^=" + value + "]")

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

Enums in Javascript with ES6

If you don't need pure ES6 and can use Typescript, it has a nice enum:

https://www.typescriptlang.org/docs/handbook/enums.html

How do I prevent an Android device from going to sleep programmatically?

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

PowerShell equivalent to grep -f

I had the same issue trying to find text in files with powershell. I used the following - to stay as close to the Linux environment as possible.

Hopefully this helps somebody:

PowerShell:

PS) new-alias grep findstr
PS) ls -r *.txt | cat | grep "some random string"

Explanation:

ls       - lists all files
-r       - recursively (in all files and folders and subfolders)
*.txt    - only .txt files
|        - pipe the (ls) results to next command (cat)
cat      - show contents of files comming from (ls)
|        - pipe the (cat) results to next command (grep)
grep     - search contents from (cat) for "some random string" (alias to findstr)

Yes, this works as well:

PS) ls -r *.txt | cat | findstr "some random string"

How to execute a command prompt command from python

Try:

import os

os.popen("Your command here")

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

UICollectionView Self Sizing Cells with Auto Layout

I tried using estimatedItemSize but there were a bunch of bugs when inserting and deleting cells if the estimatedItemSize was not exactly equal to the cell's height. i stopped setting estimatedItemSize and implemented dynamic cell's by using a prototype cell. here's how that's done:

create this protocol:

protocol SizeableCollectionViewCell {
    func fittedSize(forConstrainedSize size: CGSize)->CGSize
}

implement this protocol in your custom UICollectionViewCell:

class YourCustomCollectionViewCell: UICollectionViewCell, SizeableCollectionViewCell {

    @IBOutlet private var mTitle: UILabel!
    @IBOutlet private var mDescription: UILabel!
    @IBOutlet private var mContentView: UIView!
    @IBOutlet private var mTitleTopConstraint: NSLayoutConstraint!
    @IBOutlet private var mDesciptionBottomConstraint: NSLayoutConstraint!

    func fittedSize(forConstrainedSize size: CGSize)->CGSize {

        let fittedSize: CGSize!

        //if height is greatest value, then it's dynamic, so it must be calculated
        if size.height == CGFLoat.greatestFiniteMagnitude {

            var height: CGFloat = 0

            /*now here's where you want to add all the heights up of your views.
              apple provides a method called sizeThatFits(size:), but it's not 
              implemented by default; except for some concrete subclasses such 
              as UILabel, UIButton, etc. search to see if the classes you use implement 
              it. here's how it would be used:
            */
            height += mTitle.sizeThatFits(size).height
            height += mDescription.sizeThatFits(size).height
            height += mCustomView.sizeThatFits(size).height    //you'll have to implement this in your custom view

            //anything that takes up height in the cell has to be included, including top/bottom margin constraints
            height += mTitleTopConstraint.constant
            height += mDescriptionBottomConstraint.constant

            fittedSize = CGSize(width: size.width, height: height)
        }
        //else width is greatest value, if not, you did something wrong
        else {
            //do the same thing that's done for height but with width, remember to include leading/trailing margins in calculations
        }

        return fittedSize
    }
}

now make your controller conform to UICollectionViewDelegateFlowLayout, and in it, have this field:

class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout {
    private var mCustomCellPrototype = UINib(nibName: <name of the nib file for your custom collectionviewcell>, bundle: nil).instantiate(withOwner: nil, options: nil).first as! SizeableCollectionViewCell
}

it will be used as a prototype cell to bind data to and then determine how that data affected the dimension that you want to be dynamic

finally, the UICollectionViewDelegateFlowLayout's collectionView(:layout:sizeForItemAt:) has to be implemented:

class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    private var mDataSource: [CustomModel]

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)->CGSize {

        //bind the prototype cell with the data that corresponds to this index path
        mCustomCellPrototype.bind(model: mDataSource[indexPath.row])    //this is the same method you would use to reconfigure the cells that you dequeue in collectionView(:cellForItemAt:). i'm calling it bind

        //define the dimension you want constrained
        let width = UIScreen.main.bounds.size.width - 20    //the width you want your cells to be
        let height = CGFloat.greatestFiniteMagnitude    //height has the greatest finite magnitude, so in this code, that means it will be dynamic
        let constrainedSize = CGSize(width: width, height: height)

        //determine the size the cell will be given this data and return it
        return mCustomCellPrototype.fittedSize(forConstrainedSize: constrainedSize)
    }
}

and that's it. Returning the cell's size in collectionView(:layout:sizeForItemAt:) in this way preventing me from having to use estimatedItemSize, and inserting and deleting cells works perfectly.

ES6 exporting/importing in index file

Also, bear in mind that if you need to export multiple functions at once, like actions you can use

export * from './XThingActions';

How to hide Android soft keyboard on EditText

Hide the keyboard

editText.setInputType(InputType.TYPE_NULL);

Show Keyboard

etData.setInputType(InputType.TYPE_CLASS_TEXT);
etData.setFocusableInTouchMode(true);

in the parent layout

android:focusable="false"

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

Extending the User model with custom fields in Django

New in Django 1.5, now you can create your own Custom User Model (which seems to be good thing to do in above case). Refer to 'Customizing authentication in Django'

Probably the coolest new feature on 1.5 release.

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

How to change the bootstrap primary color?

This seem to work for me in Bootstrap v5 alpha 3

_variables-overrides.scss

$primary: #00adef;

$theme-colors: (
  "primary":    $primary,
);

main.scss

// Overrides
@import "variables-overrides";

// Required - Configuration
@import "@/node_modules/bootstrap/scss/functions";
@import "@/node_modules/bootstrap/scss/variables";
@import "@/node_modules/bootstrap/scss/mixins";
@import "@/node_modules/bootstrap/scss/utilities";

// Optional - Layout & components
@import "@/node_modules/bootstrap/scss/root";
@import "@/node_modules/bootstrap/scss/reboot";
@import "@/node_modules/bootstrap/scss/type";
@import "@/node_modules/bootstrap/scss/images";
@import "@/node_modules/bootstrap/scss/containers";
@import "@/node_modules/bootstrap/scss/grid";
@import "@/node_modules/bootstrap/scss/tables";
@import "@/node_modules/bootstrap/scss/forms";
@import "@/node_modules/bootstrap/scss/buttons";
@import "@/node_modules/bootstrap/scss/transitions";
@import "@/node_modules/bootstrap/scss/dropdown";
@import "@/node_modules/bootstrap/scss/button-group";
@import "@/node_modules/bootstrap/scss/nav";
@import "@/node_modules/bootstrap/scss/navbar";
@import "@/node_modules/bootstrap/scss/card";
@import "@/node_modules/bootstrap/scss/accordion";
@import "@/node_modules/bootstrap/scss/breadcrumb";
@import "@/node_modules/bootstrap/scss/pagination";
@import "@/node_modules/bootstrap/scss/badge";
@import "@/node_modules/bootstrap/scss/alert";
@import "@/node_modules/bootstrap/scss/progress";
@import "@/node_modules/bootstrap/scss/list-group";
@import "@/node_modules/bootstrap/scss/close";
@import "@/node_modules/bootstrap/scss/toasts";
@import "@/node_modules/bootstrap/scss/modal";
@import "@/node_modules/bootstrap/scss/tooltip";
@import "@/node_modules/bootstrap/scss/popover";
@import "@/node_modules/bootstrap/scss/carousel";
@import "@/node_modules/bootstrap/scss/spinners";

// Helpers
@import "@/node_modules/bootstrap/scss/helpers";

// Utilities
@import "@/node_modules/bootstrap/scss/utilities/api";

@import "custom";

encrypt and decrypt md5

As already stated, you cannot decrypt MD5 without attempting something like brute force hacking which is extremely resource intensive, not practical, and unethical.

However you could use something like this to encrypt / decrypt passwords/etc safely:

$input = "SmackFactory";

$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );

echo $encrypted . '<br />' . $decrypted;

function encryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

Using a encypted method with a salt would be even safer, but this would be a good next step past just using a MD5 hash.

Open source face recognition for Android

You use class media.FaceDetector in android to detect face for free.

This is an example of face detection: https://github.com/betri28/FaceDetectCamera

CSS vertical alignment of inline/inline-block elements

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

Tracking the script execution time in PHP

You may only want to know the execution time of parts of your script. The most flexible way to time parts or an entire script is to create 3 simple functions (procedural code given here but you could turn it into a class by putting class timer{} around it and making a couple of tweaks). This code works, just copy and paste and run:

$tstart = 0;
$tend = 0;

function timer_starts()
{
global $tstart;

$tstart=microtime(true); ;

}

function timer_ends()
{
global $tend;

$tend=microtime(true); ;

}

function timer_calc()
{
global $tstart,$tend;

return (round($tend - $tstart,2));
}

timer_starts();
file_get_contents('http://google.com');
timer_ends();
print('It took '.timer_calc().' seconds to retrieve the google page');

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

Repeat String - Javascript

Note to new readers: This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get String things done. When I wrote "less process" I definitely meant "less code" because, as others have noted in subsequent answers, it performs like a pig. So don't use it if speed matters to you.

I'd put this function onto the String object directly. Instead of creating an array, filling it, and joining it with an empty char, just create an array of the proper length, and join it with your desired string. Same result, less process!

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

alert( "string to repeat\n".repeat( 4 ) );

Find duplicate characters in a String and count the number of occurances using Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String reverse1;
        String reverse2;
        int count = 0;
        while(n > 0)
        {
            String A = sc.next();
            String B = sc.next();
            reverse1 = new StringBuffer(A).reverse().toString();
            reverse2 = new StringBuffer(B).reverse().toString();
            if(!A.equals(reverse1))
            {
                for(int i = 0; i < A.length(); i++)
                {
                    for(int j = 0; j < A.length(); j++)
                    {
                        if(A.charAt(j) == A.charAt(i))
                        {
                            count++;
                        }
                    }
                    if(count % 2 != 0)
                    {
                        A.replace(A.charAt(i),"");
                        count = 0;
                    }
                }
                System.out.println(A);
            }
            n--;
        } 
    }
}

Bash tool to get nth line from a file

I have a unique situation where I can benchmark the solutions proposed on this page, and so I'm writing this answer as a consolidation of the proposed solutions with included run times for each.

Set Up

I have a 3.261 gigabyte ASCII text data file with one key-value pair per row. The file contains 3,339,550,320 rows in total and defies opening in any editor I have tried, including my go-to Vim. I need to subset this file in order to investigate some of the values that I've discovered only start around row ~500,000,000.

Because the file has so many rows:

  • I need to extract only a subset of the rows to do anything useful with the data.
  • Reading through every row leading up to the values I care about is going to take a long time.
  • If the solution reads past the rows I care about and continues reading the rest of the file it will waste time reading almost 3 billion irrelevant rows and take 6x longer than necessary.

My best-case-scenario is a solution that extracts only a single line from the file without reading any of the other rows in the file, but I can't think of how I would accomplish this in Bash.

For the purposes of my sanity I'm not going to be trying to read the full 500,000,000 lines I'd need for my own problem. Instead I'll be trying to extract row 50,000,000 out of 3,339,550,320 (which means reading the full file will take 60x longer than necessary).

I will be using the time built-in to benchmark each command.

Baseline

First let's see how the head tail solution:

$ time head -50000000 myfile.ascii | tail -1
pgm_icnt = 0

real    1m15.321s

The baseline for row 50 million is 00:01:15.321, if I'd gone straight for row 500 million it'd probably be ~12.5 minutes.

cut

I'm dubious of this one, but it's worth a shot:

$ time cut -f50000000 -d$'\n' myfile.ascii
pgm_icnt = 0

real    5m12.156s

This one took 00:05:12.156 to run, which is much slower than the baseline! I'm not sure whether it read through the entire file or just up to line 50 million before stopping, but regardless this doesn't seem like a viable solution to the problem.

AWK

I only ran the solution with the exit because I wasn't going to wait for the full file to run:

$ time awk 'NR == 50000000 {print; exit}' myfile.ascii
pgm_icnt = 0

real    1m16.583s

This code ran in 00:01:16.583, which is only ~1 second slower, but still not an improvement on the baseline. At this rate if the exit command had been excluded it would have probably taken around ~76 minutes to read the entire file!

Perl

I ran the existing Perl solution as well:

$ time perl -wnl -e '$.== 50000000 && print && exit;' myfile.ascii
pgm_icnt = 0

real    1m13.146s

This code ran in 00:01:13.146, which is ~2 seconds faster than the baseline. If I'd run it on the full 500,000,000 it would probably take ~12 minutes.

sed

The top answer on the board, here's my result:

$ time sed "50000000q;d" myfile.ascii
pgm_icnt = 0

real    1m12.705s

This code ran in 00:01:12.705, which is 3 seconds faster than the baseline, and ~0.4 seconds faster than Perl. If I'd run it on the full 500,000,000 rows it would have probably taken ~12 minutes.

mapfile

I have bash 3.1 and therefore cannot test the mapfile solution.

Conclusion

It looks like, for the most part, it's difficult to improve upon the head tail solution. At best the sed solution provides a ~3% increase in efficiency.

(percentages calculated with the formula % = (runtime/baseline - 1) * 100)

Row 50,000,000

  1. 00:01:12.705 (-00:00:02.616 = -3.47%) sed
  2. 00:01:13.146 (-00:00:02.175 = -2.89%) perl
  3. 00:01:15.321 (+00:00:00.000 = +0.00%) head|tail
  4. 00:01:16.583 (+00:00:01.262 = +1.68%) awk
  5. 00:05:12.156 (+00:03:56.835 = +314.43%) cut

Row 500,000,000

  1. 00:12:07.050 (-00:00:26.160) sed
  2. 00:12:11.460 (-00:00:21.750) perl
  3. 00:12:33.210 (+00:00:00.000) head|tail
  4. 00:12:45.830 (+00:00:12.620) awk
  5. 00:52:01.560 (+00:40:31.650) cut

Row 3,338,559,320

  1. 01:20:54.599 (-00:03:05.327) sed
  2. 01:21:24.045 (-00:02:25.227) perl
  3. 01:23:49.273 (+00:00:00.000) head|tail
  4. 01:25:13.548 (+00:02:35.735) awk
  5. 05:47:23.026 (+04:24:26.246) cut

MySQL: Insert datetime into other datetime field

If you don't need the DATETIME value in the rest of your code, it'd be more efficient, simple and secure to use an UPDATE query with a sub-select, something like

UPDATE products SET t=(SELECT f FROM products WHERE id=17) WHERE id=42;

or in case it's in the same row in a single table, just

UPDATE products SET t=f WHERE id=42;

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

Operator overloading in Java

Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.

We can take +(plus) for example:

int a = 2 + 4;
string = "hello" + "world";

Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.

Why is it common to put CSRF prevention tokens in cookies?

A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

Request Body Approach

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
  5. User submits form.
  6. Server checks hidden field matches session stored token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Cookie can actually be HTTP Only.

Disadvantages:

  • All forms must output the hidden field in HTML.
  • Any AJAX POSTs must also include the value.
  • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

Custom HTTP Header (downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form (token is sent via hidden field).
  7. Server checks hidden field matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work without an AJAX request to get the header value.
  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
  • Might as well have simply output the token to the page which would save the extra request.

Custom HTTP Header (upstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
  5. User submits form via AJAX (token is sent via header).
  6. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must include the header.

Custom HTTP Header (upstream & downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form via AJAX (token is sent via header) .
  7. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

Set-Cookie

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
  5. User submits form via AJAX or via HTML form.
  6. Server checks custom header (or hidden form field) matches session stored token.
  7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
  • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

Disadvantages:

  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
  • Cookie cannot be HTTP Only.

So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

How to use router.navigateByUrl and router.navigate in Angular

navigateByUrl

routerLink directive as used like this:

<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>

is just a wrapper around imperative navigation using router and its navigateByUrl method:

router.navigateByUrl('/inbox/33/messages/44')

as can be seen from the sources:

export class RouterLink {
  ...

  @HostListener('click')
  onClick(): boolean {
    ...
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

class MyComponent {
   constructor(router: Router) {
      this.router.navigateByUrl(...);
   }
}

navigate

There's another method on the router that you can use - navigate:

router.navigate(['/inbox/33/messages/44'])

difference between the two

Using router.navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

To see the difference clearly, imagine that the current URL is '/inbox/11/messages/22(popup:compose)'.

With this URL, calling router.navigateByUrl('/inbox/33/messages/44') will result in '/inbox/33/messages/44'. But calling it with router.navigate(['/inbox/33/messages/44']) will result in '/inbox/33/messages/44(popup:compose)'.

Read more in the official docs.

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

What is the difference between association, aggregation and composition?

https://www.linkedin.com/pulse/types-relationships-object-oriented-programming-oop-sarah-el-dawody/

Composition: is a "part-of" relationship.

for example “engine is part of the car”, “heart is part of the body”.

enter image description here

Association: is a “has-a” type relationship

For example, suppose we have two classes then these two classes are said to be “has-a” relationships if both of these entities share each other’s object for some work and at the same time they can exist without each other's dependency or both have their own lifetime.

enter image description here

The above example showing an association relationship because of both Employee and Manager class using the object of each other and both their own independent life cycle.

Aggregation: is based is on "has-a" relationship and it's is \\a special form of association

for example, “Student” and “address”. Each student must have an address so the relationship between Student class and Address class will be “Has-A” type relationship but vice versa is not true.

enter image description here

Edit a specific Line of a Text File in C#

I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps

using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
        {
            var destinationReader = StreamReader(fs);
            var writer = StreamWriter(fs);
            while ((line = reader.ReadLine()) != null)
            {
              if (line_number == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    destinationReader .ReadLine();
                }
                line_number++;
            }
        }

case statement in SQL, how to return multiple variables?

You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:

SELECT * FROM
  (SELECT val1, val2 FROM table1 WHERE (condition1 is true) 
                                    OR (condition2 is true))
UNION
SELECT * FROM
  (SELECT val5, val6 FROM table7 WHERE (condition9 is true) 
                                    OR (condition4 is true))

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

How to remove the border highlight on an input text element

You can try this also

input[type="text"] {
outline-style: none;
}

or

.classname input{
outline-style: none;
}

Pointer to class data member "::*"

Here is an example where pointer to data members could be useful:

#include <iostream>
#include <list>
#include <string>

template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
    for (const typename Container::value_type& x : container) {
        if (x->*ptr == t)
            return x;
    }
    return typename Container::value_type{};
}

struct Object {
    int ID, value;
    std::string name;
    Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};

std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
    new Object(2,11,"Tom"), new Object(15,16,"John") };

int main() {
    const Object* object = searchByDataMember (objects, 11, &Object::value);
    std::cout << object->name << '\n';  // Tom
}

Using the HTML5 "required" attribute for a group of checkboxes?

we can do this easily with html5 also, just need to add some jquery code

Demo

HTML

<form>
 <div class="form-group options">
   <input type="checkbox" name="type[]" value="A" required /> A
   <input type="checkbox" name="type[]" value="B" required /> B
   <input type="checkbox" name="type[]" value="C" required /> C
   <input type="submit">
 </div>
</form>

Jquery

$(function(){
    var requiredCheckboxes = $('.options :checkbox[required]');
    requiredCheckboxes.change(function(){
        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        } else {
            requiredCheckboxes.attr('required', 'required');
        }
    });
});

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

wp-admin shows blank page, how to fix it?

That white screen of death happened to my blog, and what I did was that I renamed the theme and plugin, and everything was back to normal.

Is it possible to use global variables in Rust?

Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
        let mut map = HashMap::new();
        map.insert("James", vec!["user", "admin"]);
        map.insert("Jim", vec!["user"]);
        map
    };
}

fn show_access(name: &str) {
    let access = PRIVILEGES.get(name);
    println!("{}: {:?}", name, access);
}

fn main() {
    let access = PRIVILEGES.get("James");
    println!("James: {:?}", access);

    show_access("Jim");
}

Graphical user interface Tutorial in C

The two most usual choices are GTK+, which has documentation links here, and is mostly used with C; or Qt which has documentation here and is more used with C++.

I posted these two as you do not specify an operating system and these two are pretty cross-platform.

Java - sending HTTP parameters via POST method easily

Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

So the minimum required code is:

    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
    connection.connect();
    connection.getOutputStream().close(); 

You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

You can also use NameValuePair apparently.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

How to pass a value from Vue data to href?

You need to use v-bind: or its alias :. For example,

<a v-bind:href="'/job/'+ r.id">

or

<a :href="'/job/' + r.id">

C++ multiline string literal

In C++11 you have raw string literals. Sort of like here-text in shells and script languages like Python and Perl and Ruby.

const char * vogon_poem = R"V0G0N(
             O freddled gruntbuggly thy micturations are to me
                 As plured gabbleblochits on a lurgid bee.
              Groop, I implore thee my foonting turlingdromes.   
           And hooptiously drangle me with crinkly bindlewurdles,
Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't.

                (by Prostetnic Vogon Jeltz; see p. 56/57)
)V0G0N";

All the spaces and indentation and the newlines in the string are preserved.

These can also be utf-8|16|32 or wchar_t (with the usual prefixes).

I should point out that the escape sequence, V0G0N, is not actually needed here. Its presence would allow putting )" inside the string. In other words, I could have put

                "(by Prostetnic Vogon Jeltz; see p. 56/57)"

(note extra quotes) and the string above would still be correct. Otherwise I could just as well have used

const char * vogon_poem = R"( ... )";

The parens just inside the quotes are still needed.

Align contents inside a div

<div class="content">Hello</div>

.content {
    margin-top:auto;
    margin-bottom:auto;
    text-align:center;
}

JavaScript style.display="none" or jQuery .hide() is more efficient?

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.