Programs & Examples On #Cobra

Three possible technologies: The Cobra toolkit is a pure Java HTML parser and rendering engine with support for CSS2 and JavaScript. The Cobra Programming Language has Python-like syntax that targets the .NET Runtime and supports built-in unit tests, contracts and both dynamic/static programming support. Cobra is a Golang library for creating powerful modern CLI applications as well as a program to generate applications and command files.

Clicking a checkbox with ng-click does not update the model

The ordering between ng-model and ng-click seems to be different and it's something you probably shouldn't rely on. Instead you could do something like this:

<div ng-app="myApp" ng-controller="Ctrl">
<li  ng-repeat="todo in todos">
<input type='checkbox' ng-model="todo.done" ng-click='onCompleteTodo(todo)'>
    {{todo.text}} {{todo.done}}
</li> 
    <hr>
        task: {{current.text}}
        <hr>
            <h2>Wrong value</h2>
         done: {{current.done}}
</div>

And your script:

angular.module('myApp', [])
    .controller('Ctrl', ['$scope', function($scope) {

        $scope.todos=[
            {'text': "get milk",
             'done': true
             },
            {'text': "get milk2",
             'done': false
             }
            ];

        $scope.current = $scope.todos[0];


       $scope.onCompleteTodo = function(todo) {
            console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
    //$scope.doneAfterClick=todo.done;
    //$scope.todoText = todo.text;
       $scope.current = todo;

   };
}]);

What's different here is whenever you click a box, it sets that box as what's "current" and then display those values in the view. http://jsfiddle.net/QeR7y/

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

Set UIButton title UILabel font size programmatically

Swift:

shareButton.titleLabel?.font = UIFont.systemFontOfSize(size)

Unimportant note: deleted by animuson? Dec 5 '14 at 16:48
animuson, I had the same problem now a month after I posted this answer. I was googling and found out this post which wasn't easily copy pastable into a swift project. While I was scrolling saw my deleted answer and copied it. so please don't delete actually useful stuff..

What method in the String class returns only the first N characters?

The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.

I always add these methods to all my projects, and never have to worry about code breaking, because something changed and the index is invalid. Below is the code.

    public static String Substring(this String val, int startIndex, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
    }

    public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex, length);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        int newfrom, newlth, instrlength = val.Length;
        if (length < 0) //length is negative
        {
            newfrom = startIndex + length;
            newlth = -1 * length;
        }
        else //length is positive
        {
            newfrom = startIndex;
            newlth = length;
        }
        if (newfrom + newlth < 0 || newfrom > instrlength - 1)
        {
            return string.Empty;
        }
        if (newfrom < 0)
        {
            newlth = newfrom + newlth;
            newfrom = 0;
        }
        return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));
    }

I blogged about this back in May 2010 at: http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html

How can I pass some data from one controller to another peer controller

Use a service to achieve this:

MyApp.app.service("xxxSvc", function () {

var _xxx = {};

return {
    getXxx: function () {
        return _xxx;
    },
    setXxx: function (value) {
        _xxx = value;
    }
};

});

Next, inject this service into both controllers.

In Controller1, you would need to set the shared xxx value with a call to the service: xxxSvc.setXxx(xxx)

Finally, in Controller2, add a $watch on this service's getXxx() function like so:

  $scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
        if (newValue != null) {
            //update Controller2's xxx value
            $scope.xxx= newValue;
        }
    }, true);

VirtualBox Cannot register the hard disk already exists

The solution that worked for me is as follows:

  1. Make sure VirtualBox Manager is not running.
  2. Back up the files ~\.VirtualBox\VirtualBox.xml and ~\.VirtualBox\VirtualBox.xml-prev.
  3. Edit these files to modify the <HardDisks>...</HardDisks> section to remove the duplicate entry of <HardDisk />.
  4. Now run VirtualBox Manager.

Example:

  <HardDisks>
    <HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>

Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

make sure the username and email fields are not empty in the config file. and try to clone to an empty directory. these steps worked for me.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

You need to use an Angular form directive on the select. You can do that with ngModel. For example

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class App {
  cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
  selectedCity = this.cities[1];

  onChange(city) {
    alert(city.name);
  }
}

The (ngModelChange) event listener emits events when the selected value changes. This is where you can hookup your callback.

Note you will need to make sure you have imported the FormsModule into the application.

Here is a Plunker

jQuery Keypress Arrow Keys

You should use .keydown() because .keypress() will ignore "Arrows", for catching the key type use e.which

Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.

Notes:

  1. .keypress() will never be fired with Shift, Esc, and Delete but .keydown() will.
  2. Actually .keypress() in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown().

More useful information

  1. You can use .which Or .keyCode of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which never had a problem with).
  2. To detect a ctrl | alt | shift | META press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
  3. Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):

    • Enter: 13
    • Up: 38
    • Down: 40
    • Right: 39
    • Left: 37
    • Esc: 27
    • SpaceBar: 32
    • Ctrl: 17
    • Alt: 18
    • Shift: 16

How to implement a material design circular progress bar in android

I've backported the three Material Design progress drawables to Android 4.0, which can be used as a drop-in replacement for regular ProgressBar, with exactly the same appearance.

These drawables also backported the tinting APIs (and RTL support), and uses ?colorControlActivated as the default tint. A MaterialProgressBar widget which extends ProgressBar has also been introduced for convenience.

DreaminginCodeZH/MaterialProgressBar

This project has also been adopted by afollestad/material-dialogs for progress dialog.

On Android 4.4.4:

Android 4.4.4

On Android 5.1.1:

Android 5.1.1

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How can I align two divs horizontally?

<div>
<div style="float:left;width:45%;" >
    <span>source list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>

<div style="float:right;width:45%;">
    <span>destination list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>
<div style="clear:both; font-size:1px;"></div>
</div>

Clear must be used so as to prevent the float bug (height warping of outer Div).

style="clear:both; font-size:1px;

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I went to Preferences --> Java --> Installed JREs I did NOT see the JDK in here. I only saw the JRE here. So I added the JDK.

here we have to mandatory remove JRE instead of just unchecking.

How to filter WooCommerce products by custom attribute

A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.

https://wordpress.org/plugins/woocommerce-products-filter/

This one seems to do exactly what you are after

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also use the ignore syntax instead of using (or better the 'as any') notation:

// @ts-ignore
$("div.printArea").printArea();

How to get numbers after decimal point?

Use floor and subtract the result from the original number:

>> import math #gives you floor.
>> t = 5.55 #Give a variable 5.55
>> x = math.floor(t) #floor returns t rounded down to 5..
>> z = t - x #z = 5.55 - 5 = 0.55

How can I get CMake to find my alternative Boost installation?

I spent most of my evening trying to get this working. I tried all of the -DBOOST_* &c. directives with CMake, but it kept linking to my system Boost libraries, even after clearing and re-configuring my build area repeatedly.

At the end I modified the generated Makefile and voided the cmake_check_build_system target to do nothing (like 'echo ""') so that it wouldn't overwrite my changes when I ran make, and then did 'grep -rl "lboost_python" * | xargs sed -i "s:-lboost_python:-L/opt/sw/gcc5/usr/lib/ -lboost_python:g' in my build/ directory to explicitly point all the build commands to the Boost installation I wanted to use. Finally, that worked.

I acknowledge that it is an ugly kludge, but I am just putting it out here for the benefit of those who come up against the same brick wall, and just want to work around it and get work done.

What is the backslash character (\\)?

Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \" to represent quotation marks. Then you have a second problem: how to represent \ ? Again, out of convention you decide to use \\ instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n).

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

WordPress path url in js script file

According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

URLEncoder not able to translate space character

USE MyUrlEncode.URLencoding(String url , String enc) to handle the problem

    public class MyUrlEncode {
    static BitSet dontNeedEncoding = null;
    static final int caseDiff = ('a' - 'A');
    static {
        dontNeedEncoding = new BitSet(256);
        int i;
        for (i = 'a'; i <= 'z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = 'A'; i <= 'Z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = '0'; i <= '9'; i++) {
            dontNeedEncoding.set(i);
        }
        dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');
        dontNeedEncoding.set('&');
        dontNeedEncoding.set('=');
    }
    public static String char2Unicode(char c) {
        if(dontNeedEncoding.get(c)) {
            return String.valueOf(c);
        }
        StringBuffer resultBuffer = new StringBuffer();
        resultBuffer.append("%");
        char ch = Character.forDigit((c >> 4) & 0xF, 16);
            if (Character.isLetter(ch)) {
            ch -= caseDiff;
        }
        resultBuffer.append(ch);
            ch = Character.forDigit(c & 0xF, 16);
            if (Character.isLetter(ch)) {
            ch -= caseDiff;
        }
         resultBuffer.append(ch);
        return resultBuffer.toString();
    }
    private static String URLEncoding(String url,String enc) throws UnsupportedEncodingException {
        StringBuffer stringBuffer = new StringBuffer();
        if(!dontNeedEncoding.get('/')) {
            dontNeedEncoding.set('/');
        }
        if(!dontNeedEncoding.get(':')) {
            dontNeedEncoding.set(':');
        }
        byte [] buff = url.getBytes(enc);
        for (int i = 0; i < buff.length; i++) {
            stringBuffer.append(char2Unicode((char)buff[i]));
        }
        return stringBuffer.toString();
    }
    private static String URIEncoding(String uri , String enc) throws UnsupportedEncodingException { //?????????
        StringBuffer stringBuffer = new StringBuffer();
        if(dontNeedEncoding.get('/')) {
            dontNeedEncoding.clear('/');
        }
        if(dontNeedEncoding.get(':')) {
            dontNeedEncoding.clear(':');
        }
        byte [] buff = uri.getBytes(enc);
        for (int i = 0; i < buff.length; i++) {
            stringBuffer.append(char2Unicode((char)buff[i]));
        }
        return stringBuffer.toString();
    }

    public static String URLencoding(String url , String enc) throws UnsupportedEncodingException {
        int index = url.indexOf('?');
        StringBuffer result = new StringBuffer();
        if(index == -1) {
            result.append(URLEncoding(url, enc));
        }else {
            result.append(URLEncoding(url.substring(0 , index),enc));
            result.append("?");
            result.append(URIEncoding(url.substring(index+1),enc));
        }
        return result.toString();
    }

}

Get viewport/window height in ReactJS

I've just edited QoP's current answer to support SSR and use it with Next.js (React 16.8.0+):

/hooks/useWindowDimensions.js:

import { useState, useEffect } from 'react';

export default function useWindowDimensions() {

  const hasWindow = typeof window !== 'undefined';

  function getWindowDimensions() {
    const width = hasWindow ? window.innerWidth : null;
    const height = hasWindow ? window.innerHeight : null;
    return {
      width,
      height,
    };
  }

  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    if (hasWindow) {
      function handleResize() {
        setWindowDimensions(getWindowDimensions());
      }

      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }
  }, [hasWindow]);

  return windowDimensions;
}

/yourComponent.js:

import useWindowDimensions from './hooks/useWindowDimensions';

const Component = () => {
  const { height, width } = useWindowDimensions();
  /* you can also use default values or alias to use only one prop: */
  // const { height: windowHeight = 480 } useWindowDimensions();

  return (
    <div>
      width: {width} ~ height: {height}
    </div>
  );
}

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

DECLARE @t1 TABLE (
    TableID     int         IDENTITY,
    FieldValue  varchar(20)
)

--<< No empty string
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

--<< A record with an empty string already exists
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

How do I escape a single quote in SQL Server?

Single quotes are escaped by doubling them up, just as you've shown us in your example. The following SQL illustrates this functionality. I tested it on SQL Server 2008:

DECLARE @my_table TABLE (
    [value] VARCHAR(200)
)

INSERT INTO @my_table VALUES ('hi, my name''s tim.')

SELECT * FROM @my_table

Results

value
==================
hi, my name's tim.

Naming conventions for Java methods that return boolean

is is the one I've come across more than any other. Whatever makes sense in the current situation is the best option though.

I can't understand why this JAXB IllegalAnnotationException is thrown

One of the following may cause the exception:

  1. Add an empty public constructor to your Fields class, JAXB uses reflection to load your classes, that's why the exception is thrown.
  2. Add separate getter and setter for your list.

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

SQL - select distinct only on one column

Since you don't care, I chose the max ID for each number.

select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id

Query Explanation

 select 
    tbl.*  -- give me all the data from the base table (tbl) 
 from 
    tbl    
    inner join (  -- only return rows in tbl which match this subquery
        select 
            max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
        from 
            tbl 
        group by 
            NUMBER            -- how to group rows for the MAX aggregation
    ) maxID
        on maxID.maxID = tbl.id -- join condition ie only return rows in tbl 
                                -- whose ID is also a MAX ID for a given NUMBER

How to pass a URI to an intent?

In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.

Look at this simple approach.

// put uri to intent 
intent.setData(imageUri);

And to get Uri back from intent:

// Get Uri from Intent
Uri imageUri=getIntent().getData();

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Another way this issue can pop up on your screen is when you give a condition and insert the return inside of it. If the condition is not satisfied, then there is nothing to return. Hence the error.

export default function Component({ yourCondition }) {

    if(yourCondition === "something") {
        return(
            This will throw this error if this condition is false.
        );
    }
}

All that I did was to insert an outer return with null and it worked fine again.

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I struggled with this for a long time. I am using Angular 6 and I found that

let headers = new HttpHeaders();
headers = headers.append('key', 'value');

did not work. But what did work was

let headers = new HttpHeaders().append('key', 'value');

did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect

let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');

would work too.

Regex doesn't work in String.matches()

String.matches returns whether the whole string matches the regex, not just any substring.

How do I check that a number is float or integer?

parseInt(yourNumber)=== parseFloat(yourNumber)

Returning JSON from a PHP Script

It is also good to set the access security - just replace * with the domain you want to be able to reach it.

<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
    $response = array();
    $response[0] = array(
        'id' => '1',
        'value1'=> 'value1',
        'value2'=> 'value2'
    );

echo json_encode($response); 
?>

Here is more samples on that: how to bypass Access-Control-Allow-Origin?

Changing navigation title programmatically

Normally, the best-practice is to set the title on the UIViewController. By doing this, the UINavigationItem is also set. Generally, this is better than programmatically allocating and initializing a UINavigationBar that's not linked to anything.

You miss out on some of the benefits and functionality that the UINavigationBar was designed for. Here is a link to the documentation that may help you. It discusses the different properties you can set on the actual bar and on a UINavigationItem.

Just keep in mind:

  1. You lose back button functionality (unless you wire it yourself)
  2. The built-in "drag from the left-hand side to swipe back" gesture is forfeited

UINavigationController's are your friends.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

Why does npm install say I have unmet dependencies?

I was trying to work on an automated deployment system that runs npm install, so a lot of these solutions wouldn't work for me in an automated fasion. I wasn't in a position to go deleting/re-creating node_modules/ nor could I easily change Node.js versions.

So I ended up running npm shrinkwrap - adding the npm-shrinkwrap.json file to my deployment bundle, and running installs from there. That fixed the problem for me; with the shrinkwrap file as a 'helper', npm seemed to be able to find the right packages and get them installed for me. (Shrinkwrap has other features as well, but this was what I needed it for in this particular case).

How do I enable saving of filled-in fields on a PDF form?

In Acrobat, click on the "Advanced" tab, then click on "Enable Features in Adobe Reader." This should do the trick.

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

Android: Storing username and password?

Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.

The advice from the (Android dev guide) is:

In general, we recommend minimizing the frequency of asking for user credentials -- to make phishing attacks more conspicuous, and less likely to be successful. Instead use an authorization token and refresh it.

Where possible, username and password should not be stored on the device. Instead, perform initial authentication using the username and password supplied by the user, and then use a short-lived, service-specific authorization token.

Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.

If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.

Map a 2D array onto a 1D array

It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.

Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.

MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.

Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.

How can I tell AngularJS to "refresh"

Why $apply should be called?

TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

Get characters after last / in url

You could explode based on "/", and return the last entry:

print end( explode( "/", "http://www.vimeo.com/1234567" ) );

That's based on blowing the string apart, something that isn't necessary if you know the pattern of the string itself will not soon be changing. You could, alternatively, use a regular expression to locate that value at the end of the string:

$url = "http://www.vimeo.com/1234567";

if ( preg_match( "/\d+$/", $url, $matches ) ) {
    print $matches[0];
}

Filtering DataGridView without changing datasource

A simpler way is to transverse the data, and hide the lines with the Visible property.

// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];
currencyManager.SuspendBinding();

// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    dataGridView3.Rows[u].Visible = true;
    x++;
}

// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
    {
        dataGridView3.Rows[u].Visible = true;
    }
    else
    {
        dataGridView3.Rows[u].Visible = false;
    }
}

// Resume data grid view binding
currencyManager.ResumeBinding();

Just an idea... it works for me.

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Set a default font for whole iOS app?

None of these solutions works universally throughout the app. One thing I found to help manage the fonts in Xcode is opening the Storyboard as Source code (Control-click storyboard in Files navigator > "Open as" > "Source"), and then doing a find-and-replace.

How to remove specific element from an array using python

You don't need to iterate the array. Just:

>>> x = ['[email protected]', '[email protected]']
>>> x
['[email protected]', '[email protected]']
>>> x.remove('[email protected]')
>>> x
['[email protected]']

This will remove the first occurence that matches the string.

EDIT: After your edit, you still don't need to iterate over. Just do:

index = initial_list.index(item1)
del initial_list[index]
del other_list[index]

How to autosize and right-align GridViewColumn data in WPF?

I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.

public void correctColumnWidths()
{
    double remainingSpace = myList.ActualWidth;

    if (remainingSpace > 0)
    {
         for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
              if (i != 2)
                   remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;

          //Leave 15 px free for scrollbar
          remainingSpace -= 15;

          (myList.View as GridView).Columns[2].Width = remainingSpace;
    }
}

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

How to compare two java objects

You need to implement the equals() method in your MyClass.

The reason that == didn't work is this is checking that they refer to the same instance. Since you did new for each, each one is a different instance.

The reason that equals() didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==.

Note that you should also implement hashcode() if you're going to implement equals() because a lot of java.util Collections expect that.

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

This is possible in HTML5. Example (PHP 5.4):

<!doctype html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="my_file[]" multiple>
            <input type="submit" value="Upload">
        </form>
        <?php
            if (isset($_FILES['my_file'])) {
                $myFile = $_FILES['my_file'];
                $fileCount = count($myFile["name"]);

                for ($i = 0; $i < $fileCount; $i++) {
                    ?>
                        <p>File #<?= $i+1 ?>:</p>
                        <p>
                            Name: <?= $myFile["name"][$i] ?><br>
                            Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
                            Type: <?= $myFile["type"][$i] ?><br>
                            Size: <?= $myFile["size"][$i] ?><br>
                            Error: <?= $myFile["error"][$i] ?><br>
                        </p>
                    <?php
                }
            }
        ?>
    </body>
</html>

Here's what it looks like in Chrome after selecting 2 items in the file dialog:

chrome multiple file select

And here's what it looks like after clicking the "Upload" button.

submitting multiple files to PHP

This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.

Convert hex string to int in Python

int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa", 16)
10

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Yes! It does matter.

=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).

enter image description here

You can easily test it. Paste following code in an HTML file and open it in browser

<script>

function onPageLoad()
{
    var x = "5";
    var y = 5;
    alert(x === 5);
};

</script>

</head>

<body onload='onPageLoad();'>

You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.

Rails 3.1 and Image Assets

In rails 4 you can now use a css and sass helper image-url:

div.logo {background-image: image-url("logo.png");}

If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Delete the designer.cs file and then right click on the .aspx file and choose "Convert To Web Application". If there is a problem with your control declarations, such as a tag not being well-formed, you will get an error message and you will need to correct the malformed tag before visual studio can successfully re-generate your designer file.

In my case, at this point, I discovered that the problem was that I had declared a button control that that was not inside of a form tag with a runat="server" attribute.

PHP: HTTP or HTTPS?

$_SERVER['HTTPS']

This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Replace all latters from any language in 'A', and if you wish for example all digits to 0:

return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");

Detecting when the 'back' button is pressed on a navbar

For Swift with a UINavigationController:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.navigationController?.topViewController != self {
        print("back button tapped")
    }
}

Force Intellij IDEA to reread all maven dependencies

For IntelliJ IDEA 14.0

Project > [your project name] > right click > Maven > Reimport

How to get all subsets of a set? (powerset)

def findsubsets(s, n): 
    return list(itertools.combinations(s, n)) 

def allsubsets(s) :
    a = []
    for x in range(1,len(s)+1):
        a.append(map(set,findsubsets(s,x)))      
    return a

How do you truncate all tables in a database using TSQL?

Make an empty "template" database, take a full backup. When you need to refresh, just restore using WITH REPLACE. Fast, simple, bulletproof. And if a couple tables here or there need some base data(e.g. config information, or just basic information that makes your app run) it handles that too.

Is there a way to reset IIS 7.5 to factory settings?

This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx

It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

In my case it was happening during json serialization of a web api return payload - I had a 'circular' reference in my Entity Framework model, I was returning a simple one-to-many object graph back but the child had a reference back to the parent, which apparently the json serializer doensn't like. Removing the property on the child that was referencing the parent did the trick.

Hope this helps someone who might have a similar issue.

Node.js check if path is file or directory

Here's a function that I use. Nobody is making use of promisify and await/async feature in this post so I thought I would share.

const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);

async function isDirectory (path) {
  try {
    return (await lstat(path)).isDirectory();
  }
  catch (e) {
    return false;
  }
}

Note : I don't use require('fs').promises; because it has been experimental for one year now, better not rely on it.

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

jQuery text() and newlines

You can use html instead of text and replace each occurrence of \n with <br>. You will have to correctly escape your text though.

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

AngularJS routing without the hash '#'

**

It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular

** Because

  1. It produces the clean and SEO Friendly URLs that are easier for users to understand and remember.
  2. You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering it the client.

Use Hashlocationstrtegy only if you have to support the older browsers.

Click here to know more

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Not sure if this is stopping everyone else, but I resolved this by upgrading chromedriver and then ensuring that it was in a place that my user could read from (it seems like a lot of people encountering this are seeing it for permission reasons like me).

On Ubuntu 16.04: 1. Download chromedriver (version 2.37 for me) 2. Unzip the file 3. Install it somewhere sensible (I chose /usr/local/bin/chromedriver)

Doesn't even need to be owned by my user as long as it's globally executable (sudo chmod +x /usr/local/bin/chromedriver)

How do I convert an enum to a list in C#?

Much easier way:

Enum.GetValues(typeof(SomeEnum))
    .Cast<SomeEnum>()
    .Select(v => v.ToString())
    .ToList();

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How can the default node version be set using NVM?

This will set the default to be the most current version of node

nvm alias default node

and then you'll need to run

nvm use default

or exit and open a new tab

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

php return 500 error but no error log

Scan your source files to find @.

From php documentation site

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

PHP - print all properties of an object

To get more information use this custom TO($someObject) function:

I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.

function TO($object){ //Test Object
                if(!is_object($object)){
                    throw new Exception("This is not a Object"); 
                    return;
                }
                if(class_exists(get_class($object), true)) echo "<pre>CLASS NAME = ".get_class($object);
                $reflection = new ReflectionClass(get_class($object));
                echo "<br />";
                echo $reflection->getDocComment();

                echo "<br />";

                $metody = $reflection->getMethods();
                foreach($metody as $key => $value){
                    echo "<br />". $value;
                }

                echo "<br />";

                $vars = $reflection->getProperties();
                foreach($vars as $key => $value){
                    echo "<br />". $value;
                }
                echo "</pre>";
            }

To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:

        /**
         * DocNotes -  This is description of this class if given else it will display false
         */
        class Person{
            private $name;
            private $dob;
            private $height;
            private $weight;
            private static $num;

            function __construct($dbo, $height, $weight, $name) {
                $this->dob = $dbo;
                $this->height = (integer)$height;
                $this->weight = (integer)$weight;
                $this->name = $name;
                self::$num++;

            }
            public function eat($var="", $sar=""){
                echo $var;
            }
            public function potrzeba($var =""){
                return $var;
            }
        }

Now lets create a instance of a Person and wrap it with our function.

    $Wictor = new Person("27.04.1987", 170, 70, "Wictor");
    TO($Wictor);

This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:

CLASS NAME = Person
/**
             * DocNotes -  This is description of this class if given else it will display false
             */

Method [  public method __construct ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 75 - 82

  - Parameters [4] {
    Parameter #0 [  $dbo ]
    Parameter #1 [  $height ]
    Parameter #2 [  $weight ]
    Parameter #3 [  $name ]
  }
}

Method [  public method eat ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 83 - 85

  - Parameters [2] {
    Parameter #0 [  $var = '' ]
    Parameter #1 [  $sar = '' ]
  }
}

Method [  public method potrzeba ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 86 - 88

  - Parameters [1] {
    Parameter #0 [  $var = '' ]
  }
}


Property [  private $name ]

Property [  private $dob ]

Property [  private $height ]

Property [  private $weight ]

Property [ private static $num ]

Catch paste input

This is getting closer to what you might want.

function sanitize(s) {
  return s.replace(/\bfoo\b/g, "~"); 
};

$(function() {
 $(":text, textarea").bind("input paste", function(e) {
   try {
     clipboardData.setData("text",
       sanitize(clipboardData.getData("text"))
     );
   } catch (e) {
     $(this).val( sanitize( $(this).val() ) );
   }
 });
});

Please note that when clipboardData object is not found (on browsers other then IE) you are currently getting the element's full value + the clipboard'ed value.

You can probably do some extra steps to dif the two values, before an input & after the input, if you really are only after what data was truly pasted into the element.

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

What is considered a good response time for a dynamic, personalized web application?

I have been striving for < 3 seconds for my applications, but I'm a bit picky when it comes to performance.

If you ask around, they say that people start to loose interest in the >= 7 second range, by 10-15 seconds you have typically lost them, unless you REALLY have something they want or need.

Algorithm: efficient way to remove duplicate integers from an array

The return value of the function should be the number of unique elements and they are all stored at the front of the array. Without this additional information, you won't even know if there were any duplicates.

Each iteration of the outer loop processes one element of the array. If it is unique, it stays in the front of the array and if it is a duplicate, it is overwritten by the last unprocessed element in the array. This solution runs in O(n^2) time.

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

size_t rmdup(int *arr, size_t len)
{
  size_t prev = 0;
  size_t curr = 1;
  size_t last = len - 1;
  while (curr <= last) {
    for (prev = 0; prev < curr && arr[curr] != arr[prev]; ++prev);
    if (prev == curr) {
      ++curr;
    } else {
      arr[curr] = arr[last];
      --last;
    }
  }
  return curr;
}

void print_array(int *arr, size_t len)
{
  printf("{");
  size_t curr = 0;
  for (curr = 0; curr < len; ++curr) {
    if (curr > 0) printf(", ");
    printf("%d", arr[curr]);
  }
  printf("}");
}

int main()
{
  int arr[] = {4, 8, 4, 1, 1, 2, 9};
  printf("Before: ");
  size_t len = sizeof (arr) / sizeof (arr[0]);
  print_array(arr, len);
  len = rmdup(arr, len);
  printf("\nAfter: ");
  print_array(arr, len);
  printf("\n");
  return 0;
}

How to get process ID of background process?

You can use the jobs -l command to get to a particular jobL

^Z
[1]+  Stopped                 guard

my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18           guard

In this case, 46841 is the PID.

From help jobs:

-l Report the process group ID and working directory of the jobs.

jobs -p is another option which shows just the PIDs.

Using underscores in Java variables and method names

it's just your own style,nothing a bad style code,and nothing a good style code,just difference our code with the others.

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

Check if file exists and whether it contains a specific string

You should use the grep -q flag for quiet output. See the man pages below:

man grep output :

 General Output Control

  -q, --quiet, --silent
              Quiet;  do  not write anything to standard output.  Exit immediately with zero status
              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or
              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

grepUtil.ksh :

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    echo "Entering readLine"
    file=${1}
    while read line
    do
        #assign last line to var
        var="$line"
    done <"$file"
    echo "Exiting readLine"
}
#Check if file exists 
#Params: 1}File
doesFileExit(){
    echo "Entering doesFileExit"
    orgDirectory=${PWD}
    cd ${PWD}${dirPath}
    #echo ${PWD}
    if [[ -e "${1}" ]]; then
        echo "${1} exists"
    else
        echo "${1} does not exist"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
    echo "Entering doesFileContainStringQuiet"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep -q ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
    echo "Entering doesFileContainString"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainString"
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
    doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh

Why can't variables be declared in a switch statement?

New variables can be decalared only at block scope. You need to write something like this:

case VAL:  
  // This will work
  {
  int newVal = 42;  
  }
  break;

Of course, newVal only has scope within the braces...

Cheers, Ralph

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

angular 4: *ngIf with multiple conditions

You got a ninja ')'.

Try :

<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">

Send file via cURL from form POST in PHP

Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.

public function postFile()
{


        $file_url = "test.txt";  //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
        $eol = "\r\n"; //default line-break for mime type
        $BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
        $BODY=""; //init my curl body
        $BODY.= '--'.$BOUNDARY. $eol; //start param header
        $BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
        $BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
        $BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
        $BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
        $BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
        $BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
        $BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
        $BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.



        $ch = curl_init(); //init curl
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                         'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
                         ,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
                    );
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
        curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
        curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
        curl_setopt($ch, CURLOPT_POST, true); //set as post
        curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY 


        $response = curl_exec($ch); // start curl navigation

     print_r($response); //print response

}

With this we shoud be get on the "api.endpoint.post" the following vars posted You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row

print_r($response); //print response

public function getPostFile()
{

    echo "\n\n_SERVER\n";
    echo "<pre>";
    print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
    echo "/<pre>";
    echo "_POST\n";
    echo "<pre>";
    print_r($_POST['sometext']);
    echo "/<pre>";
    echo "_FILES\n";
    echo "<pre>";
    print_r($_FILEST['somefile']);
    echo "/<pre>";
}

Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,

My Best Reggards,

my apologies about my english but isnt my native language.

Questions every good PHP Developer should be able to answer

I think a good question would be: how does HTTP work? Working with GET and POST data among other HTTP communications is inherent in PHP development. Understanding how HTTP works in a broader context and how PHP implements this goes a long way.

How can I change IIS Express port for a site

Another fix for those who have IIS Installed:

Create a path on the IIS Server, and allocate your website/app there.

Go to propieties of the solution of the explorer, then in front of using the iisexpress from visual studio, make that vs uses your personal own IIS.

Solution Proprieties

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

CodeIgniter: How to get Controller, Action, URL information

$this->router->fetch_class(); 

// fecth class the class in controller $this->router->fetch_method();

// method

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

List all the files and folders in a Directory with PHP recursive function

To whom needs list files first than folders (with alphabetical older).

Can use following function. This is not self calling function. So you will have directory list, directory view, files list and folders list as seperated array also.

I spend two days for this and do not want someone will wast his time for this also, hope helps someone.

function dirlist($dir){
    if(!file_exists($dir)){ return $dir.' does not exists'; }
    $list = array('path' => $dir, 'dirview' => array(), 'dirlist' => array(), 'files' => array(), 'folders' => array());

    $dirs = array($dir);
    while(null !== ($dir = array_pop($dirs))){
        if($dh = opendir($dir)){
            while(false !== ($file = readdir($dh))){
                if($file == '.' || $file == '..') continue;
                $path = $dir.DIRECTORY_SEPARATOR.$file;
                $list['dirlist_natural'][] = $path;
                if(is_dir($path)){
                    $list['dirview'][$dir]['folders'][] = $path;
                    // Bos klasorler while icerisine tekrar girmeyecektir. Klasorun oldugundan emin olalim.
                    if(!isset($list['dirview'][$path])){ $list['dirview'][$path] = array(); }
                    $dirs[] = $path;
                    //if($path == 'D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content\upgrade'){ press($path); press($list['dirview']); die; }
                }
                else{
                    $list['dirview'][$dir]['files'][] = $path;
                }
            }
            closedir($dh);
        }
    }

    // if(!empty($dirlist['dirlist_natural']))  sort($dirlist['dirlist_natural'], SORT_LOCALE_STRING); // delete safe ama gerek kalmadi.

    if(!empty($list['dirview'])) ksort($list['dirview']);

    // Dosyalari dogru siralama yaptiriyoruz. Deniz P. - info[at]netinial.com
    foreach($list['dirview'] as $path => $file){
        if(isset($file['files'])){
            $list['dirlist'][] = $path;
            $list['files'] = array_merge($list['files'], $file['files']);
            $list['dirlist'] = array_merge($list['dirlist'], $file['files']);
        }
        // Add empty folders to the list
        if(is_dir($path) && array_search($path, $list['dirlist']) === false){
            $list['dirlist'][] = $path;
        }
        if(isset($file['folders'])){
            $list['folders'] = array_merge($list['folders'], $file['folders']);
        }
    }

    //press(array_diff($list['dirlist_natural'], $list['dirlist'])); press($list['dirview']); die;

    return $list;
}

will output something like this.

[D:\Xampp\htdocs\exclusiveyachtcharter.localhost] => Array
                (
                    [files] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
                            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
                            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
                            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
                            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
                            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
                            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
                            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
                            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
                            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
                            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
                            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
                            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
                            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
                            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
                            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
                        )

                    [folders] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-admin
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-includes
                        )

                )

dirview output

    [dirview] => Array
        (
            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
            [19] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost
            [20] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql
            [21] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql.zip
            [22] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
)

Laravel: Auth::user()->id trying to get a property of a non-object

The first check user logged in and then

if (Auth::check()){
    //get id of logged in user
    {{ Auth::getUser()->id}}

    //get the name of logged in user
    {{ Auth::getUser()->name }}
}

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

How to filter an array from all elements of another array

with object filter result

[{id:1},{id:2},{id:3},{id:4}].filter(v=>!([{id:2},{id:4}].some(e=>e.id === v.id)))

enter image description here

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

What is the purpose of the return statement?

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2

Change an image with onclick()

Or maybe and that is prob it

_x000D_
_x000D_
<img src="path" onclick="this.src='path'">
_x000D_
_x000D_
_x000D_

What is the "__v" field in Mongoose

From here:

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v.

If this conflicts with your application you can configure as such:

new Schema({..}, { versionKey: '_somethingElse' })

How to view the committed files you have not pushed yet?

I'm not great with Git, but this is what I do. This does not necessarily compare with the remote repo, but you can modify the git diff with the appropriate commit hash from the remote.

Say you made one commit that you haven't pushed...

First find the last two commits...

git log -2

This shows the last commit first, and descends from there...

[jason:~/git/my_project] git log -2
commit ea7937edc8b10
Author: xyz
Date:   Wed Jul 27 14:06:41 2016 -0500

    Made a change in July

commit 52f9bf7956f0
Author: xyz
Date:   Tue Jun 14 14:29:52 2016 -0500

    Made a change in June

Now just use the two commit hashes (which I abbreviated) to run a diff:

git diff 52f9bf7956f0 ea7937edc8b10

How do I supply an initial value to a text field?

If you are using TextEditingController then set the text to it, like below

TextEditingController _controller = new TextEditingController();


_controller.text = 'your initial text';

final your_text_name = TextFormField(
      autofocus: false,
      controller: _controller,
      decoration: InputDecoration(
        hintText: 'Hint Value',
      ),
    );

and if you are not using any TextEditingController then you can directly use initialValue like below

final last_name = TextFormField(
      autofocus: false,
      initialValue: 'your initial text',
      decoration: InputDecoration(
        hintText: 'Last Name',
      ),
    );

For more reference TextEditingController

to_string is not a member of std, says g++ (mingw)

This is a known bug under MinGW. Relevant Bugzilla. In the comments section you can get a patch to make it work with MinGW.

This issue has been fixed in MinGW-w64 distros higher than GCC 4.8.0 provided by the MinGW-w64 project. Despite the name, the project provides toolchains for 32-bit along with 64-bit. The Nuwen MinGW distro also solves this issue.

Unable to connect to SQL Server instance remotely

Disable the firewall and try to connect.

If that works, then enable the firewall and

Windows Defender Firewall -> Advanced Settings -> Inbound Rules(Right Click) -> New Rules -> Port -> Allow Port 1433 (Public and Private) -> Add

Do the same for Outbound Rules.

Then Try again.

How to switch to the new browser window, which opens after click on the button?

If you have more then one browser (using java 8)

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestLink {

  private static Set<String> windows;

  public static void main(String[] args) {

    WebDriver driver = new FirefoxDriver();
    driver.get("file:///C:/Users/radler/Desktop/myLink.html");
    setWindows(driver);
    driver.findElement(By.xpath("//body/a")).click();
    // get new window
    String newWindow = getWindow(driver);
    driver.switchTo().window(newWindow);

    // Perform the actions on new window
    String text = driver.findElement(By.cssSelector(".active")).getText();
    System.out.println(text);

    driver.close();
    // Switch back
    driver.switchTo().window(windows.iterator().next());


    driver.findElement(By.xpath("//body/a")).click();

  }

  private static void setWindows(WebDriver driver) {
    windows = new HashSet<String>();
    driver.getWindowHandles().stream().forEach(n -> windows.add(n));
  }

  private static String getWindow(WebDriver driver) {
    List<String> newWindow = driver.getWindowHandles().stream()
        .filter(n -> windows.contains(n) == false).collect(Collectors.toList());
    System.out.println(newWindow.get(0));
    return newWindow.get(0);
  }

}

How to loop through an associative array and get the key?

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

How to display alt text for an image in chrome

If I'm correct, this is a bug in webkit (according to this). I'm not sure if there is much you can do, sorry for the weak answer.

There is, however, a work around which you can use. If you add the title attribute to your image (e.g. title="Image Not Found") it'll work.

Why is Git better than Subversion?

First, concurrent version control seems like an easy problem to solve. It's not at all. Anyway...

SVN is quite non-intuitive. Git is even worse. [sarcastic-speculation] This might be because developers, that like hard problems like concurrent version control, don't have much interest in making a good UI. [/sarcastic-speculation]

SVN supporters think they don't need a distributed version-control system. I thought that too. But now that we use Git exclusively, I'm a believer. Now version control works for me AND the team/project instead of just working for the project. When I need a branch, I branch. Sometimes it's a branch that has a corresponding branch on the server, and sometimes it does not. Not to mention all the other advantages that I'll have to go study up on (thanks in part to the arcane and absurd lack of UI that is a modern version control system).

SQL Server Express CREATE DATABASE permission denied in database 'master'

I know, it is an old question, but no solution worked for me. Here is what I did:

USE master 
GO 
GRANT CREATE TABLE TO PUBLIC

Repeat this with every permission you need, for example GRANT CREATE DATABASE TO PUBLIC, ... You must have the server role "public" (yes, I am captain obvious).

Note 1: GRANT ALL TO PUBLIC is deprecated, does not work anymore in 2017.

Note 2: I tried to build an msi installer using the wix toolset. This toolset calls a powershell file, wich creates the databases, ... Just to give you some background information :)

CSS technique for a horizontal line with words in the middle

If you are using React with Styled Components. I found that is more easy to just separate elements. Is not the "amazing solution" but it works.

import React from 'react';
import styled from "@emotion/styled";

const Container = styled.div`
  padding-top: 210px;
  padding-left: 50px;  
  display: inline-flex;
`

const Title1 = styled.div`
  position: absolute;
  font-size: 25px;
  left:40px;
  color: white;
  margin-top: -17px;
  padding-left: 40px;
`

const Title2 = styled.div`
  position: absolute;
  font-size: 25px;
  left:1090px;
  color: white;
  margin-top: -17px;
  padding-left: 40px;
`

const Line1 = styled.div`
  width: 20px;
  border: solid darkgray 1px;
  margin-right: 90px;
`
const Line2 = styled.div`
  width: 810px;
  border: solid darkgray 1px;
  margin-right: 126px;
`
const Line3 = styled.div`
  width: 178px;
  border: solid darkgray 1px;
`


const Titulos = () => {
    return (
        <Container>
            <Line1/>
            <Title1>
                FEATURED
            </Title1>
            <Line2/>
            <Line1/>
            <Title2>
                EXCLUSIVE
            </Title2>
            <Line3/>
        </Container>
    );
};

export default Titulos;

Result:

enter image description here

submit a form in a new tab

Add target="_blank" to the <form> tag.

Does Eclipse have line-wrap

Word wrap comes out of the box with Juno now. Right Click on the editor and select the "Word Wrap" option from the dropdown.

How to use the divide function in the query?

Try something like this

select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT

I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.

How do I get the parent directory in Python?

The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:

import os
# Create list of ".." times 5
upup = [os.pardir]*5
# Extract list as arguments of join()
go_upup = os.path.join(*upup)
# Get abspath for current file
up_dir = os.path.abspath(os.path.join(__file__, go_upup))

Convert InputStream to BufferedReader

InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

What's a .sh file?

open the location in terminal then type these commands 1. chmod +x filename.sh 2. ./filename.sh that's it

What is unit testing and how do you do it?

Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests.

Usually tests are run as separate programs, but the method of testing varies, depending on the language, and type of software (GUI, command-line, library).

Most languages have unit testing frameworks, you should look into one for yours.

Tests are usually run periodically, often after every change to the source code. The more often the better, because the sooner you will catch problems.

Calculating number of full months between two dates in SQL

This is for ORACLE only and not for SQL-Server:

months_between(to_date ('2009/05/15', 'yyyy/mm/dd'), 
               to_date ('2009/04/16', 'yyyy/mm/dd'))

And for full month:

round(months_between(to_date ('2009/05/15', 'yyyy/mm/dd'), 
                     to_date ('2009/04/16', 'yyyy/mm/dd')))

Can be used in Oracle 8i and above.

how to get selected row value in the KendoUI

I think it needs to be checked if any row is selected or not? The below code would check it:

var entityGrid = $("#EntitesGrid").data("kendoGrid");
            var selectedItem = entityGrid.dataItem(entityGrid.select());
            if (selectedItem != undefined)
                alert("The Row Is SELECTED");
            else
                alert("NO Row Is SELECTED")

Make an image responsive - the simplest way

You can try doing

<p>
  <a href="MY WEBSITE LINK" target="_blank">
    <img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
  </a>
</p>

This should scale your image if in a fluid layout.

For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media queries in CSS to change the width of the image.

Note that changing the height of the image will mess with the ratio.

Blue and Purple Default links, how to remove?

By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.

Pass a JavaScript function as parameter

There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!

In addition to Steve Fenton's answer, you can also pass functions directly.

function addContact(entity, refreshFn) {
    refreshFn();
}

function callAddContact() {
    addContact("entity", function() { DoThis(); });
}

Matplotlib (pyplot) savefig outputs blank image

Call plt.show() after plt.savefig(fig) and your problem should be solved.

How to adjust layout when soft keyboard appears

In my case it helped.

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.livewallpaper.profileview.loginact.Main2Activity">

<TextView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:text="Title"
    android:gravity="center"
    android:layout_height="0dp" />
<LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp">
    <EditText
        android:hint="enter here"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
<TextView
    android:layout_weight="1"
    android:text="signup for App"
    android:gravity="bottom|center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="0dp" />
</LinearLayout>

Use this in manifest file

<activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize"/>

Now the most important part! Use theme like this in either Activity or Application tag.

android:theme="@style/AppTheme"

And the theme tooks like this

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="windowActionModeOverlay">true</item>
</style>

So I was missing the theme. Which made me frustrated all day.

Oracle insert if not exists statement

insert into OPT (email, campaign_id) 
select '[email protected]',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='[email protected]' and campaign_id =100));

Reverse order of foreach list items

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

Reversing the Array

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

How to get the pure text without HTML element using JavaScript?

If you can use jquery then its simple

$("#txt").text()

How to retrieve the current value of an oracle sequence without increment it?

SELECT last_number
  FROM all_sequences
 WHERE sequence_owner = '<sequence owner>'
   AND sequence_name = '<sequence_name>';

You can get a variety of sequence metadata from user_sequences, all_sequences and dba_sequences.

These views work across sessions.

EDIT:

If the sequence is in your default schema then:

SELECT last_number
  FROM user_sequences
 WHERE sequence_name = '<sequence_name>';

If you want all the metadata then:

SELECT *
  FROM user_sequences
 WHERE sequence_name = '<sequence_name>';

Hope it helps...

EDIT2:

A long winded way of doing it more reliably if your cache size is not 1 would be:

SELECT increment_by I
  FROM user_sequences
 WHERE sequence_name = 'SEQ';

      I
-------
      1

SELECT seq.nextval S
  FROM dual;

      S
-------
   1234

-- Set the sequence to decrement by 
-- the same as its original increment
ALTER SEQUENCE seq 
INCREMENT BY -1;

Sequence altered.

SELECT seq.nextval S
  FROM dual;

      S
-------
   1233

-- Reset the sequence to its original increment
ALTER SEQUENCE seq 
INCREMENT BY 1;

Sequence altered.

Just beware that if others are using the sequence during this time - they (or you) may get

ORA-08004: sequence SEQ.NEXTVAL goes below the sequences MINVALUE and cannot be instantiated

Also, you might want to set the cache to NOCACHE prior to the resetting and then back to its original value afterwards to make sure you've not cached a lot of values.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Changing the ID (in all 3 places) from "map-canvas" to "map" fixed it for me, even though I had made sure the IDs were the same, the div had a width and height, and the code wasn't running until after the window load call. It's not the dash; it doesn't seem to work with any other ID than "map".

Should I Dispose() DataSet and DataTable?

Do you create the DataTables yourself? Because iterating through the children of any Object (as in DataSet.Tables) is usually not needed, as it's the job of the Parent to dispose all its child members.

Generally, the rule is: If you created it and it implements IDisposable, Dispose it. If you did NOT create it, then do NOT dispose it, that's the job of the parent object. But each object may have special rules, check the Documentation.

For .NET 3.5, it explicitly says "Dispose it when not using anymore", so that's what I would do.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

Also we can just kill git process. I receive the same issue via GUI app for git, something goes wrong and git makes some work infinitely. Killing process will freeze application that works with git, just restart it and everything will be ok.

What is the best way to add options to a select from a JavaScript object with jQuery?

This looks nicer, provides readability, but is slower than other methods.

$.each(selectData, function(i, option)
{
    $("<option/>").val(option.id).text(option.title).appendTo("#selectBox");
});

If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.

auxArr = [];
$.each(selectData, function(i, option)
{
    auxArr[i] = "<option value='" + option.id + "'>" + option.title + "</option>";
});

$('#selectBox').append(auxArr.join(''));

Is floating point math broken?

Imagine working in base ten with, say, 8 digits of accuracy. You check whether

1/3 + 2 / 3 == 1

and learn that this returns false. Why? Well, as real numbers we have

1/3 = 0.333.... and 2/3 = 0.666....

Truncating at eight decimal places, we get

0.33333333 + 0.66666666 = 0.99999999

which is, of course, different from 1.00000000 by exactly 0.00000001.


The situation for binary numbers with a fixed number of bits is exactly analogous. As real numbers, we have

1/10 = 0.0001100110011001100... (base 2)

and

1/5 = 0.0011001100110011001... (base 2)

If we truncated these to, say, seven bits, then we'd get

0.0001100 + 0.0011001 = 0.0100101

while on the other hand,

3/10 = 0.01001100110011... (base 2)

which, truncated to seven bits, is 0.0100110, and these differ by exactly 0.0000001.


The exact situation is slightly more subtle because these numbers are typically stored in scientific notation. So, for instance, instead of storing 1/10 as 0.0001100 we may store it as something like 1.10011 * 2^-4, depending on how many bits we've allocated for the exponent and the mantissa. This affects how many digits of precision you get for your calculations.

The upshot is that because of these rounding errors you essentially never want to use == on floating-point numbers. Instead, you can check if the absolute value of their difference is smaller than some fixed small number.

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

When should use Readonly and Get only properties

Creating a property with only a getter makes your property read-only for any code that is outside the class.

You can however change the value using methods provided by your class :

public class FuelConsumption {
    private double fuel;
    public double Fuel
    {
        get { return this.fuel; }
    }
    public void FillFuelTank(double amount)
    {
        this.fuel += amount;
    }
}

public static void Main()
{
    FuelConsumption f = new FuelConsumption();

    double a;
    a = f.Fuel; // Will work
    f.Fuel = a; // Does not compile

    f.FillFuelTank(10); // Value is changed from the method's code
}

Setting the private field of your class as readonly allows you to set the field value only once (using an inline assignment or in the class constructor). You will not be able to change it later.

public class ReadOnlyFields {
    private readonly double a = 2.0;
    private readonly double b;

    public ReadOnlyFields()
    {
        this.b = 4.0;
    }
}

readonly class fields are often used for variables that are initialized during class construction, and will never be changed later on.

In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.

If you need to store a value which will never change once its initial value has been set, use a readonly field.

Python group by

Do it in 2 steps. First, create a dictionary.

>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...

Then, convert that dictionary into the expected format.

>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

It is also possible with itertools.groupby but it requires the input to be sorted first.

>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]

Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.

>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
...   if k in res: res[k].append(v)
...   else: res[k] = [v]
... 
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]

Rename multiple files in a directory in Python

What about this :

import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***

How should I escape strings in JSON?

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

Create PDF with Java

Following are few libraries to create PDF with Java:

  1. iText
  2. Apache PDFBox
  3. BFO

I have used iText for genarating PDF's with a little bit of pain in the past.

Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.

Rename Pandas DataFrame Index

You can also use Index.set_names as follows:

In [25]: x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2],
   ....:                   'country':['A','A','B','B','A','A','B','B'],
   ....:                   'prod':[1,2,1,2,1,2,1,2],
   ....:                   'val':[10,20,15,25,20,30,25,35]})

In [26]: x = x.set_index(['year','country','prod']).squeeze()

In [27]: x
Out[27]: 
year  country  prod
1     A        1       10
               2       20
      B        1       15
               2       25
2     A        1       20
               2       30
      B        1       25
               2       35
Name: val, dtype: int64
In [28]: x.index = x.index.set_names('foo', level=1)

In [29]: x
Out[29]: 
year  foo  prod
1     A    1       10
           2       20
      B    1       15
           2       25
2     A    1       20
           2       30
      B    1       25
           2       35
Name: val, dtype: int64

Sorting std::map using value

Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )

    int main(){

      std::map<std::string, int> map;
       //Populate map

      std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
                                      std::make_move_iterator(end(map))};
       // Create a vector with the map parameters

       sort(begin(v), end(v),
             [](auto p1, auto p2){return p1.second > p2.second;});
       // Using sort + lambda function to return an ordered vector 
       // in respect to the int value that is now the 2nd parameter 
       // of our newly created vector v
  }

PHP: Best way to check if input is a valid number?

For PHP version 4 or later versions:

<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

header location not working in my php code

I use following code and it works fine for me.

if(!isset($_SESSION['user'])) {
       ob_start();
       header("Location: https://sitename.com/login.php");
       exit();
} else { 

// my further code 

}

Display array values in PHP

Other option:

$lijst=array(6,4,7,2,1,8,9,5,0,3);
for($i=0;$i<10;$i++){
echo $lijst[$i];
echo "<br>";
}

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

Adding a guideline to the editor in Visual Studio

This is originally from Sara's blog.

It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio.

The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)

You can also have the guide in multiple columns by listing more than one number after the color specifier:

RGB(230,230,230), 4, 80

Puts a white line at column 4 and column 80. This should be the value of a string value Guides in "Text Editor" key (see bellow).

Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).

Here are the registry keys that I know of:

Visual Studio 2010: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor

Visual Studio 2008: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor

Visual Studio 2005: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor

Visual Studio 2003: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor

For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:

These are also part of the Productivity Power Tools, which includes many other very useful extensions.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?

Scanner scanner = new Scanner("Student.txt");
String currentLine;

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Perform logic
    }
}

You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:

Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

How to Apply Corner Radius to LinearLayout

try this, for Programmatically to set a background with radius to LinearLayout or any View.

 private Drawable getDrawableWithRadius() {

    GradientDrawable gradientDrawable   =   new GradientDrawable();
    gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
    gradientDrawable.setColor(Color.RED);
    return gradientDrawable;
}

LinearLayout layout = new LinearLayout(this);
layout.setBackground(getDrawableWithRadius());

Get first key in a (possibly) associative array?

array_keys returns an array of keys. Take the first entry. Alternatively, you could call reset on the array, and subsequently key. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.

How can I give the Intellij compiler more heap space?

There is a

idea64.exe

starter in

IntelliJ IDEA 13.1.5\bin

so you can address more space.

jQuery UI 1.10: dialog and zIndex option

You don't tell it, but you are using jQuery UI 1.10.

In jQuery UI 1.10 the zIndex option is removed:

Removed zIndex option

Similar to the stack option, the zIndex option is unnecessary with a proper stacking implementation. The z-index is defined in CSS and stacking is now controlled by ensuring the focused dialog is the last "stacking" element in its parent.

you have to use pure css to set the dialog "on the top":

.ui-dialog { z-index: 1000 !important ;}

you need the key !important to override the default styling of the element; this affects all your dialogs if you need to set it only for a dialog use the dialogClass option and style it.

If you need a modal dialog set the modal: true option see the docs:

If set to true, the dialog will have modal behavior; other items on the page will be disabled, i.e., cannot be interacted with. Modal dialogs create an overlay below the dialog but above other page elements.

You need to set the modal overlay with an higher z-index to do so use:

.ui-front { z-index: 1000 !important; }

for this element too.

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

How to get week number in Python?

If you are only using the isocalendar week number across the board the following should be sufficient:

import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]

This retrieves the second member of the tuple returned by isocalendar for our week number.

However, if you are going to be using date functions that deal in the Gregorian calendar, isocalendar alone will not work! Take the following example:

import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]

The string here says to return the Monday of the first week in 2014 as our date. When we use isocalendar to retrieve the week number here, we would expect to get the same week number back, but we don't. Instead we get a week number of 2. Why?

Week 1 in the Gregorian calendar is the first week containing a Monday. Week 1 in the isocalendar is the first week containing a Thursday. The partial week at the beginning of 2014 contains a Thursday, so this is week 1 by the isocalendar, and making date week 2.

If we want to get the Gregorian week, we will need to convert from the isocalendar to the Gregorian. Here is a simple function that does the trick.

import datetime

def gregorian_week(date):
    # The isocalendar week for this date
    iso_week = date.isocalendar()[1]

    # The baseline Gregorian date for the beginning of our date's year
    base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")

    # If the isocalendar week for this date is not 1, we need to 
    # decrement the iso_week by 1 to get the Gregorian week number
    return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file

~/.bash_profile 

and append those lines

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

jQuery: select an element's class and id at the same time?

Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

# -*- coding: utf-8 -*-
print( bytes('ò') )

This is the way of Python 2.7 when dealing with unicode chars.

This won't work with Python 3.6, since bytes require an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'

In my case I had to use iso_8859_1 when encoding bytes in order to solve the issue.

Hope this helps someone.

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

how to toggle (hide/show) a table onClick of <a> tag in java script

Your anchor tag should be:

  <a id="loginLink" onclick="showHideTable();" href="#">Login</a>

And You javascript function :

function showHideTable()
{
   if (document.getElementById("loginTable").style.display == "none" ) {
       document.getElementById("loginTable").style.display="";

   } else {
      document.getElementById("loginTable").style.display="none";

}

Switch on ranges of integers in JavaScript

Incrementing on the answer by MarvinLabs to make it cleaner:

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

It is not necessary to check the lower end of the range because the break statements will cause execution to skip remaining cases, so by the time execution gets to checking e.g. (x < 9) we know the value must be 5 or greater.

Of course the output is only correct if the cases stay in the original order, and we assume integer values (as stated in the question) - technically the ranges are between 5 and 8.999999999999 or so since all numbers in js are actually double-precision floating point numbers.

If you want to be able to move the cases around, or find it more readable to have the full range visible in each case statement, just add a less-than-or-equal check for the lower range of each case:

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x >= 5 && x < 9):
        alert("between 5 and 8");
        break;
    case (x >= 9 && x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

Keep in mind that this adds an extra point of human error - someone may try to update a range, but forget to change it in both places, leaving an overlap or gap that is not covered. e.g. here the case of 8 will now not match anything when I just edit the case that used to match 8.

    case (x >= 5 && x < 8):
        alert("between 5 and 7");
        break;
    case (x >= 9 && x < 12):
        alert("between 9 and 11");
        break;

How to send custom headers with requests in Swagger UI?

Also it's possible to use attribute [FromHeader] for web methods parameters (or properties in a Model class) which should be sent in custom headers. Something like this:

[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)

At least it works fine for ASP.NET Core 2.1 and Swashbuckle.AspNetCore 2.5.0.

How to set null value to int in c#?

 public static int? Timesaday { get; set; } = null;

OR

 public static Nullable<int> Timesaday { get; set; }

or

 public static int? Timesaday = null;

or

 public static int? Timesaday

or just

 public static int? Timesaday { get; set; } 


    static void Main(string[] args)
    {


    Console.WriteLine(Timesaday == null);

     //you also can check using 
     Console.WriteLine(Timesaday.HasValue);

        Console.ReadKey();
    }

The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

No output to console from a WPF application?

I've create a solution, mixed the information of varius post.

Its a form, that contains a label and one textbox. The console output is redirected to the textbox.

There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.

The forms is called FrmConsole. Here are the XAML and the c# code.

The use is very simple:

ConsoleView.Show("Title of the Console");

For open the console. Use:

System.Console.WriteLine("The debug message");

For output text to the console.

Use:

ConsoleView.Close();

For Close the console.

ConsoleView.Release();

Leaves open the console and enables the Close button

XAML

<Window x:Class="CustomControls.FrmConsole"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CustomControls"
    mc:Ignorable="d"
    Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="10"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
    </Grid>
    <Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>

The code of the Window:

partial class FrmConsole : Window
{
    private class ControlWriter : TextWriter
    {
        private TextBox textbox;
        public ControlWriter(TextBox textbox)
        {
            this.textbox = textbox;
        }

        public override void WriteLine(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void WriteLine(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.ScrollToEnd();
            }));
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }

        }
    }

    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE

    #endregion


    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    public FrmConsole(string titulo)
    {
        InitializeComponent();
        lblTitulo.Content = titulo;
        Clear();
        btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
        Console.SetOut(new ControlWriter(txtInner));
        DesactivarCerrar();
    }

    #endregion


    //PROPIEDADES
    #region PROPIEDADES

    #endregion


    //DELEGADOS
    #region DELEGADOS

    private void BtnCerrar_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    #endregion


    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public void ActivarCerrar()
    {
        btnCerrar.IsEnabled = true;
    }

    public void Clear()
    {
        txtInner.Clear();
    }

    public void DesactivarCerrar()
    {
        btnCerrar.IsEnabled = false;
    }

    #endregion  
}

the code of ConsoleView class

static public class ConsoleView
{
    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE
    static FrmConsole console;
    static Thread StatusThread;
    static bool isActive = false;
    #endregion

    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    #endregion

    //PROPIEDADES
    #region PROPIEDADES

    #endregion

    //DELEGADOS
    #region DELEGADOS

    #endregion

    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public static void Show(string label)
    {
        if (isActive)
        {
            return;
        }

        isActive = true;
        //create the thread with its ThreadStart method
        StatusThread = new Thread(() =>
        {
            try
            {
                console = new FrmConsole(label);
                console.ShowDialog();
                //this call is needed so the thread remains open until the dispatcher is closed
                Dispatcher.Run();
            }
            catch (Exception)
            {
            }
        });

        //run the thread in STA mode to make it work correctly
        StatusThread.SetApartmentState(ApartmentState.STA);
        StatusThread.Priority = ThreadPriority.Normal;
        StatusThread.Start();

    }

    public static void Close()
    {
        isActive = false;
        if (console != null)
        {
            //need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
            console.Dispatcher.InvokeShutdown();
            console = null;
            StatusThread = null;
        }

        console = null;
    }

    public static void Release()
    {
        isActive = false;
        if (console != null)
        {
            console.Dispatcher.Invoke(console.ActivarCerrar);
        }

    }
    #endregion
}

I hope this result usefull.

Count Rows in Doctrine QueryBuilder

To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:

   //in repository class:
   $count = $qb->select('count(p.id)')
      ->from('Products', 'p')
      ->getQuery()
      ->getSingleScalarResult();

    return $count;

    //in controller class:
    $count = $this->em->getRepository('RepositoryBundle')->...

    return $count-$offset;

Anybody knows more clean way to do it?

Extracting extension from filename in Python

def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

Getting current device language in iOS?

Simple Swift 3 function:

@discardableResult
func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
}

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

how to stop a for loop

Others ways to do the same is:

el = L[0][0]
m=len(L)

print L == [[el]*m]*m

Or:

first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

SQL: Two select statements in one query

select name, games, goals
from tblMadrid where name = 'ronaldo'
union
select name, games, goals
from tblBarcelona where name = 'messi'
ORDER  BY goals 

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

SSIS Excel Import Forcing Incorrect Column Type

;IMEX=1; is not always working... Everything about mixed datatypes in Excel: Mixed data types in Excel column

enter image description here

bootstrap datepicker today as default

Perfect Picker with current date and basic settings

        //Datepicker
        $('.datepicker').datepicker({
            autoclose: true,
            format: "yyyy-mm-dd",
            immediateUpdates: true,
            todayBtn: true,
            todayHighlight: true
        }).datepicker("setDate", "0");

Can I apply the required attribute to <select> fields in HTML5?

You need to set the value attribute of option to the empty string:

<select name="status" required>
    <option selected disabled value="">what's your status?</option>
    <option value="code">coding</option>
    <option value="sleep">sleeping</option>
</select>

select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input -> raising the required message.


w3schools

The value attribute specifies the value to be sent to a server when a form is submitted.

Example

C# Help reading foreign characters using StreamReader

Using Encoding.Unicode won't accurately decode an ANSI file in the same way that a JPEG decoder won't understand a GIF file.

I'm surprised that Encoding.Default didn't work for the ANSI file if it really was ANSI - if you ever find out exactly which code page Notepad was using, you could use Encoding.GetEncoding(int).

In general, where possible I'd recommend using UTF-8.

jQuery javascript regex Replace <br> with \n

myString.replace(/<br ?\/?>/g, "\n")

VB.NET: Clear DataGridView

Don't do anything on DataGridView, just clear the data source. I tried clearing myDataset.clear() method, then it worked.

How to Calculate Execution Time of a Code Snippet in C++

I have another working example that uses microseconds (UNIX, POSIX, etc).

    #include <sys/time.h>
    typedef unsigned long long timestamp_t;

    static timestamp_t
    get_timestamp ()
    {
      struct timeval now;
      gettimeofday (&now, NULL);
      return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
    }

    ...
    timestamp_t t0 = get_timestamp();
    // Process
    timestamp_t t1 = get_timestamp();

    double secs = (t1 - t0) / 1000000.0L;

Here's the file where we coded this:

https://github.com/arhuaco/junkcode/blob/master/emqbit-bench/bench.c