Programs & Examples On #And operator

The and operator can refer to a either a logical AND (evaluating to true if all the compared statements are true) or a bitwise AND (comparing the bits of an integer).

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Regex AND operator

Maybe you are looking for something like this. If you want to select the complete line when it contains both "foo" and "baz" at the same time, this RegEx will comply that:

.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

This problem will occurred due to some unnecessary changes made in my.cnf file. Try to diff /etc/mysql/my.cnf with one of working mysql servers my.cnf file.

I just replaced /etc/mysql/my.cnf file with new my.cnf file and this works for me.

What size should TabBar images be?

30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.

How do I check if a PowerShell module is installed?

When I use a non-default modules in my scripts I call the function below. Beside the module name you can provide a minimum version.

# See https://www.powershellgallery.com/ for module and version info
Function Install-ModuleIfNotInstalled(
    [string] [Parameter(Mandatory = $true)] $moduleName,
    [string] $minimalVersion
) {
    $module = Get-Module -Name $moduleName -ListAvailable |`
        Where-Object { $null -eq $minimalVersion -or $minimalVersion -ge $_.Version } |`
        Select-Object -Last 1
    if ($null -ne $module) {
         Write-Verbose ('Module {0} (v{1}) is available.' -f $moduleName, $module.Version)
    }
    else {
        Import-Module -Name 'PowershellGet'
        $installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
        if ($null -ne $installedModule) {
            Write-Verbose ('Module [{0}] (v {1}) is installed.' -f $moduleName, $installedModule.Version)
        }
        if ($null -eq $installedModule -or ($null -ne $minimalVersion -and $installedModule.Version -lt $minimalVersion)) {
            Write-Verbose ('Module {0} min.vers {1}: not installed; check if nuget v2.8.5.201 or later is installed.' -f $moduleName, $minimalVersion)
            #First check if package provider NuGet is installed. Incase an older version is installed the required version is installed explicitly
            if ((Get-PackageProvider -Name NuGet -Force).Version -lt '2.8.5.201') {
                Write-Warning ('Module {0} min.vers {1}: Install nuget!' -f $moduleName, $minimalVersion)
                Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force
            }        
            $optionalArgs = New-Object -TypeName Hashtable
            if ($null -ne $minimalVersion) {
                $optionalArgs['RequiredVersion'] = $minimalVersion
            }  
            Write-Warning ('Install module {0} (version [{1}]) within scope of the current user.' -f $moduleName, $minimalVersion)
            Install-Module -Name $moduleName @optionalArgs -Scope CurrentUser -Force -Verbose
        } 
    }
}

usage example:

Install-ModuleIfNotInstalled 'CosmosDB' '2.1.3.528'

Please let me known if it's usefull (or not)

HTTP GET request in JavaScript?

Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.

In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}

java.sql.SQLException: Exhausted Resultset

When there is no records returned from Database for a particular condition and When I tried to access the rs.getString(1); I got this error "exhausted resultset".

Before the issue, my code was:

rs.next();
sNr= rs.getString(1);

After the fix:

while (rs.next()) {
    sNr = rs.getString(1);
}

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

failed to push some refs to [email protected]

for me deleting package-lock.json fixed my problem,

  1. delete
  2. commit changes
  3. push again

turns out Heroku accepts only one package.json file :p

CSS - display: none; not working

Remove display: block; in the div #tfl style property

<div id="tfl" style="display: block; width: 187px; height: 260px;

Inline style take priority then css file

In which case do you use the JPA @JoinTable annotation?

EDIT 2017-04-29: As pointed to by some of the commenters, the JoinTable example does not need the mappedBy annotation attribute. In fact, recent versions of Hibernate refuse to start up by printing the following error:

org.hibernate.AnnotationException: 
   Associations marked as mappedBy must not define database mappings 
   like @JoinTable or @JoinColumn

Let's pretend that you have an entity named Project and another entity named Task and each project can have many tasks.

You can design the database schema for this scenario in two ways.

The first solution is to create a table named Project and another table named Task and add a foreign key column to the task table named project_id:

Project      Task
-------      ----
id           id
name         name
             project_id

This way, it will be possible to determine the project for each row in the task table. If you use this approach, in your entity classes you won't need a join table:

@Entity
public class Project {

   @OneToMany(mappedBy = "project")
   private Collection<Task> tasks;

}

@Entity
public class Task {

   @ManyToOne
   private Project project;

}

The other solution is to use a third table, e.g. Project_Tasks, and store the relationship between projects and tasks in that table:

Project      Task      Project_Tasks
-------      ----      -------------
id           id        project_id
name         name      task_id

The Project_Tasks table is called a "Join Table". To implement this second solution in JPA you need to use the @JoinTable annotation. For example, in order to implement a uni-directional one-to-many association, we can define our entities as such:

Project entity:

@Entity
public class Project {

    @Id
    @GeneratedValue
    private Long pid;

    private String name;

    @JoinTable
    @OneToMany
    private List<Task> tasks;

    public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }
}

Task entity:

@Entity
public class Task {

    @Id
    @GeneratedValue
    private Long tid;

    private String name;

    public Long getTid() {
        return tid;
    }

    public void setTid(Long tid) {
        this.tid = tid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This will create the following database structure:

ER Diagram 1

The @JoinTable annotation also lets you customize various aspects of the join table. For example, had we annotated the tasks property like this:

@JoinTable(
        name = "MY_JT",
        joinColumns = @JoinColumn(
                name = "PROJ_ID",
                referencedColumnName = "PID"
        ),
        inverseJoinColumns = @JoinColumn(
                name = "TASK_ID",
                referencedColumnName = "TID"
        )
)
@OneToMany
private List<Task> tasks;

The resulting database would have become:

ER Diagram 2

Finally, if you want to create a schema for a many-to-many association, using a join table is the only available solution.

Print new output on same line

>>> for i in range(1, 11):
...     print(i, end=' ')
...     if i==len(range(1, 11)): print()
... 
1 2 3 4 5 6 7 8 9 10 
>>> 

This is how to do it so that the printing does not run behind the prompt on the next line.

Comparing Java enum members: == or equals()?

Using == to compare two enum values works, because there is only one object for each enum constant.

On a side note, there is actually no need to use == to write null-safe code, if you write your equals() like this:

public useEnums(final SomeEnum a) {
    if (SomeEnum.SOME_ENUM_VALUE.equals(a)) {
        …
    }
    …
}

This is a best practice known as Compare Constants From The Left that you definitely should follow.

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

Gradle: How to Display Test Results in the Console in Real Time?

Add this to build.gradle to stop gradle from swallowing stdout and stderr.

test {
    testLogging.showStandardStreams = true
}

It's documented here.

How can I change the default Mysql connection timeout when connecting through python?

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value

SELECT @@GLOBAL.MAX_EXECUTION_TIME, @@SESSION.MAX_EXECUTION_TIME;

Then set it according to your needs.

SET SESSION MAX_EXECUTION_TIME=2000;
SET GLOBAL MAX_EXECUTION_TIME=2000;

IntelliJ cannot find any declarations

I was having similar issues in my IntelliJ mvn project. Pom.xml was not recognized. What worked for me was right click on the pom.xml and then add as a maven project.

jQuery location href

Use:

window.location.replace(...)

See this Stack Overflow question for more information:

How do I redirect to another webpage?

Or perhaps it was this you remember:

var url = "http://stackoverflow.com";
$(location).attr('href',url);

How to use the 'main' parameter in package.json?

To answer your first question, the way you load a module is depending on the module entry point and the main parameter of the package.json.

Let's say you have the following file structure:

my-npm-module
|-- lib
|   |-- module.js
|-- package.json

Without main parameter in the package.json, you have to load the module by giving the module entry point: require('my-npm-module/lib/module.js').

If you set the package.json main parameter as follows "main": "lib/module.js", you will be able to load the module this way: require('my-npm-module').

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

Java: Enum parameter in method

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

How can I roll back my last delete command in MySQL?

Use the BEGIN TRANSACTION command before starting queries. So that you can ROLLBACK things at any point of time.

FOR EXAMPLE:

  1. begin transaction
  2. select * from Student
  3. delete from Student where Id=2
  4. select * from Student
  5. rollback
  6. select * from Student

Format numbers in django templates

Django's contributed humanize application does this:

{% load humanize %}
{{ my_num|intcomma }}

Be sure to add 'django.contrib.humanize' to your INSTALLED_APPS list in the settings.py file.

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

Getting Data from Android Play Store

Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.

As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:

  • Make sure the URL you are trying to parse is not blocked in robots.txt - e.g. https://play.google.com/robots.txt
  • Make sure that you are not doing it too often, Google will throttle and potentially blacklist you if you are doing it too much.
  • Send a correct User-Agent header to actually show you are a bot
  • The page of an app is big - make sure you accept gzip and request the mobile version
  • GPlay website is not an API, it doesn't care that you parse it so it will change over time. Make sure you handle changes - e.g. by having test to make sure you get what you expected.

So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:

      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet(crawlUrl);
      HttpResponse rsp = httpClient.execute(request);

      int statusCode = rsp.getStatusLine().getStatusCode();

      if (statusCode == 200) {
           String content = EntityUtils.toString(rsp.getEntity());    
           Document doc = Jsoup.parse(content);
           //parse content, whatever you need
           Element price = doc.select("[itemprop=price]").first();
      }      

For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:

  • Search is forbidden in robots.
  • Keeping app metadata up-to-date is hard to do. There are more than 2.2m apps, if you want to refresh their metadata daily there are 2.2 requests/day, which will 1) get blocked immediately, 2) costs a lot of money - pessimistic 220gb data transfer per day if one app is 100k
  • How do you discover new apps
  • How do you get pricing in each country, translations of each language

The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.

[2]:

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

how to check if a datareader is null or empty

if (myReader.HasRows) //The key Word is **.HasRows**

{

    ltlAdditional.Text = "Contains data";

}

else

{   

    ltlAdditional.Text = "Is null Or Empty";

}

How to insert image in mysql database(table)?

Step 1: open your mysql workbench application select table. choose image cell right click select "Open value in Editor" enter image description here

Step 2: click on the load button and choose image file enter image description here

Step 3:then click apply buttonenter image description here

Step 4: Then apply the query to save the image .Don't forgot image data type is "BLOB". Step 5: You can can check uploaded image enter image description here

Convert to date format dd/mm/yyyy

You can use a regular expression or some manual string fiddling, but I think I prefer:

date("d/m/Y", strtotime($str));

What I can do to resolve "1 commit behind master"?

Use

git cherry-pick <commit-hash>

So this will pick your behind commit to git location you are on.

How to execute a shell script from C in Linux?

If you need more fine-grade control, you can also go the fork pipe exec route. This will allow your application to retrieve the data outputted from the shell script.

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

proper way to sudo over ssh

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

How to make ng-repeat filter out duplicate results

It seems everybody is throwing their own version of the unique filter into the ring, so I'll do the same. Critique is very welcome.

angular.module('myFilters', [])
  .filter('unique', function () {
    return function (items, attr) {
      var seen = {};
      return items.filter(function (item) {
        return (angular.isUndefined(attr) || !item.hasOwnProperty(attr))
          ? true
          : seen[item[attr]] = !seen[item[attr]];
      });
    };
  });

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

How to set editable true/false EditText in Android programmatically?

Once focus of edit text is removed, it would not allow you to type even if you set it to focusable again.

Here is a way around it

if (someCondition)
   editTextField.setFocusable(false);
else
   editTextField.setFocusableInTouchMode(true);

Setting it true in setFocusableInTouchMode() seems to do the trick.

Unable to open debugger port in IntelliJ IDEA

None of above methods worked in my case i.e. changing port number in run configuration, machine restart, invalidate cache in IntelliJ, killing process shown in netstat (nestat -anob | findstr <port-number> and then tskill <pid>). The only thing that finally helped was starting and shutting down tomcat manually via startup.bat and shutdown.bat (you should use correspondig .sh files on linux and macOS).

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

jQuery Mobile: document ready vs. page events

Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).

$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});

You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:

$(window).unload(function () { debugger; console.log("window unloaded");});

And you will see what I mean.

How to check type of files without extensions in python?

also you can use this code (pure python by 3 byte of header file):

full_path = os.path.join(MEDIA_ROOT, pathfile)

try:
    image_data = open(full_path, "rb").read()
except IOError:
    return "Incorrect Request :( !!!"

header_byte = image_data[0:3].encode("hex").lower()

if header_byte == '474946':
    return "image/gif"
elif header_byte == '89504e':
    return "image/png"
elif header_byte == 'ffd8ff':
    return "image/jpeg"
else:
    return "binary file"

without any package install [and update version]

How to save/restore serializable object to/from file?

You can use the following:

    /// <summary>
    /// Serializes an object.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="serializableObject"></param>
    /// <param name="fileName"></param>
    public void SerializeObject<T>(T serializableObject, string fileName)
    {
        if (serializableObject == null) { return; }

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, serializableObject);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }
    }


    /// <summary>
    /// Deserializes an xml file into an object list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public T DeSerializeObject<T>(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) { return default(T); }

        T objectOut = default(T);

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            string xmlString = xmlDocument.OuterXml;

            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(T);

                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    objectOut = (T)serializer.Deserialize(reader);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }

        return objectOut;
    }

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

Convert alphabet letters to number in Python

Here's something I use to convert excel column letters to numbers (so a limit of 3 letters but it's pretty easy to extend this out if you need more). Probably not the best way but it works for what I need it for.

def letter_to_number(letters):
    letters = letters.lower()
    dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
    strlen = len(letters)
    if strlen == 1:
        number = dictionary[letters]
    elif strlen == 2:
        first_letter = letters[0]
        first_number = dictionary[first_letter]
        second_letter = letters[1]
        second_number = dictionary[second_letter]
        number = (first_number * 26) + second_number
    elif strlen == 3:
        first_letter = letters[0]
        first_number = dictionary[first_letter]
        second_letter = letters[1]
        second_number = dictionary[second_letter]
        third_letter = letters[2]
        third_number = dictionary[third_letter]
        number = (first_number * 26 * 26) + (second_number * 26) + third_number
    return number

Using Caps Lock as Esc in Mac OS X

It is now much easier to map the Caps Lock key to Esc with macOS Sierra.

  1. Open System Preferences ? Keyboard.

  2. Click the Modifier Keys button in the bottom right-hand corner.

  3. Click the drop down box next to the hardware key that you’d like to remap, and select Escape.

  4. Click OK and close System Preferences.

enter image description here

https://9to5mac.com/2016/10/25/remap-escape-key-action-macbook-pro-macos-sierra-10-12-1-modifier-keys/

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

In Java, how do I call a base class's method from the overriding method in a derived class?

super.MyMethod() should be called inside the MyMethod() of the class B. So it should be as follows

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { 
        super.MyMethod();
        /* Another code */ 
    }
}

What is the recommended way to make a numeric TextField in JavaFX?

I would like to improve Evan Knowles answer: https://stackoverflow.com/a/30796829/2628125

In my case I had class with handlers for UI Component part. Initialization:

this.dataText.textProperty().addListener((observable, oldValue, newValue) -> this.numericSanitization(observable, oldValue, newValue));

And the numbericSanitization method:

private synchronized void numericSanitization(ObservableValue<? extends String> observable, String oldValue, String newValue) {
    final String allowedPattern = "\\d*";

    if (!newValue.matches(allowedPattern)) {
        this.dataText.setText(oldValue);
    }
}

Keyword synchronized is added to prevent possible render lock issue in javafx if setText will be called before old one is finished execution. It is easy to reproduce if you will start typing wrong chars really fast.

Another advantage is that you keep only one pattern to match and just do rollback. It is better because you can easily abstragate solution for different sanitization patterns.

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

Sequelize, convert entity to plain object

For nested JSON plain text

db.model.findAll({
  raw : true ,
  nest : true
})

find all unchecked checkbox in jquery

$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
               // enter your code here
            } });

Javascript - object key->value

Use this syntax:

obj[name]

Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).

obj["Hey, this is ... neat?"] = 42

String length in bytes in JavaScript

There is no way to do it in JavaScript natively. (See Riccardo Galli's answer for a modern approach.)


For historical reference or where TextEncoder APIs are still unavailable.

If you know the character encoding, you can calculate it yourself though.

encodeURIComponent assumes UTF-8 as the character encoding, so if you need that encoding, you can do,

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

This should work because of the way UTF-8 encodes multi-byte sequences. The first encoded byte always starts with either a high bit of zero for a single byte sequence, or a byte whose first hex digit is C, D, E, or F. The second and subsequent bytes are the ones whose first two bits are 10. Those are the extra bytes you want to count in UTF-8.

The table in wikipedia makes it clearer

Bits        Last code point Byte 1          Byte 2          Byte 3
  7         U+007F          0xxxxxxx
 11         U+07FF          110xxxxx        10xxxxxx
 16         U+FFFF          1110xxxx        10xxxxxx        10xxxxxx
...

If instead you need to understand the page encoding, you can use this trick:

function lengthInPageEncoding(s) {
  var a = document.createElement('A');
  a.href = '#' + s;
  var sEncoded = a.href;
  sEncoded = sEncoded.substring(sEncoded.indexOf('#') + 1);
  var m = sEncoded.match(/%[0-9a-f]{2}/g);
  return sEncoded.length - (m ? m.length * 2 : 0);
}

How to open the Chrome Developer Tools in a new window?

enter image description here

  1. click on three dots in the top right ->
  2. click on "Undock into separate window" icon

How to make the window full screen with Javascript (stretching all over the screen)

Create Function

function toggleFullScreen() {

            if ((document.fullScreenElement && document.fullScreenElement !== null) ||
                    (!document.mozFullScreen && !document.webkitIsFullScreen)) {
             $scope.topMenuData.showSmall = true;
                if (document.documentElement.requestFullScreen) {
                    document.documentElement.requestFullScreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullScreen) {
                    document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {

                  $scope.topMenuData.showSmall = false;
                if (document.cancelFullScreen) {
                    document.cancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                }
            }
        }

In Html Put Code like

<ul class="unstyled-list fg-white">

            <li class="place-right" data-ng-if="!topMenuData.showSmall" data-ng-click="toggleFullScreen()">Full Screen</li>
            <li class="place-right" data-ng-if="topMenuData.showSmall" data-ng-click="toggleFullScreen()">Back</li>
        </ul>

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

How to make overlay control above all other controls?

This is a common function of Adorners in WPF. Adorners typically appear above all other controls, but the other answers that mention z-order may fit your case better.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

Make sure the hamcrest jar is higher on the import order than your JUnit jar.

JUnit comes with its own org.hamcrest.Matcher class that is probably being used instead.

You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes.

mockito also has the hamcrest classes in it as well, so you may need to move\reorder it as well

Add new row to excel Table (VBA)

I actually just found that if you want to add multiple rows below the selection in your table Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

in the first you should make form like this :

<form method="post" enctype="multipart/form-data" >
   <input type="file" name="file[]" multiple id="file"/>
   <input type="submit" name="ok"  />
</form> 

that is right . now add this code under your form code or on the any page you like

<?php
if(isset($_POST['ok']))
   foreach ($_FILES['file']['name'] as $filename) {
    echo $filename.'<br/>';
}
?>

it's easy... finish

String.equals() with multiple conditions (and one action on result)

Possibilities:

  • Use String.equals():

    if (some_string.equals("john") ||
        some_string.equals("mary") ||
        some_string.equals("peter"))
    {
    }
    
  • Use a regular expression:

    if (some_string.matches("john|mary|peter"))
    {
    }
    
  • Store a list of strings to be matched against in a Collection and search the collection:

    Set<String> names = new HashSet<String>();
    names.add("john");
    names.add("mary");
    names.add("peter");
    
    if (names.contains(some_string))
    {
    }
    

Best way to read a large file into a byte array in C#?

I might argue that the answer here generally is "don't". Unless you absolutely need all the data at once, consider using a Stream-based API (or some variant of reader / iterator). That is especially important when you have multiple parallel operations (as suggested by the question) to minimise system load and maximise throughput.

For example, if you are streaming data to a caller:

Stream dest = ...
using(Stream source = File.OpenRead(path)) {
    byte[] buffer = new byte[2048];
    int bytesRead;
    while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
        dest.Write(buffer, 0, bytesRead);
    }
}

How do you set the max number of characters for an EditText in Android?

I always set the max like this:

    <EditText
        android:id="@+id/edit_blaze_it
        android:layout_width="0dp"
        android:layout_height="@dimen/too_high"

    <!-- This is the line you need to write to set the max-->
        android:maxLength="420"
        />

Using varchar(MAX) vs TEXT on SQL Server

If using MS Access (especially older versions like 2003) you are forced to use TEXT datatype on SQL Server as MS Access does not recognize nvarchar(MAX) as a Memo field in Access, whereas TEXT is recognized as a Memo-field.

Calculate date from week number

Currently, there is no C# class that correctly handles ISO 8601week numbers. Even though you can instantiate a culture, look for the closest thing and correct that, I think it is better to do the complete calculation yourself:

    /// <summary>
    /// Converts a date to a week number.
    /// ISO 8601 week 1 is the week that contains the first Thursday that year.
    /// </summary>
    public static int ToIso8601Weeknumber(this DateTime date)
    {
        var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
        return (thursday.DayOfYear - 1) / 7 + 1;
    }

    /// <summary>
    /// Converts a week number to a date.
    /// Note: Week 1 of a year may start in the previous year.
    /// ISO 8601 week 1 is the week that contains the first Thursday that year, so
    /// if December 28 is a Monday, December 31 is a Thursday,
    /// and week 1 starts January 4.
    /// If December 28 is a later day in the week, week 1 starts earlier.
    /// If December 28 is a Sunday, it is in the same week as Thursday January 1.
    /// </summary>
    public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
    {
        var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
        var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
        return monday.AddDays(day.DayOffset());
    }

    /// <summary>
    /// Iso8601 weeks start on Monday. This returns 0 for Monday.
    /// </summary>
    private static int DayOffset(this DayOfWeek weekDay)
    {
        return ((int)weekDay + 6) % 7;
    }

How do you enable auto-complete functionality in Visual Studio C++ express edition?

All the answers were missing Ctrl-J (which enables and disables autocomplete).

Very Simple, Very Smooth, JavaScript Marquee

I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/ It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;

function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
        scroll();
    }
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
        b.animate({
            'left': -width
        }, time, 'linear', function() {
            scroll();
        });
    }
}

b.css({
    'width': width,
    'left': start_pos
});
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over
}

$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element
});

Why do Twitter Bootstrap tables always have 100% width?

All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span* grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:

.table-nonfluid {
   width: auto !important;
}

You can add this class inside your own stylesheet and simply add it to the container of your table like so:

<table class="table table-nonfluid"> ... </table>

This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

In my case even though I used all the solutions mentioned above but nothing worked for me. So I decided to uninstall docker and install it again.

Now in the process, I have noticed that I did not check Use Windows containers instead of Linux containers (this can be changed after installation) in my previous installation, and that is why I got the problem above and the solutions still did not fix it. So ensure to check it before you run desktop docker or uninstall it and install it again by checking this option.

Docker Installation Process

How to redraw DataTable with new data

The accepted answer calls the draw function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:

datatable.clear().rows.add(newData).draw();

remove url parameters with javascript or jquery

//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
    var newUrl = refineUrl();
    window.history.pushState("object or string", "Title", "/"+newUrl );
}

function refineUrl()
{
    //get full url
    var url = window.location.href;
    //get url after/  
    var value = url = url.slice( 0, url.indexOf('?') );
    //get the part after before ?
    value  = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');  
    return value;     
}

JavaScript, getting value of a td with id name

For input you must have used value to grab its text but for td, you should use innerHTML to get its html/value. Example:

alert(document.getElementById("td_id_here").innerHTML);

To get its text though, use:

alert(document.getElementById("td_id_here").innerText);

Creating a new column based on if-elif-else condition

df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1

Easy to solve using indexing. The first line of code reads like so, if column A is equal to column B then create and set column C equal to 0.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

JAXB: how to marshall map into <key>value</key>

I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <mapProperty>
      <map>
         <key>value</key>
         <key2>value2</key2>
      </map>
   </mapProperty>
</root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, String> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, String>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> map) {
        this.mapProperty = map;
    }

}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {

    @Override
    public AdaptedMap marshal(Map<String, String> map) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element rootElement = document.createElement("map");
        document.appendChild(rootElement);

        for(Entry<String,String> entry : map.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.setTextContent(entry.getValue());
            rootElement.appendChild(mapElement);
        }

        AdaptedMap adaptedMap = new AdaptedMap();
        adaptedMap.setValue(document);
        return adaptedMap;
    }

    @Override
    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Element rootElement = (Element) adaptedMap.getValue();
        NodeList childNodes = rootElement.getChildNodes();
        for(int x=0,size=childNodes.getLength(); x<size; x++) {
            Node childNode = childNodes.item(x);
            if(childNode.getNodeType() == Node.ELEMENT_NODE) {
                map.put(childNode.getLocalName(), childNode.getTextContent());
            }
        }
        return map;
    }

}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;

public class AdaptedMap {

    private Object value;

    @XmlAnyElement
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

Webpack not excluding node_modules

Try use absolute path:

exclude:path.resolve(__dirname, "node_modules")

Bootstrap modal: is not a function

The problem is due to having jQuery instances more than one time. Take care if you are using many files with multiples instance of jQuery. Just leave 1 instance of jQuery and your code will work.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

How to make a JSONP request from Javascript without JQuery?

the way I use jsonp like below:

function jsonp(uri) {
    return new Promise(function(resolve, reject) {
        var id = '_' + Math.round(10000 * Math.random());
        var callbackName = 'jsonp_callback_' + id;
        window[callbackName] = function(data) {
            delete window[callbackName];
            var ele = document.getElementById(id);
            ele.parentNode.removeChild(ele);
            resolve(data);
        }

        var src = uri + '&callback=' + callbackName;
        var script = document.createElement('script');
        script.src = src;
        script.id = id;
        script.addEventListener('error', reject);
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
    });
}

then use 'jsonp' method like this:

jsonp('http://xxx/cors').then(function(data){
    console.log(data);
});

reference:

JavaScript XMLHttpRequest using JsonP

http://www.w3ctech.com/topic/721 (talk about the way of use Promise)

Console.WriteLine does not show up in Output window

Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.

Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.

Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).

Press any key to continue

Here is what I use.

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

Loop inside React JSX

I am not sure if this will work for your situation, but often [map][1] is a good answer.

If this was your code with the for loop:

<tbody>
    for (var i=0; i < objects.length; i++) {
        <ObjectRow obj={objects[i]} key={i}>
    }
</tbody>

You could write it like this with the map function:

<tbody>
    {objects.map(function(object, i){
        return <ObjectRow obj={object} key={i} />;
    })}
</tbody>

objects.map is the best way to do a loop, and objects.filter is the best way to filter the required data. The filtered data will form a new array, and objects.some is the best way to check whether the array satisfies the given condition (it returns Boolean).

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Enabling HTTPS on express.js

First, you need to create selfsigned.key and selfsigned.crt files. Go to Create a Self-Signed SSL Certificate Or do following steps.

Go to the terminal and run the following command.

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt

  • After that put the following information
  • Country Name (2 letter code) [AU]: US
  • State or Province Name (full name) [Some-State]: NY
  • Locality Name (eg, city) []:NY
  • Organization Name (eg, company) [Internet Widgits Pty Ltd]: xyz (Your - Organization)
  • Organizational Unit Name (eg, section) []: xyz (Your Unit Name)
  • Common Name (e.g. server FQDN or YOUR name) []: www.xyz.com (Your URL)
  • Email Address []: Your email

After creation adds key & cert file in your code, and pass the options to the server.

const express = require('express');
const https = require('https');
const fs = require('fs');
const port = 3000;

var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
var options = {
  key: key,
  cert: cert
};

app = express()
app.get('/', (req, res) => {
   res.send('Now using https..');
});

var server = https.createServer(options, app);

server.listen(port, () => {
  console.log("server starting on port : " + port)
});
  • Finally run your application using https.

More information https://github.com/sagardere/set-up-SSL-in-nodejs

jquery $(window).height() is returning the document height

Here's a question and answer for this: Difference between screen.availHeight and window.height()

Has pics too, so you can actually see the differences. Hope this helps.

Basically, $(window).height() give you the maximum height inside of the browser window (viewport), and$(document).height() gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.

How to add header row to a pandas DataFrame

To fix your code you can simply change [Cov] to Cov.values, the first parameter of pd.DataFrame will become a multi-dimensional numpy array:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

But the smartest solution still is use pd.read_excel with header=None and names=columns_list.

Get day of week in SQL Server 2005/2008

With SQL Server 2012 and onward you can use the FORMAT function

SELECT FORMAT(GETDATE(), 'dddd')

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

How to check if the string is empty?

Test empty or blank string (shorter way):

if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

You can change the matplotlib using backend using the from agg to Tkinter TKAgg using command

matplotlib.use('TKAgg',warn=False, force=True)

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

Default instance name of SQL Server Express

Should be .\SQLExpress or localhost\SQLExpress no $ sign at the end

See also here http://www.connectionstrings.com/sql-server-2008

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

Why is PHP session_destroy() not working?

After using session_destroy(), the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION, which was already populated for this request, but it will be empty in future requests.

You can manually clear $_SESSION if you so desire ($_SESSION = [];).

'do...while' vs. 'while'

I can't imagine how you've gone this long without using a do...while loop.

There's one on another monitor right now and there are multiple such loops in that program. They're all of the form:

do
{
    GetProspectiveResult();
}
while (!ProspectIsGood());

Spark - load CSV file as DataFrame?

To read from relative path on the system use System.getProperty method to get current directory and further uses to load the file using relative path.

scala> val path = System.getProperty("user.dir").concat("/../2015-summary.csv")
scala> val csvDf = spark.read.option("inferSchema","true").option("header", "true").csv(path)
scala> csvDf.take(3)

spark:2.4.4 scala:2.11.12

Position DIV relative to another DIV?

First set position of the parent DIV to relative (specifying the offset, i.e. left, top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want.
It's simple and should do the trick well.

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

How to stop event bubbling on checkbox click

Here's a trick that worked for me:

handleClick = e => {
    if (e.target === e.currentTarget) {
        // do something
    } else {
        // do something else
    }
}

Explanation: I attached handleClick to a backdrop of a modal window, but it also fired on every click inside of a modal window (because it was IN the backdrop div). So I added the condition (e.target === e.currentTarget), which is only fulfilled when a backdrop is clicked.

Angular 4 - get input value

I think you were planning to use Angular template reference variable based on your html template.

 // in html
 <input #nameInput type="text" class="form-control" placeholder=''/>

 // in add-player.ts file
 import { OnInit, ViewChild, ElementRef } from '@angular/core';

 export class AddPlayerComponent implements OnInit {
   @ViewChild('nameInput') nameInput: ElementRef;

   constructor() { }

   ngOnInit() { }

   addPlayer() {
     // you can access the input value via the following syntax.
     console.log('player name: ', this.nameInput.nativeElement.value);
   }
 }

Fast Bitmap Blur For Android SDK

Thanks @Yahel for the code. Posting the same method with alpha channel blurring support as it took me some time to make it work correctly so it may save someone's time:

/**
 * Stack Blur v1.0 from
 * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
 * Java Author: Mario Klingemann <mario at quasimondo.com>
 * http://incubator.quasimondo.com
 * <p/>
 * created Feburary 29, 2004
 * Android port : Yahel Bouaziz <yahel at kayenko.com>
 * http://www.kayenko.com
 * ported april 5th, 2012
 * <p/>
 * This is a compromise between Gaussian Blur and Box blur
 * It creates much better looking blurs than Box Blur, but is
 * 7x faster than my Gaussian Blur implementation.
 * <p/>
 * I called it Stack Blur because this describes best how this
 * filter works internally: it creates a kind of moving stack
 * of colors whilst scanning through the image. Thereby it
 * just has to add one new block of color to the right side
 * of the stack and remove the leftmost color. The remaining
 * colors on the topmost layer of the stack are either added on
 * or reduced by one, depending on if they are on the right or
 * on the left side of the stack.
 * <p/>
 * If you are using this algorithm in your code please add
 * the following line:
 * Stack Blur Algorithm by Mario Klingemann <[email protected]>
 */

public static Bitmap fastblur(Bitmap sentBitmap, float scale, int radius) {

    int width = Math.round(sentBitmap.getWidth() * scale);
    int height = Math.round(sentBitmap.getHeight() * scale);
    sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int a[] = new int[wh];
    int rsum, gsum, bsum, asum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][4];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum, aoutsum;
    int rinsum, ginsum, binsum, ainsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            asum += sir[3] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];
            a[yi] = dv[asum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];
            sir[3] = a[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;
            asum += a[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            pix[yi] = (dv[asum] << 24) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];


            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];
            sir[3] = a[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi += w;
        }
    }

    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return (bitmap);
}

Sending intent to BroadcastReceiver from adb

I am not sure whether anyone faced issues with getting the whole string "test from adb". Using the escape character in front of the space worked for me.

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb" -n com.whereismywifeserver/.IntentReceiver

How can I check if a string is null or empty in PowerShell?

Personally, I do not accept a whitespace ($STR3) as being 'not empty'.

When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.

I find this is the best way to accomplish it:

$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}

Empty

$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}

Empty

$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}

Empty!! :-)

$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}

Not empty

How can I get the external SD card path for Android 4.0+?

Thanks for the clues provided by you guys, especially @SmartLemon, I got the solution. In case someone else need it, I put my final solution here( to find the first listed external SD card ):

public File getExternalSDCardDirectory()
{
    File innerDir = Environment.getExternalStorageDirectory();
    File rootDir = innerDir.getParentFile();
    File firstExtSdCard = innerDir ;
    File[] files = rootDir.listFiles();
    for (File file : files) {
        if (file.compareTo(innerDir) != 0) {
            firstExtSdCard = file;
            break;
        }
    }
    //Log.i("2", firstExtSdCard.getAbsolutePath().toString());
    return firstExtSdCard;
}

If no external SD card there, then it returns the on board storage. I will use it if the sdcard is not exist, you may need to change it.

Python socket receive - incoming packets always have a different size

You can alternatively use recv(x_bytes, socket.MSG_WAITALL), which seems to work only on Unix, and will return exactly x_bytes.

Storing data into list with class

EmailData clsEmailData = new EmailData();
List<EmailData> lstemail = new List<EmailData>(); 

clsEmailData.FirstName="JOhn";
clsEmailData.LastName ="Smith";
clsEmailData.Location ="Los Angeles"

lstemail.add(clsEmailData);

Why is 2 * (i * i) faster than 2 * i * i in Java?

I got similar results:

2 * (i * i): 0.458765943 s, n=119860736
2 * i * i: 0.580255126 s, n=119860736

I got the SAME results if both loops were in the same program, or each was in a separate .java file/.class, executed on a separate run.

Finally, here is a javap -c -v <.java> decompile of each:

     3: ldc           #3                  // String 2 * (i * i):
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: iload         4
    30: imul
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

vs.

     3: ldc           #3                  // String 2 * i * i:
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: imul
    29: iload         4
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

FYI -

java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

Why functional languages?

Lots of people have mentioned Functional Languages.

But some of the Most commonly used Functional Languages in use today besides Javascript.

Excel, SQL, XSLT, XQuery, J and K are used in financial realm.

Of course Erlang.

So I would say that from that list that Functional Programming techniques are used in mainstream every day.

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

Why use the INCLUDE clause when creating an index?

If the column is not in the WHERE/JOIN/GROUP BY/ORDER BY, but only in the column list in the SELECT clause is where you use INCLUDE.

The INCLUDE clause adds the data at the lowest/leaf level, rather than in the index tree. This makes the index smaller because it's not part of the tree

INCLUDE columns are not key columns in the index, so they are not ordered. This means it isn't really useful for predicates, sorting etc as I mentioned above. However, it may be useful if you have a residual lookup in a few rows from the key column(s)

Another MSDN article with a worked example

Combining multiple commits before pushing in Git

What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.

"Insert if not exists" statement in SQLite

If you never want to have duplicates, you should declare this as a table constraint:

CREATE TABLE bookmarks(
    users_id INTEGER,
    lessoninfo_id INTEGER,
    UNIQUE(users_id, lessoninfo_id)
);

(A primary key over both columns would have the same effect.)

It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:

INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)

How to use comparison operators like >, =, < on BigDecimal

Every object of the Class BigDecimal has a method compareTo you can use to compare it to another BigDecimal. The result of compareTo is then compared > 0, == 0 or < 0 depending on what you need. Read the documentation and you will find out.

The operators ==, <, > and so on can only be used on primitive data types like int, long, double or their wrapper classes like Integerand Double.

From the documentation of compareTo:

Compares this BigDecimal with the specified BigDecimal.

Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

Enum ToString with user friendly strings

Instead of using an enum use a static class.

replace

private enum PublishStatuses{
    NotCompleted,
    Completed,
    Error
};

with

private static class PublishStatuses{
    public static readonly string NotCompleted = "Not Completed";
    public static readonly string Completed = "Completed";
    public static readonly string Error = "Error";
};

it will be used like this

PublishStatuses.NotCompleted; // "Not Completed"

Issue using the top "extension method" solutions:

A private enum is often used inside another class. The extension method solution is not valid there since it must be in it's own class. This solution can be private and embedded in another class.

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

BEGIN - END block atomic transactions in PL/SQL

You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.

If an error occurs the transaction implicitly does a ROLLBACK.

This is the default behaviour for PL/SQL.

What's the difference between StaticResource and DynamicResource in WPF?

Important benefit of the dynamic resources

if application startup takes extremely long time, you must use dynamic resources, because static resources are always loaded when the window or app is created, while dynamic resources are loaded when they’re first used.

However, you won’t see any benefit unless your resource is extremely large and complex.

Implode an array with JavaScript?

We can create alternative of implode of in javascript:

function my_implode_js(separator,array){
       var temp = '';
       for(var i=0;i<array.length;i++){
           temp +=  array[i] 
           if(i!=array.length-1){
                temp += separator  ; 
           }
       }//end of the for loop

       return temp;
}//end of the function

var array = new Array("One", "Two", "Three");


var str = my_implode_js('-',array);
alert(str);

Make install, but not to default directories?

try using INSTALL_ROOT.

make install INSTALL_ROOT=$INSTALL_DIRECTORY

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

How do I set the default page of my application in IIS7?

Karan has posted the answer but that didn't work for me. So, I am posting what worked for me. If that didn't work then user can try this

<configuration> 
    <system.webServer> 
        <defaultDocument enabled="true"> 
            <files> 
                <add value="myFile.aspx" /> 
            </files> 
        </defaultDocument> 
    </system.webServer>
</configuration> 

Typescript: React event types

I think the simplest way is that:

type InputEvent = React.ChangeEvent<HTMLInputElement>;
type ButtonEvent = React.MouseEvent<HTMLButtonElement>;

update = (e: InputEvent): void => this.props.login[e.target.name] = e.target.value;
submit = (e:  ButtonEvent): void => {
    this.props.login.logIn();
    e.preventDefault();
}

What should a Multipart HTTP request with multiple files look like?

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

What is the difference between include and require in Ruby?

Have you ever tried to require a module? What were the results? Just try:

MyModule = Module.new
require MyModule # see what happens

Modules cannot be required, only included!

What's the purpose of SQL keyword "AS"?

In the early days of SQL, it was chosen as the solution to the problem of how to deal with duplicate column names (see below note).

To borrow a query from another answer:

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
  FROM Products AS P
       INNER JOIN Orders AS O ON O.ProductID = P.ProductID
 WHERE O.OrderID = 123456

The column ProductID (and possibly others) is common to both tables and since the join condition syntax requires reference to both, the 'dot qualification' provides disambiguation.

Of course, the better solution was to never have allowed duplicate column names in the first place! Happily, if you use the newer NATURAL JOIN syntax, the need for the range variables P and O goes away:

SELECT ProductName, ProductRetailPrice, Quantity
  FROM Products NATURAL JOIN Orders
 WHERE OrderID = 123456

But why is the AS keyword optional? My recollection from a personal discussion with a member of the SQL standard committee (either Joe Celko or Hugh Darwen) was that their recollection was that, at the time of defining the standard, one vendor's product (Microsoft's?) required its inclusion and another vendor's product (Oracle's?) required its omission, so the compromise chosen was to make it optional. I have no citation for this, you either believe me or not!


In the early days of the relational model, the cross product (or theta-join or equi-join) of relations whose headings are not disjoint appeared to produce a relation with two attributes of the same name; Codd's solution to this problem in his relational calculus was the use of dot qualification, which was later emulated in SQL (it was later realised that so-called natural join was primitive without loss; that is, natural join can replace all theta-joins and even cross product.)

Source: Business System 12, Notes keyed to slides of the presentation given at TTM Implementers’ Workshop, University of Northumbria, 2-3 June 2011 by Hugh Darwen

Reading a string with spaces with sscanf

I guess this is what you want, it does exactly what you specified.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d cool %s", &age, buffer);
    printf("cool %s is %d years old\n", buffer, age);
    return 0;
}

The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.

Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".

Using Mysql WHERE IN clause in codeigniter

$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query =  $this->db->get();
return $query->result_array();

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

Add vertical whitespace using Twitter Bootstrap?

I know this is old and there are several good solutions already posted, but a simple solution that worked for me is the following CSS

<style>
  .divider{
    margin: 0cm 0cm .5cm 0cm;
  }
</style>

and then create a div in your html

<div class="divider"></div>

Best way to create a simple python web service

Life is simple if you get a good web framework. Web services in Django are easy. Define your model, write view functions that return your CSV documents. Skip the templates.

Angular 2 Sibling Component Communication

This is not what you exactly want but for sure will help you out

I'm surprised there's not more information out there about component communication <=> consider this tutorial by angualr2

For sibling components communication, I'd suggest to go with sharedService. There are also other options available though.

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {NameService} from 'src/nameService';


import {TheContent} from 'src/content';
import {Navbar} from 'src/nav';


@Component({
  selector: 'app',
  directives: [TheContent,Navbar],
  providers: [NameService],
  template: '<navbar></navbar><thecontent></thecontent>'
})


export class App {
  constructor() {
    console.log('App started');
  }
}

bootstrap(App,[]);

Please refer to link at top for more code.

Edit: This is a very small demo. You have already mention that you have already tried with sharedService. So please consider this tutorial by angualr2 for more information.

How to pass a null variable to a SQL Stored Procedure from C#.net code

    SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
    If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
        SQLParam.Value = DBNull.Value
    Else
        SQLParam.Value = p_RetailerID
    End If

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

Which data type for latitude and longitude?

I strongly advocate for PostGis. It's specific for that kind of datatype and it has out of the box methods to calculate distance between points, among other GIS operations that you can find useful in the future

How to cd into a directory with space in the name?

If you want to move from c:\ and you want to go to c:\Documents and settings, write on console: c:\Documents\[space]+tab and cygwin will autocomplete it as c:\Documents\ and\ settings/

How to make child divs always fit inside parent div?

you could use display: inline-block;

hope it is useful.

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
  this.form.complexForm.patchValue(cloneObj);

If you don't want manually set each field.

How to override a JavaScript function

You can override any built-in function by just re-declaring it.

parseFloat = function(a){
  alert(a)
};

Now parseFloat(3) will alert 3.

How do I select a random value from an enumeration?

Here is a generic function for it. Keep the RNG creation outside the high frequency code.

public static Random RNG = new Random();

public static T RandomEnum<T>()
{  
    Type type = typeof(T);
    Array values = Enum.GetValues(type);
    lock(RNG)
    {
        object value= values.GetValue(RNG.Next(values.Length));
        return (T)Convert.ChangeType(value, type);
    }
}

Usage example:

System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();

Convert multidimensional array into single array

Just assign it to it's own first element:

$array = $array[0];

Object Dump JavaScript

Firebug + console.log(myObjectInstance)

Php header location redirect not working

Use the following code:

if(isset($_SERVER['HTTPS']) == 'on')
{

    $self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    ?>

     <script type='text/javascript'>
     window.location.href = 'http://<?php echo $self ?>';
     </script>"
     <?php

     exit();
}
?>

How to see if an object is an array without using reflection?

Simply obj instanceof Object[] (tested on JShell).

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

Is Google Play Store supported in avd emulators?

It's not officially supported yet.

Edit: It's now supported in modern versions of Android Studio, at least on some platforms.

Old workarounds

If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:

  1. Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.

  2. Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk ]. Then use adb install to install the .apk file.

Preloading images with jQuery

I wanted to do this with a Google Maps API custom overlay. Their sample code simply uses JS to insert IMG elements and the image placeholder box is displayed until the image is loaded. I found an answer here that worked for me : https://stackoverflow.com/a/10863680/2095698 .

$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});

This preloads an image as suggested before, and then uses the handler to append the img object after the img URL is loaded. jQuery's documentation warns that cached images don't work well with this eventing/handler code, but it's working for me in FireFox and Chrome, and I don't have to worry about IE.

smooth scroll to top

Pure Javascript only

_x000D_
_x000D_
var t1 = 0;_x000D_
window.onscroll = scroll1;_x000D_
_x000D_
function scroll1() {_x000D_
  var toTop = document.getElementById('toTop');_x000D_
  window.scrollY > 0 ? toTop.style.display = 'Block' : toTop.style.display = 'none';_x000D_
}_x000D_
_x000D_
function abcd() {_x000D_
  var y1 = window.scrollY;_x000D_
  y1 = y1 - 1000;_x000D_
  window.scrollTo(0, y1);_x000D_
  if (y1 > 0) {_x000D_
    t1 = setTimeout("abcd()", 100);_x000D_
  } else {_x000D_
    clearTimeout(t1);_x000D_
  }_x000D_
}
_x000D_
#toTop {_x000D_
  display: block;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 20px;_x000D_
  font-size: 48px;_x000D_
}_x000D_
_x000D_
#toTop {_x000D_
  transition: all 0.5s ease 0s;_x000D_
  -moz-transition: all 0.5s ease 0s;_x000D_
  -webkit-transition: all 0.5s ease 0s;_x000D_
  -o-transition: all 0.5s ease 0s;_x000D_
  opacity: 0.5;_x000D_
  display: none;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
#toTop:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<p>your text here</p>_x000D_
<img id="toTop" src="http://via.placeholder.com/50x50" onclick="abcd()" title="Go To Top">
_x000D_
_x000D_
_x000D_

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

How to get directory size in PHP

function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false && $path!='' && file_exists($path)){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

The same idea as Janith Chinthana suggested. With a few fixes:

  • Converts $path to realpath
  • Performs iteration only if path is valid and folder exists
  • Skips . and .. files
  • Optimized for performance

How to Validate a DateTime in C#?

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
    startDateTextox.Text = DateTime.Today.ToShortDateString();
}

Reasons for preferring this approach:

  • Clearer code (it says what it wants to do)
  • Better performance than catching and swallowing exceptions
  • This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)

How to correctly close a feature branch in Mercurial?

One way is to just leave merged feature branches open (and inactive):

$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
feature-x  41:...
    (2 branches)

$ hg branches -a
default    43:...
    (1 branch)

Another way is to close a feature branch before merging using an extra commit:

$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge

$ hg heads
    (1 head)

$ hg branches
default    43:...
    (1 branch)

The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch, but one should know in advance which commit will be the last one.

Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches and hg heads anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.

Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

Laravel 5 not finding css files

if you are on ubuntu u can try these commands:

sudo apt install npm

npm install && npm run dev

How can I check if an InputStream is empty without reading from it?

public void run() {
    byte[] buffer = new byte[256];  
    int bytes;                      

    while (true) {
        try {
            bytes = mmInStream.read(buffer);
            mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Format date to MM/dd/yyyy in JavaScript

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

_x000D_
_x000D_
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
    alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
_x000D_
_x000D_

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to write an inline IF statement in JavaScript?

<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>

parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );

Create Elasticsearch curl query for not null and not empty("")

The only solution here that worked for me in 5.6.5 was bigstone1998's regex answer. I'd prefer not to use a regex search though for performance reasons. I believe the reason the other solutions don't work is because a standard field will be analyzed and as a result have no empty string token to negate against. The exists query won't help on it's own either since an empty string is considered non-null.

If you can't change the index the regex approach may be your only option, but if you can change the index then adding a keyword subfield will solve the problem.

In the mappings for the index:

"myfield": {
    "type": "text",
    "fields": {
        "keyword": {
            "ignore_above": 256,
            "type": "keyword"
        }
    }
}

Then you can simply use the query:

{
  "query": {
    "bool": {
      "must": {
        "exists": {
          "field": "myfield"
        }
      },
      "must_not": {
        "term": {
          "myfield.keyword": ""
        }
      }
    }
  }
}

Note the .keyword in the must_not component.

C++, how to declare a struct in a header file

You should not place an using directive in an header file, it creates unnecessary headaches.

Also you need an include guard in your header.

EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.

Remove Primary Key in MySQL

One Line:

ALTER TABLE  `user_customer_permission` DROP PRIMARY KEY , ADD PRIMARY KEY (  `id` )

You will also not lose the auto-increment and have to re-add it which could have side-effects.

deleting folder from java

It will delete a folder recursively

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Best way to check if a drop down list contains a value?

Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):

if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Easy way to write contents of a Java InputStream to an OutputStream

Using Guava's ByteStreams.copy():

ByteStreams.copy(inputStream, outputStream);

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

Git error on commit after merge - fatal: cannot do a partial commit during a merge

During a merge Git wants to keep track of the parent branches for all sorts of reasons. What you want to do is not a merge as git sees it. You will likely want to do a rebase or cherry-pick manually.

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

Windows batch script to unhide files hidden by virus

Try this.

Does not require any options to change.

Does not require any command line activity.

Just run software and you will done the job.

www.vhghorecha.in/unhide-all-files-folders-virus/

Happy Knowledge Sharing

Non-alphanumeric list order from os.listdir()

Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:

import re
def sorted_alphanumeric(data):
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(data, key=alphanum_key)

You can now use this function to sort a list:

dirlist = sorted_alphanumeric(os.listdir(...))

PROBLEMS: In case you use the above function to sort strings (for example folder names) and want them sorted like Windows Explorer does, it will not work properly in some edge cases.
This sorting function will return incorrect results on Windows, if you have folder names with certain 'special' characters in them. For example this function will sort 1, !1, !a, a, whereas Windows Explorer would sort !1, 1, !a, a.

So if you want to sort exactly like Windows Explorer does in Python you have to use the Windows built-in function StrCmpLogicalW via ctypes (this of course won't work on Unix):

from ctypes import wintypes, windll
from functools import cmp_to_key

def winsort(data):
    _StrCmpLogicalW = windll.Shlwapi.StrCmpLogicalW
    _StrCmpLogicalW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR]
    _StrCmpLogicalW.restype  = wintypes.INT

    cmp_fnc = lambda psz1, psz2: _StrCmpLogicalW(psz1, psz2)
    return sorted(data, key=cmp_to_key(cmp_fnc))

This function is slightly slower than sorted_alphanumeric().

Bonus: winsort can also sort full paths on Windows.

Alternatively, especially if you use Unix, you can use the natsort library (pip install natsort) to sort by full paths in a correct way (meaning subfolders at the correct position).

You can use it like this to sort full paths:

from natsort import natsorted, ns
dirlist = natsorted(dirlist, alg=ns.PATH | ns.IGNORECASE)

Starting with version 7.1.0 natsort supports os_sorted which internally uses either the beforementioned Windows API or Linux sorting and should be used instead of natsorted().

Android java.exe finished with non-zero exit value 1

There's many reason that leads to

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1

If you are not hitting the dex limit but you are getting error similar to this Error:com.android.dx.cf.iface.ParseException: name already added: string{"a"}

Try disable proguard, if it manage to compile without issue then you will need to figure out which library caused it and add it to proguard-rules.pro file

In my case this issue occur when I updated compile 'com.google.android.gms:play-services-ads:8.3.0' to compile 'com.google.android.gms:play-services-ads:8.4.0'

One of the workaround is I added this to proguard-rules.pro file

## Google AdMob specific rules ##
## https://developers.google.com/admob/android/quick-start ##

-keep public class com.google.ads.** {
   public *;
}

Android Studio

How to access a dictionary element in a Django template?

choices = {'key1':'val1', 'key2':'val2'}

Here's the template:

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
{% endfor %}
</ul>

Basically, .items is a Django keyword that splits a dictionary into a list of (key, value) pairs, much like the Python method .items(). This enables iteration over a dictionary in a Django template.

Multi-statement Table Valued Function vs Inline Table Valued Function

I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

Join a list of items with different types as string in Python

a=[1,2,3]
b=[str(x) for x in a]
print b

above method is the easiest and most general way to convert list into string. another short method is-

a=[1,2,3]
b=map(str,a)
print b

Flutter- wrapping text

In a project of mine I wrap Text instances around Containers. This particular code sample features two stacked Text objects.

Here's a code sample.

    //80% of screen width
    double c_width = MediaQuery.of(context).size.width*0.8;

    return new Container (
      padding: const EdgeInsets.all(16.0),
      width: c_width,
      child: new Column (
        children: <Widget>[
          new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
          new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
        ],
      ),
    );

[edit] Added a width constraint to the container

How do I unbind "hover" in jQuery?

Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):

$("#myElement").unbind('mouseenter mouseleave');

As of jQuery 1.7, you are also able use $.on() and $.off() for event binding, so to unbind the hover event, you would use the simpler and tidier:

$('#myElement').off('hover');

The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off() now allows you to drop both mouse events using the same shorthand.

Edit 2016:

Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:

$('#myElement').off('mouseenter mouseleave');

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

How to detect Windows 64-bit platform with .NET?

UPDATE: As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check Environment.Is64BitOperatingSystem.


IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).

As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.

Microsoft's Raymond Chen: How to detect programmatically whether you are running on 64-bit Windows

My solution:

static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
    [In] IntPtr hProcess,
    [Out] out bool wow64Process
);

public static bool InternalCheckIsWow64()
{
    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
        Environment.OSVersion.Version.Major >= 6)
    {
        using (Process p = Process.GetCurrentProcess())
        {
            bool retVal;
            if (!IsWow64Process(p.Handle, out retVal))
            {
                return false;
            }
            return retVal;
        }
    }
    else
    {
        return false;
    }
}

Windows ignores JAVA_HOME: how to set JDK as default?

This issue is probably because of the earlier versions of Java installed in your System. First check your Environment Variables Carefully and remove all the Environment Variables related to the previous versions of JAVA and replace those paths to

C:\Program Files\Java\<your new jdk version>\bin

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

This is solved for me when I update maven and check the option "Force update of Snapshots/Releases" in Eclipse. this clears all errors. So right click on project -> Maven -> update project, then check the above option -> Ok. Hope this helps you.

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

Finding first blank row, then writing to it

I would have done it like this. Short and sweet :)

Sub test()
Dim rngToSearch As Range
Dim FirstBlankCell As Range
Dim firstEmptyRow As Long

Set rngToSearch = Sheet1.Range("A:A")
    'Check first cell isn't empty
    If IsEmpty(rngToSearch.Cells(1, 1)) Then
        firstEmptyRow = rngToSearch.Cells(1, 1).Row
    Else
        Set FirstBlankCell = rngToSearch.FindNext(After:=rngToSearch.Cells(1, 1))
        If Not FirstBlankCell Is Nothing Then
            firstEmptyRow = FirstBlankCell.Row
        Else
            'no empty cell in range searched
        End If
    End If
End Sub

Updated to check if first row is empty.

Edit: Update to include check if entire row is empty

Option Explicit

Sub test()
Dim rngToSearch As Range
Dim firstblankrownumber As Long

    Set rngToSearch = Sheet1.Range("A1:C200")
    firstblankrownumber = FirstBlankRow(rngToSearch)
    Debug.Print firstblankrownumber

End Sub

Function FirstBlankRow(ByVal rngToSearch As Range, Optional activeCell As Range) As Long
Dim FirstBlankCell As Range

    If activeCell Is Nothing Then Set activeCell = rngToSearch.Cells(1, 1)
    'Check first cell isn't empty
    If WorksheetFunction.CountA(rngToSearch.Cells(1, 1).EntireRow) = 0 Then
        FirstBlankRow = rngToSearch.Cells(1, 1).Row
    Else

        Set FirstBlankCell = rngToSearch.FindNext(After:=activeCell)
        If Not FirstBlankCell Is Nothing Then

            If WorksheetFunction.CountA(FirstBlankCell.EntireRow) = 0 Then
                FirstBlankRow = FirstBlankCell.Row
            Else
                Set activeCell = FirstBlankCell
                FirstBlankRow = FirstBlankRow(rngToSearch, activeCell)

            End If
        Else
            'no empty cell in range searched
        End If
    End If
End Function

How to right-align and justify-align in Markdown?

If you want to right-align in a form, you can try:

| Option | Description |
| ------:| -----------:|
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext    | extension to be used for dest files. |

https://learn.getgrav.org/content/markdown#right-aligned-text

How to disable sort in DataGridView?

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
           dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
      }
}

Case vs If Else If: Which is more efficient?

The debugger is making it simpler, because you don't want to step through the actual code that the compiler creates.

If the switch contains more than five items, it's implemented using a lookup table or hash table, otherwise it's implemeneted using an if..else.

See the closely related question is “else if” faster than “switch() case” ?.

Other languages than C# will of course implement it more or less differently, but a switch is generally more efficient.

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbo' and TABLE_TYPE='BASE TABLE'

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

React JS Error: is not defined react/jsx-no-undef

Here you have not specified class name to be imported from Map.js file. If Map is class exportable class name exist in the Map.js file, your code should be as follow.

import React, { Component } from 'react';
import Map from  './Map';
class App extends Component {
   render() {
     return (
         <div className="App">
            <Map/>
         </div>
     );
   }
}
export default App;

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Change the mouse cursor on mouse over to anchor-like style

If you want to do this in jQuery instead of CSS, you basically follow the same process.

Assuming you have some <div id="target"></div>, you can use the following code:

$("#target").hover(function() {
    $(this).css('cursor','pointer');
}, function() {
    $(this).css('cursor','auto');
});

and that should do it.

How to change the size of the font of a JLabel to take the maximum size

Source Code for Label - How to change Color and Font (in Netbeans)

jLabel1.setFont(new Font("Serif", Font.BOLD, 12));


jLabel1.setForeground(Color.GREEN);