Programs & Examples On #Frp

Functional reactive programming is programming paradigm for reactive programming

What is (functional) reactive programming?

To me it is about 2 different meanings of symbol =:

  1. In math x = sin(t) means, that x is different name for sin(t). So writing x + y is the same thing as sin(t) + y. Functional reactive programming is like math in this respect: if you write x + y, it is computed with whatever the value of t is at the time it's used.
  2. In C-like programming languages (imperative languages), x = sin(t) is an assignment: it means that x stores the value of sin(t) taken at the time of the assignment.

Hello World in Python

print("Hello, World!")

You are probably using Python 3.0, where print is now a function (hence the parenthesis) instead of a statement.

How to define a circle shape in an Android XML drawable file?

This is a simple circle as a drawable in Android.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

   <solid 
       android:color="#666666"/>

   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

css 'pointer-events' property alternative for IE

You can also just "not" add a url inside the <a> tag, i do this for menus that are <a> tag driven with drop downs as well. If there is not drop down then i add the url but if there are drop downs with a <ul> <li> list i just remove it.

Python add item to the tuple

Tuple can only allow adding tuple to it. The best way to do it is:

mytuple =(u'2',)
mytuple +=(new.id,)

I tried the same scenario with the below data it all seems to be working fine.

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')

Reactjs - setting inline styles correctly

Correct and more clear way is :

<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>

It is made more simple by following approach :

// JS
const styleObject = {
      "font-size" : "10px",
      "height" : "100px",
      "width" : "100%"
}

// HTML    
<div style={styleObject}> My inline Style </div>

Inline style attribute expects object. Hence its written in {}, and it becomes double {{}} as one is for default react standards.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Is there an XSL "contains" directive?

there is indeed an xpath contains function it should look something like:

<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

Runtime vs. Compile time

Compile Time:

Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program. Run-Time:

More or less the exact opposite. Little cost when you build, more cost when the program is run.

From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

Redis - Connect to Remote Server

In addition to the excellent answer given by Orabîg:

I resolved this issue by removing the bind section entirely and setting protected-mode to no.

#bind 127.0.0.1
protected-mode no

Never use this method on publicly exposed servers.

Set markers for individual points on a line in Matplotlib

For future reference - the Line2D artist returned by plot() also has a set_markevery() method which allows you to only set markers on certain points - see https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_markevery

MySQL selecting yesterday's date

You can get yesterday's date by using the expression CAST(NOW() - INTERVAL 1 DAY AS DATE). So something like this might work:

SELECT * FROM your_table

WHERE DateVisited >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
  AND DateVisited <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

The easy way to fix this is to add this to your form.

{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">

then the update method will be like this :

public function update(Request $request, $id)
{
    $project = Project::findOrFail($id);
    $project->name = $request->name;
    $project->description = $request->description;

    $post->save();
}

How can I read an input string of unknown length?

Enter while securing an area dynamically

E.G.

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

char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(*str)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(*str)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(*str)*len);
}

int main(void){
    char *m;

    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%s\n", m);

    free(m);
    return 0;
}

How to check if ping responded or not in a batch file

The question was to see if ping responded which this script does.

However this will not work if you get the Host Unreachable message as this returns ERRORLEVEL 0 and passes the check for Received = 1 used in this script, returning Link is UP from the script. Host Unreachable occurs when ping was delivered to target notwork but remote host cannot be found.

If I recall the correct way to check if ping was successful is to look for the string 'TTL' using Find.

@echo off
cls
set ip=%1
ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=win
if errorlevel 1 set error=fail
cls
echo Result: %error%

This wont work with IPv6 networks because ping will not list TTL when receiving reply from IPv6 address.

Simple IEnumerator use (with example)

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  List<string> myList = new List<string>();
  foreach(string str in strings)
  {
      myList.Add(str + "roxxors");
  }
  return myList;
}

or

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  foreach(string str in strings)
  {
      yield return str + "roxxors";
  }
}

using the yield construct, or simply

var newCollection = strings.Select(str => str + "roxxors"); //(*)

or

var newCollection = from str in strings select str + "roxxors"; //(**)

where the two latter use LINQ and (**) is just syntactic sugar for (*).

doGet and doPost in Servlets

Could it be that you are passing the data through get, not post?

<form method="get" ..>
..
</form>

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

    $(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

This code worked pretty good on me, I just had to add the 46 in the controlKeys array to use the period, though I don't thinks is the best way to do it ;)

How to debug heap corruption errors?

In addition to looking for tools, consider looking for a likely culprit. Is there any component you're using, perhaps not written by you, which may not have been designed and tested to run in a multithreaded environment? Or simply one which you do not know has run in such an environment.

The last time it happened to me, it was a native package which had been successfully used from batch jobs for years. But it was the first time at this company that it had been used from a .NET web service (which is multithreaded). That was it - they had lied about the code being thread safe.

How to get random value out of an array?

$rand = rand(1,4);

or, for arrays specifically:

$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];

Adding options to select with javascript

The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.

var firstSelect = document.getElementById('first select elements id'),
    secondSelect = document.getElementById('second select elements id'),
    optionsHTML = [],
    i = 12;

for (; i < 100; i += 1) {
  optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}

firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');

Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.

Rerouting stdin and stdout from C

freopen solves the easy part. Keeping old stdin around is not hard if you haven't read anything and if you're willing to use POSIX system calls like dup or dup2. If you're started to read from it, all bets are off.

Maybe you can tell us the context in which this problem occurs?

I'd encourage you to stick to situations where you're willing to abandon old stdin and stdout and can therefore use freopen.

How to set up ES cluster?

its super easy.

You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.

The only thing you really need to do is edit the config file to include the name of the cluster.

If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)

Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html

When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)

How to remove numbers from a string?

String are immutable, that's why questionText.replace(/[0-9]/g, ''); on it's own does work, but it doesn't change the questionText-string. You'll have to assign the result of the replacement to another String-variable or to questionText itself again.

var cleanedQuestionText = questionText.replace(/[0-9]/g, '');

or in 1 go (using \d+, see Kobi's answer):

 questionText = ("1 ding ?").replace(/\d+/g,'');

and if you want to trim the leading (and trailing) space(s) while you're at it:

 questionText = ("1 ding ?").replace(/\d+|^\s+|\s+$/g,'');

How do I create and access the global variables in Groovy?

Just declare the variable at class or script scope, then access it from inside your methods or closures. Without an example, it's hard to be more specific for your particular problem though.

However, global variables are generally considered bad form.

Why not return the variable from one function, then pass it into the next?

Android Studio Gradle Configuration with name 'default' not found

My solution is to simply remove a line from the settings.gradle file, which represents a module that doesn't exist:

include ':somesdk'

and also remove the corresponding line from the main project's build.gradle:

compile project(':somesdk')

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Android basics: running code in the UI thread

use Handler

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

Javamail Could not convert socket to TLS GMail

I got similar problem when default SSL protocol for sending emails was set to TLSv1 and smtp server was not supporting this protocol anymore. Trick was to use newer protocol:

mail.smtp.ssl.protocols=TLSv1.2

How to set the JSTL variable value in javascript?

This variable can be set using value="${val1}" inside c:set if you have used jquery in your system.

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

Convert floats to ints in Pandas?

The columns that needs to be converted to int can be mentioned in a dictionary also as below

df = df.astype({'col1': 'int', 'col2': 'int', 'col3': 'int'})

How to check if a string contains only digits in Java

Using regular expressions is costly in terms of performance. Trying to parse string as a long value is inefficient and unreliable, and may be not what you need.

What I suggest is to simply check if each character is a digit, what can be efficiently done using Java 8 lambda expressions:

boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I was doing this mistake

ForEach ($server in $servers) {
$OS = Get-WmiObject win32_operatingsystem -ComputerName $server
}

Which, of course, couldn't be passed, because output of the server in a csv file was @{Name=hv1g.contoso.com}

I had to call the property from csv file like this $server.Name

ForEach ($server in $servers) {
$OS = Get-WmiObject win32_operatingsystem -ComputerName $server.Name
}

It fixed my issue.

$(this).serialize() -- How to add a value?

You can write an extra function to process form data and you should add your nonform data as the data valu in the form.seethe example :

<form method="POST" id="add-form">
    <div class="form-group required ">
        <label for="key">Enter key</label>
        <input type="text" name="key" id="key"  data-nonformdata="hai"/>
    </div>
    <div class="form-group required ">
        <label for="name">Ente Name</label>
        <input type="text" name="name" id="name"  data-nonformdata="hello"/>
    </div>
    <input type="submit" id="add-formdata-btn" value="submit">
</form>

Then add this jquery for form processing

<script>
$(document).onready(function(){
    $('#add-form').submit(function(event){
        event.preventDefault();
        var formData = $("form").serializeArray();
        formData = processFormData(formData);
        // write further code here---->
    });
});
processFormData(formData)
{
    var data = formData;
    data.forEach(function(object){
        $('#add-form input').each(function(){
            if(this.name == object.name){
                var nonformData = $(this).data("nonformdata");
                formData.push({name:this.name,value:nonformData});
            }
        });
    });
    return formData;
}

AngularJS open modal on button click

I am not sure,how you are opening popup or say model in your code. But you can try something like this..

<html ng-app="MyApp">
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />

<script type="text/javascript">
    var myApp = angular.module("MyApp", []);
    myApp.controller('MyController', function ($scope) {
      $scope.open = function(){
        var modalInstance = $modal.open({
                        templateUrl: '/assets/yourOpupTemplatename.html',
                        backdrop:'static',
                        keyboard:false,
                        controller: function($scope, $modalInstance) {
                            $scope.cancel = function() {
                                $modalInstance.dismiss('cancel');
                            };
                            $scope.ok = function () {
                              $modalInstance.close();
                            };
                        }
                    });
      }
    });
</script>
</head>
<body ng-controller="MyController">

    <button class="btn btn-primary" ng-click="open()">Test Modal</button>

    <!-- Confirmation Dialog -->
    <div class="modal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title">Delete confirmation</h4>
          </div>
          <div class="modal-body">
            <p>Are you sure?</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="cancel()">No</button>
            <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
          </div>
        </div>
      </div>
    </div>
    <!-- End of Confirmation Dialog -->

 </body>
 </html>

How can I undo a `git commit` locally and on a remote after `git push`

git reset HEAD~1 if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]

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

This is the exit status of the last executed command.

For example the command true always returns a status of 0 and false always returns a status of 1:

true
echo $? # echoes 0
false
echo $? # echoes 1

From the manual: (acessible by calling man bash in your shell)

$?       Expands to the exit status of the most recently executed foreground pipeline.

By convention an exit status of 0 means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.

There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

#ifdef replacement in the Swift language

As of Swift 4.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:

  • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
  • _isReleaseAssertConfiguration() (true when optimization is set to -O) (not available on Swift 3+)
  • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)

e.g.

func obtain() -> AbstractThing {
    if _isDebugAssertConfiguration() {
        return DecoratedThingWithDebugInformation(Thing())
    } else {
        return Thing()
    }
}

Compared with preprocessor macros,

  • ? You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ? Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)

  • ? Using in if/else will always generate a "Will never be executed" warning.

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

How do I sort a VARCHAR column in SQL server that contains numbers?

This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.

SELECT *,
       (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
FROM table_name 
ORDER BY IsNum, LEN(column_name), column_name;

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I would go with Swing. For layout I would use JGoodies form layout. Its worth studying the white paper on the Form Layout here - http://www.jgoodies.com/freeware/forms/

Also if you are going to start developing a huge desktop application, you will definitely need a framework. Others have pointed out the netbeans framework. I didnt like it much so wrote a new one that we now use in my company. I have put it onto sourceforge, but didnt find the time to document it much. Here's the link to browse the code:

http://swingobj.svn.sourceforge.net/viewvc/swingobj/

The showcase should show you how to do a simple logon actually..

Let me know if you have any questions on it I could help.

Functions that return a function

This is super useful in real life.

Working with Express.js

So your regular express route looks like this:

function itWorksHandler( req, res, next ) {
  res.send("It works!");
}

router.get("/check/works", itWorksHandler );

But what if you need to add some wrapper, error handler or smth?

Then you invoke your function off a wrapper.

function loggingWrapper( req, res, next, yourFunction ) {
  try {
    yourFunction( req, res );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", function( req, res, next ) {
  loggingWrapper( req, res, next, itWorksHandler );
});

Looks complicated? Well, how about this:

function function loggingWrapper( yourFunction ) => ( req, res, next ) {
  try {
    yourFunction( req, res, next );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", loggingWrapper( itWorksHandler ) );

See at the end you're passing a function loggingWrapper having one argument as another function itWorksHandler, and your loggingWrapper returns a new function which takes req, res, next as arguments.

Selecting default item from Combobox C#

Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.

How to get whole and decimal part of a number?

Just a new simple solution, for those of you who want to get the Integer part and Decimal part splitted as two integer separated values:

5.25 -> Int part: 5; Decimal part: 25

$num = 5.25;
$int_part = intval($num);
$dec_part = $num * 100 % 100;

This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).

Haven't tested thoroughly with extreme values, but it works fine for me for price calculations.

But, watch out! Now from -5.25 you get: Integer part: -5; Decimal part: -25

In case you want to get always positive numbers, simply add abs() before the calculations:

$num = -5.25;
$num = abs($num);
$int_part = intval($num);
$dec_part = $num * 100 % 100;

Finally, bonus snippet for printing prices with 2 decimals:

$message = sprintf("Your price: %d.%02d Eur", $int_part, $dec_part);

...so that you avoid getting 5.5 instead of 5.05. ;)

Can I change the height of an image in CSS :before/:after pseudo-elements?

Adjusting the background-size is permitted. You still need to specify width and height of the block, however.

.pdflink:after {
    background-image: url('/images/pdf.png');
    background-size: 10px 20px;
    display: inline-block;
    width: 10px; 
    height: 20px;
    content:"";
}

See the full Compatibility Table at the MDN.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

If you start annotating constructor, you must annotate all fields.

Notice, my Staff.name field is mapped to "ANOTHER_NAME" in JSON string.

     String jsonInString="{\"ANOTHER_NAME\":\"John\",\"age\":\"17\"}";
     ObjectMapper mapper = new ObjectMapper();
     Staff obj = mapper.readValue(jsonInString, Staff.class);
     // print to screen

     public static class Staff {
       public String name;
       public Integer age;
       public Staff() {         
       }        

       //@JsonCreator - don't need this
       public Staff(@JsonProperty("ANOTHER_NAME") String   n,@JsonProperty("age") Integer a) {
        name=n;age=a;
       }        
    }

Test if a command outputs an empty string

As mentioned by tripleee in the question comments , use moreutils ifne (if input not empty).

In this case we want ifne -n which negates the test:

ls -A /tmp/empty | ifne -n command-to-run-if-empty-input

The advantage of this over many of the another answers when the output of the initial command is non-empty. ifne will start writing it to STDOUT straight away, rather than buffering the entire output then writing it later, which is important if the initial output is slowly generated or extremely long and would overflow the maximum length of a shell variable.

There are a few utils in moreutils that arguably should be in coreutils -- they're worth checking out if you spend a lot of time living in a shell.

In particular interest to the OP may be dirempty/exists tool which at the time of writing is still under consideration, and has been for some time (it could probably use a bump).

Copy files on Windows Command Line with Progress

robocopy:

Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is robocopy...

Creating JSON on the fly with JObject

Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "@odata.etag". I prefer the indexer initializer syntax in my test cases:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = "2Pac"
};

Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = new JObject
    {
        ["Name"] = "2Pac",
        ["Age"] = 28
    }
};

With object initializer syntax, the above initialization would be:

JObject jsonObject = new JObject
{
    { "Date", DateTime.Now },
    { "Album", "Me Against The World" },
    { "Year", 1995 }, 
    { "Artist", new JObject
        {
            { "Name", "2Pac" },
            { "Age", 28 }
        }
    }
};

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

Sorting a tab delimited file

If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:

tr " " "\t" < <file> | sort <options>

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

Getting data from Yahoo Finance

To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)

To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:

  1. Start at the YQL Console
  2. In the upper left corner, make sure Show Community Tables is checked
  3. Type finance in the search field
  4. You'll see all the Yahoo Finance tables (about 15)

Then you can try some example queries like the following:

select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")

Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables: enter image description here

jQuery append and remove dynamic table row

In addition to the other answers, I'd like to improve the removal, to something more generic:

$(this).closest('tr').remove();

This would be much better than using $(this).parent().parent().remove();, because it doesn't depend on the depth of the element. So, the structure of the row becomes much more flexible.

How can I extract embedded fonts from a PDF as valid font files?

Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

Python dict how to create key or append an element to key?

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

How can I represent a range in Java?

If you are checking against a lot of intervals, I suggest using an interval tree.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

In my case, I deleted out the caniuse-lite, browserslist folders from node_modules.

Then I type the following command to install the packages.

npm i -g browserslist caniuse-lite --save

worked fine.

pip broke. how to fix DistributionNotFound error?

I replaced 0.8.1 in 0.8.2 in /usr/local/bin/pip and everything worked again.

__requires__ = 'pip==0.8.2'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==0.8.2', 'console_scripts', 'pip')()
    )

I installed pip through easy_install which probably caused me this headache. I think this is how you should do it nowadays..

$ sudo apt-get install python-pip python-dev build-essential 
$ sudo pip install --upgrade pip 
$ sudo pip install --upgrade virtualenv

In Node.js, how do I "include" functions from my other files?

Like you are having a file abc.txt and many more?

Create 2 files: fileread.js and fetchingfile.js, then in fileread.js write this code:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

In fetchingfile.js write this code:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

Now, in a terminal: $ node fetchingfile.js --file=abc.txt

You are passing the file name as an argument, moreover include all files in readfile.js instead of passing it.

Thanks

How do I set up Visual Studio Code to compile C++ code?

First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:

  1. Code Runner
  2. C/C++

Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N. To change other features goto user setting. enter image description here

How do I add indices to MySQL tables?

Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.

Explanation

Primary key as index

Consider you have a tbl_student table and you want student_id as primary key:

ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)

Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.

Specify index name

ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)

Above statement will create an ordinary index with student_index name.

Create unique index

ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)

Here, student_unique_index is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).

Fulltext option

ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)

Above statement will create the Fulltext index name with student_fulltext_index, for which you need MyISAM Mysql Engine.

How to remove indexes ?

DROP INDEX `student_index` ON `tbl_student`

How to check available indexes?

SHOW INDEX FROM `tbl_student`

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

c# datagridview doubleclick on row with FullRowSelect

I think you are looking for this: RowHeaderMouseDoubleClick event

private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}

to get the row index:

int indice = e.RowIndex

How do you connect localhost in the Android emulator?

Instead of giving localhost give the IP.

How do I translate an ISO 8601 datetime string into a Python datetime object?

Since Python 3.7 and no external libraries, you can use the strptime function from the datetime module:

datetime.datetime.strptime('2019-01-04T16:41:24+0200', "%Y-%m-%dT%H:%M:%S%z")

For more formatting options, see here.

Python 2 doesn't support the %z format specifier, so it's best to explicitly use Zulu time everywhere if possible:

datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")

Android - Center TextView Horizontally in LinearLayout

Just use: android:layout_centerHorizontal="true"

It will put the whole textview in the center

What is a software framework?

I'm very late to answer it. But, I would like to share one example, which I only thought of today. If I told you to cut a piece of paper with dimensions 5m by 5m, then surely you would do that. But suppose I ask you to cut 1000 pieces of paper of the same dimensions. In this case, you won't do the measuring 1000 times; obviously, you would make a frame of 5m by 5m, and then with the help of it you would be able to cut 1000 pieces of paper in less time. So, what you did was make a framework which would do a specific type of task. Instead of performing the same type of task again and again for the same type of applications, you create a framework having all those facilities together in one nice packet, hence providing the abstraction for your application and more importantly many applications.

NGinx Default public www location?

For CentOS, Ubuntu and Fedora, the default directory is /usr/share/nginx/html

Git submodule update

This GitPro page does summarize the consequence of a git submodule update nicely

When you run git submodule update, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.


Note March 2013:

As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 
# or (with rebase)
git submodule update --rebase --remote

See "git submodule update --remote vs git pull".

MindTooth's answer illustrate a manual update (without local configuration):

git submodule -q foreach git pull -q origin master

In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.

The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).


To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:


So, to answer your questions:

can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?

You can create a branch and push modifications.

WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.

how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)

The page "Understanding Submodules" can help

Git submodules are implemented using two moving parts:

  • the .gitmodules file and
  • a special kind of tree object.

These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.


From the git submodule page

you cannot modify the contents of the submodule from within the main project

100% correct: you cannot modify a submodule, only refer to one of its commits.

This is why, when you do modify a submodule from within the main project, you:

  • need to commit and push within the submodule (to the upstream module), and
  • then go up in your main project, and re-commit (in order for that main project to refer to the new submodule commit you just created and pushed)

A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").

A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.

However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.

But the main idea remains: referencing specific components which:

  • have their own lifecycle
  • have their own set of tags
  • have their own development

The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)

If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.

Does that help understanding the true nature of Git Submodules?

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal class from the tutorial you were reading.

First of all your Animal class with the Json Annotations for the subclasses.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "Dog"),

    @JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {

    private String name;

    public String getName() {
        return name;
    }

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

}

Then your subclasses, Dog and Cat.

public class Dog extends Animal {

    private String breed;

    public Dog() {

    }

    public Dog(String name, String breed) {
        setName(name);
        setBreed(breed);
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }
}

public class Cat extends Animal {

    public String getFavoriteToy() {
        return favoriteToy;
    }

    public Cat() {}

    public Cat(String name, String favoriteToy) {
        setName(name);
        setFavoriteToy(favoriteToy);
    }

    public void setFavoriteToy(String favoriteToy) {
        this.favoriteToy = favoriteToy;
    }

    private String favoriteToy;

}

As you can see, there is nothing special for Cat and Dog, the only one that know about them is the abstract class Animal, so when deserializing, you'll target to Animal and the ObjectMapper will return the actual instance as you can see in the following test:

public class Test {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        Animal myDog = new Dog("ruffus","english shepherd");

        Animal myCat = new Cat("goya", "mice");

        try {
            String dogJson = objectMapper.writeValueAsString(myDog);

            System.out.println(dogJson);

            Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);

            System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());

            String catJson = objectMapper.writeValueAsString(myCat);

            Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);

            System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Output after running the Test class:

{"@type":"Dog","name":"ruffus","breed":"english shepherd"}

Deserialized dogJson Class: Dog

{"@type":"Cat","name":"goya","favoriteToy":"mice"}

Deserialized catJson Class: Cat

Hope this helps,

Jose Luis

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

Can't concatenate 2 arrays in PHP

It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.

Instead you must use array_merge()

$array = array_merge(array('Item 1'), array('Item 2'));

Docker - Container is not running

For anyone attempting something similar using a Dockerfile...

Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.

In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash

This would get you the interactive login you're looking for.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long is equivalent to long int, just as short is equivalent to short int. A long int is a signed integral type that is at least 32 bits, while a long long or long long int is a signed integral type is at least 64 bits.

This doesn't necessarily mean that a long long is wider than a long. Many platforms / ABIs use the LP64 model - where long (and pointers) are 64 bits wide. Win64 uses the LLP64, where long is still 32 bits, and long long (and pointers) are 64 bits wide.

There's a good summary of 64-bit data models here.

long double doesn't guarantee much other than it will be at least as wide as a double.

Refresh certain row of UITableView based on Int in Swift

In Swift 3.0

let rowNumber: Int = 2
let sectionNumber: Int = 0

let indexPath = IndexPath(item: rowNumber, section: sectionNumber)

self.tableView.reloadRows(at: [indexPath], with: .automatic)

byDefault, if you have only one section in TableView, then you can put section value 0.

error: package com.android.annotations does not exist

To automatically fix all android to androidx issues for React Native (prerequisite npx)

Add the following two flags to true in your gradle.properties file at ProjectFolder/android/gradle.properties

android.useAndroidX=true
android.enableJetifier=true

Execute

npm install --save-dev jetifier
npx jetify
npx react-native run-android

In your package.json add the following to scripts

  "postinstall" : "npx jetify"

More info at https://github.com/mikehardy/jetifier

Update: This is now in-built in react-native 0.60. If you migrate to react-native 0.60 you won't need this step. - https://facebook.github.io/react-native/blog/2019/07/03/version-60#androidx-support

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

In your apache's httpd.conf, just add such a line:

AddType application/x-javascript .js

How to write unit testing for Angular / TypeScript for private methods with Jasmine

This worked for me:

Instead of:

sut.myPrivateMethod();

This:

sut['myPrivateMethod']();

How to create dispatch queue in Swift 3

Compiles under >=Swift 3. This example contains most of the syntax that we need.

QoS - new quality of service syntax

weak self - to disrupt retain cycles

if self is not available, do nothing

async global utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

Of course, you need to add some error checking to this...

DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in

    guard let strongSelf = self else { return }

    strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in

        if error != nil {
            print("error:\(error)")
        } else {
            DispatchQueue.main.async { () -> Void in
                activityIndicator.removeFromSuperview()
                strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
            }
        }
    }
}

Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

 <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>

checkit out

Angular 2 - Setting selected value on dropdown list

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I ran into a similar problem with the same error message using following code:

@Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())

I found a good answer here

Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

Be sure to import the following lib into your model:

using System.ComponentModel.DataAnnotations;

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

String.replaceAll single backslashes with double backslashes

To avoid this sort of trouble, you can use replace (which takes a plain string) instead of replaceAll (which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

If (Array.Length == 0)

This is the best way. Please note Array is an object in NET so you need to check for null before.

Cannot bulk load because the file could not be opened. Operating System Error Code 3

Using SQL connection via Windows Authentication: A "Kerberos double hop" is happening: one hop is your client application connecting to the SQL Server, a second hop is the SQL Server connecting to the remote "\\NETWORK_MACHINE\". Such a double hop falls under the restrictions of Constrained Delegation and you end up accessing the share as Anonymous Login and hence the Access Denied.

To resolve the issue you need to enable constrained delegation for the SQL Server service account. See here for a good post that explains it quite well

SQL Server using SQL Authentication You need to create a credential for your SQL login and use that to access that particular network resource. See here

Anybody knows any knowledge base open source?

I believe that phpMyFAQ is the most useful KB I have seen so far ( from open-source ). It is simple, straight-forward KB software, is it PHP => can be easily installed on any server and can be customized if you know a bit of php. In addition it is made simple enough but with correct priorities and logic. I suggest to install it and play with it, I did and I decided to stay with this KB.

Send POST request using NSURLSession

Swift 2.0 solution is here:

 let urlStr = “http://url_to_manage_post_requests” 
 let url = NSURL(string: urlStr) 
 let request: NSMutableURLRequest =
 NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
 request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
 request.timeoutInterval = 60.0 
 //additional headers
 request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)

 let bodyStr = “string or data to add to body of request” 
 let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
 request.HTTPBody = bodyData

 let session = NSURLSession.sharedSession()

 let task = session.dataTaskWithRequest(request){
             (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

             if let httpResponse = response as? NSHTTPURLResponse {
                print("responseCode \(httpResponse.statusCode)")
             }

            if error != nil {

                 // You can handle error response here
                 print("\(error)")
             }else {
                  //Converting response to collection formate (array or dictionary)
                 do{
                     let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:
 NSJSONReadingOptions.MutableContainers))

                     //success code
                 }catch{
                     //failure code
                 }
             }
         }

   task.resume()

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

UPDATE with CASE and IN - Oracle

Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

So my final code looks like this ($bp_gr1' are strings like 1,2,3):

UPDATE TAB1
SET    BUDGPOST_GR1 =
          CASE
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR1'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR2'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR3'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR4'
             ELSE
                'SAKNAR BUDGETGRUPP'
          END;

Is there a way to make it run faster?

iterating through json object javascript

An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:

var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
  jDepthLvl++;
  if (isIterable(object)) {
    if(objectAccessor === null) {
      console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
    } else
      console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
    forEachIn(object, function (accessor, child) {
      visit(child, accessor);
    });
  } else {
    var value = object;
    console.log("%c"
      + spacesDepth(jDepthLvl)
      + objectAccessor + "[%c" + value + "%c] "
      ,"color:blue","color:red","color:blue");
  }
  if(objectAccessor === null) {
    console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
  }
  jDepthLvl--;
}

function spacesDepth(jDepthLvl) {
  let jSpc="";
  for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
    jSpc+="\u0020\u0020"
  }
  return jSpc;
}

function forEachIn(iterable, functionRef) {
  for (var accessor in iterable) {
    functionRef(accessor, iterable[accessor]);
  }
}

function isIterable(element) {
  return isArray(element) || isObject(element);
}

function isArray(element) {
  return element.constructor == Array;
}

function isObject(element) {
  return element.constructor == Object;
}


visit($OBJECT_OR_ARRAY$);

Console Output using JSON from @eric

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

What does "hashable" mean in Python?

In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.

This is why Python requires us to use immutable datatypes for the keys in a dictionary.

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

How to echo (or print) to the js console with php

<?php  echo "<script>console.log({$yourVariable})</script>"; ?>

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Rather than using JavaScript perhaps try something like

<a href="#">

  <input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />

</a>

Adding an onclick event to a table row

I think for IE you will need to use the srcElement property of the Event object. if jQuery is an option for you, you may want to consider using it - as it abstracts most browser differences for you. Example jQuery:

$("#tableId tr").click(function() {
   alert($(this).children("td").html());
});

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

Open File in Another Directory (Python)

from pathlib import Path

data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)
print(f.read())

jQuery counting elements by class - what is the best way to implement this?

HTML:

<div>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>

    

JavaScript:

var numItems = $('.class').length; 
        
alert(numItems);

Fiddle demo for inside only div

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

load csv into 2D matrix with numpy for plotting

I think using dtype where there is a name row is confusing the routine. Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])

MySQL Sum() multiple columns

The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?

If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.

Then your query would be

SELECT subject, SUM(mark) total 
FROM Subjects s 
  INNER JOIN Marks m ON m.subject_id = s.id
GROUP BY s.id

make div's height expand with its content

I tried this and it worked

<div style=" position: absolute; direction: ltr;height:auto; min-height:100%">   </div>

How to redraw DataTable with new data

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20

How do I get the key at a specific index from a Dictionary in Swift?

I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.

My initial thought was to wrap my dictionary in an Array. [[String: UIImage]] but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0. No more converting it to an Array. Just my 2 cents.

Complexities of binary tree traversals

Depth first traversal of a binary tree is of order O(n).

Algo -- <b>
    PreOrderTrav():-----------------T(n)<b>
    if root is null---------------O(1)<b>
      return null-----------------O(1)<b>
    else:-------------------------O(1)<b>
      print(root)-----------------O(1)<b>
      PreOrderTrav(root.left)-----T(n/2)<b>
      PreOrderTrav(root.right)----T(n/2)<b>

If the time complexity of the algo is T(n) then it can be written as T(n) = 2*T(n/2) + O(1). If we apply back substitution we will get T(n) = O(n).

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

How to stop/shut down an elasticsearch node?

For Mac users using Homebrew (Brew) to install and manage services:

List your Brew services:

brew services

Do something with a service:

brew services start elasticsearch-full
brew services restart elasticsearch-full
brew services stop elasticsearch-full

How do I format a number to a dollar amount in PHP

In php.ini add this (if it is missing):

#windows
extension=php_intl.dll

#linux
extension=php_intl.so

Then do this:

$amount = 123.456;

// for Canadian Dollars
$currency = 'CAD';

// for Canadian English
$locale = 'en_CA';

$fmt = new \NumberFormatter( $locale, \NumberFormatter::CURRENCY );
echo $fmt->formatCurrency($amount, $currency);

Python list iterator behavior and next(iterator)

Something is wrong with your Python/Computer.

a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

>>> 
0
2
4
6
8

Works like expected.

Tested in Python 2.7 and in Python 3+ . Works properly in both

How to easily duplicate a Windows Form in Visual Studio?

  • Save the all project
  • Right click in the Solution Explorer (SE), "Copy"
  • Right click on the project name in the SE (this is the first line), "Paste". It will create a "Copy of .....vb" form
  • Right click on this new form in SE, "View code", and change its class name to the name, that you wanna use for the Form
  • Left click on the new form in SE and rewrite its name for the one, that you used in the class name (and .vb in the end)
  • Build - if it has no error, you win! :)

Left align block of equations

The fleqn option in the document class will apply left aligning setting in all equations of the document. You can instead use \begin{flalign}. This will align only the desired equations.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

Your problem is that you load an external image, meaning from another domain. This causes a security error when you try to access any data of your canvas context.

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

how to get javaScript event source element?

USE .live()

 $(selector).live(events, data, handler); 

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$(document).on(events, selector, data, handler);  

I can't install intel HAXM

I've figured out. Try to disable Security Boot Control in BIOS options: http://remontka.pro/secure-boot-disable/ (sorry for russian examples) Or try to start system without Digital signature (only for one loading). I had had many unlucky attempts with 'HAXM installer, before I disabled this line. At the beginning I thought that's because Windows 10 Home was installed, and there're many limits.

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

MISCONF Redis is configured to save RDB snapshots

If you are running Redis locally on a windows machine, try to "run as administrator" and see if it works. With me, the problem was that Redis was located in the "Program Files" folder, which restricts permissions by default. As it should.

However, do not automatically run Redis as an administrator You don't want to grant it more rights that it is supposed to have. You want to solve this by the book.

So, we have been able to quickly identify the problem by running it as an administrator, but this is not the cure. A likely scenario is that you have put Redis in a folder that doesn't have write rights and as a consequence the DB file is stored in that same location.

You can solve this by opening the redis.windows.conf and to search for the following configuration:

    # The working directory.
    #
    # The DB will be written inside this directory, with the filename specified
    # above using the 'dbfilename' configuration directive.
    #
    # The Append Only File will also be created inside this directory.
    #
    # Note that you must specify a directory here, not a file name.
    dir ./

Change dir ./ to a path you have regular read/write permissions for

You could also just move the Redis folder in it's entirety to a folder you know has the right permissions.

Python Database connection Close

According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.

To close your connection when you call close() you should set pooling to False:

import pyodbc

pyodbc.pooling = False

Get property value from string using reflection

Have a look at the Heleonix.Reflection library. You can get/set/invoke members by paths, or create a getter/setter (lambda compiled into a delegate) which is faster than reflection. For example:

var success = Reflector.Get(DateTime.Now, null, "Date.Year", out int value);

Or create a getter once and cache for reuse (this is more performant but might throw NullReferenceException if an intermediate member is null):

var getter = Reflector.CreateGetter<DateTime, int>("Date.Year", typeof(DateTime));
getter(DateTime.Now);

Or if you want to create a List<Action<object, object>> of different getters, just specify base types for compiled delegates (type conversions will be added into compiled lambdas):

var getter = Reflector.CreateGetter<object, object>("Date.Year", typeof(DateTime));
getter(DateTime.Now);

Share cookie between subdomain and domain

Simple solution

setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);

Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )

Reference: http://php.net/manual/en/function.setcookie.php

Accessing Websites through a Different Port?

A simple way is to got to http://websitename.com:174, and you will be entering through a different port.

All possible array initialization syntaxes

Non-empty arrays

  • var data0 = new int[3]

  • var data1 = new int[3] { 1, 2, 3 }

  • var data2 = new int[] { 1, 2, 3 }

  • var data3 = new[] { 1, 2, 3 }

  • var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.

Empty arrays

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } and int[] data9 = new [] { } are not compilable.

  • var data10 = { } is not compilable. Use int[] data11 = { } instead.

As an argument of a method

Only expressions that can be assigned with the var keyword can be passed as arguments.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) is not compilable
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) is not compilable

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

Extracting just Month and Year separately from Pandas Datetime column

Thanks to jaknap32, I wanted to aggregate the results according to Year and Month, so this worked:

df_join['YearMonth'] = df_join['timestamp'].apply(lambda x:x.strftime('%Y%m'))

Output was neat:

0    201108
1    201108
2    201108

How to validate IP address in Python?

From Python 3.4 on, the best way to check if an IPv6 or IPv4 address is correct, is to use the Python Standard Library module ipaddress - IPv4/IPv6 manipulation library s.a. https://docs.python.org/3/library/ipaddress.html for complete documentation.

Example :

#!/usr/bin/env python

import ipaddress
import sys

try:
    ip = ipaddress.ip_address(sys.argv[1])
    print('%s is a correct IP%s address.' % (ip, ip.version))
except ValueError:
    print('address/netmask is invalid: %s' % sys.argv[1])
except:
    print('Usage : %s  ip' % sys.argv[0])

For other versions: Github, phihag / Philipp Hagemeister,"Python 3.3's ipaddress for older Python versions", https://github.com/phihag/ipaddress

The backport from phihag is available e.g. in Anaconda Python 2.7 & is included in Installer. s.a. https://docs.continuum.io/anaconda/pkg-docs

To install with pip:

pip install ipaddress

s.a.: ipaddress 1.0.17, "IPv4/IPv6 manipulation library", "Port of the 3.3+ ipaddress module", https://pypi.python.org/pypi/ipaddress/1.0.17

Reading rows from a CSV file in Python

Reading it columnwise is harder?

Anyway this reads the line and stores the values in a list:

for line in open("csvfile.csv"):
    csv_row = line.split() #returns a list ["1","50","60"]

Modern solution:

# pip install pandas
import pandas as pd 
df = pd.read_table("csvfile.csv", sep=" ")

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

Scanner is never closed

Here is some better usage of java for scanner

try(Scanner sc = new Scanner(System.in)) {

    //Use sc as you need

} catch (Exception e) {

        //  handle exception

}

MySQL search and replace some text in a field

Change table_name and field to match your table name and field in question:

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;

Python regex findall

Use this pattern,

pattern = '\[P\].+?\[\/P\]'

Check here

How can I parse a YAML file in Python

#!/usr/bin/env python

import sys
import yaml

def main(argv):

    with open(argv[0]) as stream:
        try:
            #print(yaml.load(stream))
            return 0
        except yaml.YAMLError as exc:
            print(exc)
            return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Convert a list of characters into a string

You could also use operator.concat() like this:

>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'

If you're using Python 3 you need to prepend:

>>> from functools import reduce

since the builtin reduce() has been removed from Python 3 and now lives in functools.reduce().

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

How to get the IP address of the server on which my C# application is running on?

I just thought that I would add my own, one-liner (even though there are many other useful answers already).


string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

Why would one omit the close tag?

It's pretty useful not to let the closing ?> in.

The file stays valid to PHP (not a syntax error) and as @David Dorward said it allows to avoid having white space / break-line (anything that can send a header to the browser) after the ?>.

For example,

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10);
    imagepng ( $img);
?>
[space here]
[break line here]

won't be valid.

But

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10 );
    imagepng ( $img );

will.

For once, you must be lazy to be secure.

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

This happenes might be because you ran out of disk storage and the mysql files and starting files got corrupted

The solution to be tried as below

First we will move the tmp file to somewhere with larger space

Step 1: Copy your existing /etc/my.cnf file to make a backup

cp /etc/my.cnf{,.back-`date +%Y%m%d`}

Step 2: Create your new directory, and set the correct permissions

mkdir /home/mysqltmpdir
chmod 1777 /home/mysqltmpdir

Step 3: Open your /etc/my.cnf file

nano /etc/my.cnf

Step 4: Add below line under the [mysqld] section and save the file

tmpdir=/home/mysqltmpdir

Secondly you need to remove or error files and logs from the /var/lib/mysql/ib_* that means to remove anything that starts by "ib"

rm /var/lib/mysql/ibdata1 and rm /var/lib/mysql/ibda.... and so on

Thirdly you will need to make sure that there is a pid file available to have the database to write in

Step 1 you need to edit /etc/my.cnf

pid-file= /var/run/mysqld/mysqld.pid 

Step 2 create the directory with the file to point to

 mkdir /var/run/mysqld
 touch /var/run/mysqld/mysqld.pid
 chown -R mysql:mysql /var/run/mysqld

Last step restart mysql server

/etc/init.d/mysql restart

Chrome ignores autocomplete="off"

Seen chrome ignore the autocomplete="off", I solve it with a stupid way which is using "fake input" to cheat chrome to fill it up instead of filling the "real" one.

Example:

<input type="text" name="username" style="display:none" value="fake input" /> 
<input type="text" name="username" value="real input"/>

Chrome will fill up the "fake input", and when submit, server will take the "real input" value.

Difference between abstract class and interface in Python

For completeness, we should mention PEP3119 where ABC was introduced and compared with interfaces, and original Talin's comment.

The abstract class is not perfect interface:

  • belongs to the inheritance hierarchy
  • is mutable

But if you consider writing it your own way:

def some_function(self):
     raise NotImplementedError()

interface = type(
    'your_interface', (object,),
    {'extra_func': some_function,
     '__slots__': ['extra_func', ...]
     ...
     '__instancecheck__': your_instance_checker,
     '__subclasscheck__': your_subclass_checker
     ...
    }
)

ok, rather as a class
or as a metaclass
and fighting with python to achieve the immutable object
and doing refactoring
...

you'll quite fast realize that you're inventing the wheel to eventually achieve abc.ABCMeta

abc.ABCMeta was proposed as a useful addition of the missing interface functionality, and that's fair enough in a language like python.

Certainly, it was able to be enhanced better whilst writing version 3, and adding new syntax and immutable interface concept ...

Conclusion:

The abc.ABCMeta IS "pythonic" interface in python

How to read keyboard-input?

It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:

nb = input('Choose a number: ')

The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:

nb = raw_input('Choose a number: ')

If you want to convert that to a number, then you should try:

number = int(nb)

... though you need to take into account that this can raise an exception:

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

And if you want to print the number using formatting, in Python 3 str.format() is recommended:

print("Number: {0}\n".format(number))

Instead of:

print('Number %s \n' % (nb))

But both options (str.format() and %) do work in both Python 2.7 and Python 3.

How to move a marker in Google Maps API

Just try to create the marker and set the draggable property to true. The code will be something as follows:

Marker = new google.maps.Marker({
    position: latlon,
    map: map,            
    draggable: true,
    title: "Drag me!"
});

I hope this helps!

twitter bootstrap text-center when in xs mode

Css Part is:

CSS:

@media (max-width: 767px) {

  // Align text to center.
  .text-xs-center {
    text-align: center;
  } 
}

And the HTML part will be ( this text center work only below 767px width )

HTML:

 <div class="col-xs-12 col-sm-6 text-right text-xs-center">
        <p>
            <a href="#"><i class="fa fa-facebook"></i></a> 
            <a href="#"><i class="fa fa-twitter"></i></a> 
            <a href="#"><i class="fa fa-google-plus"></i></a>
        </p>
 </div>

EOFException - how to handle?

You may come across code that reads from an InputStream and uses the snippet while(in.available()>0) to check for the end of the stream, rather than checking for an EOFException (end of the file).

The problem with this technique, and the Javadoc does echo this, is that it only tells you the number of blocks that can be read without blocking the next caller. In other words, it can return 0 even if there are more bytes to be read. Therefore, the InputStream available() method should never be used to check for the end of the stream.

You must use while (true) and

catch(EOFException e) {
//This isn't problem
} catch (Other e) {
//This is problem
}

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

How to find out which package version is loaded in R?

Use the R method packageDescription to get the installed package description and for version just use $Version as:

packageDescription("AppliedPredictiveModeling")$Version
[1] "1.1-6"

WebView and HTML5 <video>

I know this thread is several months old, but I found a solution for playing the video inside the WebView without doing it fullscreen (but still in the media player...). So far, I didn't find any hint on this in the internet so maybe this is also interesting for others. I'm still struggling on some issues (i.e. placing the media player in the right section of the screen, don't know why I'm doing it wrong but it's a relatively small issue I think...).

In the Custom ChromeClient specify LayoutParams:

// 768x512 is the size of my video
FrameLayout.LayoutParams LayoutParameters = 
                                     new FrameLayout.LayoutParams (768, 512); 

My onShowCustomView method looks like this:

public void onShowCustomView(final View view, final CustomViewCallback callback) {
     // super.onShowCustomView(view, callback);
     if (view instanceof FrameLayout) {
         this.mCustomViewContainer = (FrameLayout) view;
         this.mCustomViewCallback = callback;
         this.mContentView = (WebView) this.kameha.findViewById(R.id.webview);
         if (this.mCustomViewContainer.getFocusedChild() instanceof VideoView) {
             this.mCustomVideoView = (VideoView) 
                                     this.mCustomViewContainer.getFocusedChild();
             this.mCustomViewContainer.setVisibility(View.VISIBLE);
             final int viewWidth = this.mContentView.getWidth();
             final int viewLeft = (viewWidth - 1024) / 2;
             // get the x-position for the video (I'm porting an iPad-Webapp to Xoom, 
             // so I can use those numbers... you have to find your own of course...
             this.LayoutParameters.leftMargin = viewLeft + 256; 
             this.LayoutParameters.topMargin = 128;
             // just add this view so the webview underneath will still be visible, 
             // but apply the LayoutParameters specified above
             this.kameha.addContentView(this.mCustomViewContainer, 
                                             this.LayoutParameters); 
             this.mCustomVideoView.setOnCompletionListener(this);
             this.mCustomVideoView.setOnErrorListener(this);
             // handle clicks on the screen (turning off the video) so you can still
             // navigate in your WebView without having the video lying over it
             this.mCustomVideoView.setOnFocusChangeListener(this); 
             this.mCustomVideoView.start();
         }
     }
 }

So, I hope I could help... I too had to play around with video-Encoding and saw different kinds of using the WebView with html5 video - in the end my working code was a wild mix of different code-parts I found in the internet and some things I had to figure out by myself. It really was a pain in the a*.

Python variables as keys to dict

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

System.Net.Http: missing from namespace? (using .net 4.5)

Making the "Copy Local" property True for the reference did it for me. Expand References, right-click on System.Net.Http and change the value of Copy Local property to True in the properties window. I'm using VS2019.

Get public/external IP address?

Or this, it works quite well i think for what i needed. It's from here.

public IPAddress GetExternalIP()
{
    WebClient lol = new WebClient();
    string str = lol.DownloadString("http://www.ip-adress.com/");
    string pattern = "<h2>My IP address is: (.+)</h2>"
    MatchCollection matches1 = Regex.Matches(str, pattern);
    string ip = matches1(0).ToString;
    ip = ip.Remove(0, 21);
    ip = ip.Replace("

    ", "");
    ip = ip.Replace(" ", "");
    return IPAddress.Parse(ip);
}

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

How to hide html source & disable right click and text copy?

You cannot effectively hide your HTML and JavaScript code, even if you encrypt or minify it.

If the code you're trying to hide is really sensitive, it should either be in a protected area of the site, i.e. an area that you can only access via a username and password, or potentially in a client application that isn't exposed via the web.

If you have to expose the application functionality via a web frontend, you could use Silverlight to write the frontend or bits of the frontend. In the old days you could also use ActiveX.

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

How to horizontally center an unordered list of unknown width?

It depends on if you mean the list items are below the previous or to the right of the previous, ie:

Home
About
Contact

or

Home | About | Contact

The first one you can do simply with:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }

The second could be done like this:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }
#footer li { display: inline; }
#footer a { padding: 2px 12px; background: orange; text-decoration: none; }
#footer a:hover { background: green; color: yellow; }

How do I specify "close existing connections" in sql script

You can disconnect everyone and roll back their transactions with:

alter database [MyDatbase] set single_user with rollback immediate

After that, you can safely drop the database :)

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

What is the best way to calculate a checksum for a file that is on my machine?

The CertUtil is a pre-installed Windows utility, that can be used to generate hash checksums:

CertUtil -hashfile pathToFileToCheck [HashAlgorithm]

HashAlgorithm choices: MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512

So for example, the following generates an MD5 checksum for the file C:\TEMP\MyDataFile.img:

CertUtil -hashfile C:\TEMP\MyDataFile.img MD5

To get output similar to *Nix systems you can add some PS magic:

$(CertUtil -hashfile C:\TEMP\MyDataFile.img MD5)[1] -replace " ",""

How do I convert NSInteger to NSString datatype?

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

sql searching multiple words in a string

Select * from table where 
  columnname like'%David%' and 
  columnname like '%Moses%' and columnname like'%Robi%' 

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

How can I completely remove TFS Bindings

Sometime, the binding info is cached

To clear Team Explorer's cache:

Go to C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\2.0
Delete or rename the Cache folder.

This come from a website I could not find now. Thanks for that guy for the tip.

How to see full absolute path of a symlink

Another way to see information is stat command that will show more information. Command stat ~/.ssh on my machine display

File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
  Size: 34          Blocks: 0          IO Block: 4096   symbolic link
Device: 801h/2049d  Inode: 25297409    Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/   sumon)   Gid: ( 1000/   sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
 Birth: -

Hope this may help someone.

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

What causes a TCP/IP reset (RST) flag to be sent?

A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...

One reason a device will send a RST is in response to receiving a packet for a closed socket.

It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)

How to access the ith column of a NumPy multidimensional array?

>>> test
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

>>> ncol = test.shape[1]
>>> ncol
5L

Then you can select the 2nd - 4th column this way:

>>> test[0:, 1:(ncol - 1)]
array([[1, 2, 3],
       [6, 7, 8]])

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

HTML5 input type range show range value

Shortest version without form, min or external JavaScript.

_x000D_
_x000D_
<input type="range" value="0" max="10" oninput="num.value = this.value">
<output id="num">0</output>
_x000D_
_x000D_
_x000D_

Explanation

If you wanna retrieve the value from the output you commonly use an id that can be linked from the oninput instead of using this.nextElementSibling.value (we take advantage of something that we are already using)

Compare the example above with this valid but a little more complex and long answer:

<input id="num" type="range" value="0" max="100" oninput="this.nextElementSibling.value = this.value">
<output>0</output>

With the shortest answer:

  • We avoid the use of this, something weird in JS for newcomers
  • We avoid new concept about connecting siblings in the DOM
  • We avoid too much attributes in the input placing the id in the output

Notes

  • In both examples we don't need to add the min value when equal to 0
  • Removing JavaScript’s this keyword makes it a better language

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

How to return rows from left table not found in right table?

I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).

DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

SELECT l.*
FROM 
    @testLeft l
     LEFT JOIN 
    @testRight r ON 
        l.ID = r.ID
WHERE r.ID IS NULL 

How can I connect to a Tor hidden service using cURL in PHP?

TL;DR: Set CURLOPT_PROXYTYPE to use CURLPROXY_SOCKS5_HOSTNAME if you have a modern PHP, the value 7 otherwise, and/or correct the CURLOPT_PROXY value.

As you correctly deduced, you cannot resolve .onion domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.

Using CURLPROXY_SOCKS5 will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion address unless it, too, is specifically forwarding such queries to Tor.

Instead of CURLPROXY_SOCKS5, you must use CURLPROXY_SOCKS5_HOSTNAME. Alternatively, you can also use CURLPROXY_SOCKS4A, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion domain.

There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:

  • Missing semicolon at end of line 1.
  • The proxy address value is set to an HTTP URL, but its type is SOCKS; these are incompatible. For SOCKS proxies, the value must be an IP or domain name and port number combination without a scheme/protocol/prefix.

Here is the correct code in full, with comments to indicate the changes.

<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);

You can also omit setting CURLOPT_PROXYTYPE entirely by changing the CURLOPT_PROXY value to include the socks5h:// prefix:

// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');

Create a directory if it doesn't exist

#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
    
namespace fs = std::experimental::filesystem;


if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
    fs::create_directory("src"); // create src folder
}

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:

$var = new YourClass();
$var->method();

You can also use the new way to do the same since PHP 5.4:

(new YourClass)->method();

I hope it helps you!

How do I automatically resize an image for a mobile site?

if you use bootstrap 3 , just add img-responsive class in your img tag

<img class="img-responsive"  src="...">

if you use bootstrap 4, add img-fluid class in your img tag

<img class="img-fluid"  src="...">

which does the staff: max-width: 100%, height: auto, and display:block to the image

Angular 2 Hover event

For handling the event on overing, you can try something like this (it works for me):

In the Html template:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

In the angular component:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

Configure Log4net to write to multiple files

I wanted to log all messages to root logger, and to have a separate log with errors, here is how it can be done:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="allMessages.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
    </appender>

    <appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
        <file value="errorsLog.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="FileAppender" />
        <appender-ref ref="ErrorsFileAppender" />
    </root>
</log4net>

Notice the use of filter element.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

jQuery get mouse position within an element

To get the position of click relative to current clicked element
Use this code

$("#specialElement").click(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
}); 

Convert JavaScript String to be all lower case?

Opt 1: using toLowerCase()

var x = 'ABC';
x = x.toLowerCase();

Opt 2: Using your own function

function convertToLowerCase(str) {
  var result = '';

  for (var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code > 64 && code < 91) {
      result += String.fromCharCode(code + 32);
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

Call it as:

x = convertToLowerCase(x);

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

Modify request parameter with servlet filter

For the record, here is the class I ended up writing:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public final class XssFilter implements Filter {

    static class FilteredRequest extends HttpServletRequestWrapper {

        /* These are the characters allowed by the Javascript validation */
        static String allowedChars = "+-0123456789#*";

        public FilteredRequest(ServletRequest request) {
            super((HttpServletRequest)request);
        }

        public String sanitize(String input) {
            String result = "";
            for (int i = 0; i < input.length(); i++) {
                if (allowedChars.indexOf(input.charAt(i)) >= 0) {
                    result += input.charAt(i);
                }
            }
            return result;
        }

        public String getParameter(String paramName) {
            String value = super.getParameter(paramName);
            if ("dangerousParamName".equals(paramName)) {
                value = sanitize(value);
            }
            return value;
        }

        public String[] getParameterValues(String paramName) {
            String values[] = super.getParameterValues(paramName);
            if ("dangerousParamName".equals(paramName)) {
                for (int index = 0; index < values.length; index++) {
                    values[index] = sanitize(values[index]);
                }
            }
            return values;
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new FilteredRequest(request), response);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
    }
}

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.