Programs & Examples On #Optional variables

How do I hide an element when printing a web page?

You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):

<div id="printOption">
    <a href="javascript:void();" 
       onclick="document.getElementById('printOption').style.visibility = 'hidden'; 
       document.print(); 
       return true;">
       Print
    </a>
</div>

The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).

The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.

How do you add a scroll bar to a div?

Css class to have a nice Div with scroll

.DivToScroll{   
    background-color: #F5F5F5;
    border: 1px solid #DDDDDD;
    border-radius: 4px 0 4px 0;
    color: #3B3C3E;
    font-size: 12px;
    font-weight: bold;
    left: -1px;
    padding: 10px 7px 5px;
}

.DivWithScroll{
    height:120px;
    overflow:scroll;
    overflow-x:hidden;
}

Importing CSV File to Google Maps

For generating the KML file from your CSV file (or XLS), you can use MyGeodata online GIS Data Converter. Here is the CSV to KML How-To.

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

jQuery: how to get which button was clicked upon form submission?

I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:

My .cshtml form:

<div class="form-group" id="buttons_grp">
    <button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
    <button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
    <button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
    ...

The jQuery submit handler:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
    $(document).ready(function() {
    ...
    // Ensure that we log an explanatory comment if "Reject"
    $('#update_task_form').on('submit', function (e) {
        let text = e.originalEvent.submitter.textContent;
        if (text == "Reject") {
           // Do stuff...
        }
    });
    ...

The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.

Can Selenium WebDriver open browser windows silently in the background?

There are a few ways, but it isn't a simple "set a configuration value". Unless you invest in a headless browser, which doesn't suit everyone's requirements, it is a little bit of a hack:

How to hide Firefox window (Selenium WebDriver)?

and

Is it possible to hide the browser in Selenium RC?

You can 'supposedly', pass in some parameters into Chrome, specifically: --no-startup-window

Note that for some browsers, especially Internet Explorer, it will hurt your tests to not have it run in focus.

You can also hack about a bit with AutoIt, to hide the window once it's opened.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Is Task.Result the same as .GetAwaiter.GetResult()?

If a task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult(). Rather than calling GetResult, we could simply access the Result property of the task. The benefit of calling GetResult is that if the task faults, the exception is thrown directly without being wrapped in AggregateException, allowing for simpler and cleaner catch blocks.

For nongeneric tasks, GetResult() has a void return value. Its useful function is then solely to rethrow exceptions.

source : c# 7.0 in a Nutshell

How to stop BackgroundWorker correctly

I agree with guys. But sometimes you have to add more things.

IE

1) Add this worker.WorkerSupportsCancellation = true;

2) Add to you class some method to do the following things

public void KillMe()
{
   worker.CancelAsync();
   worker.Dispose();
   worker = null;
   GC.Collect();
}

So before close your application your have to call this method.

3) Probably you can Dispose, null all variables and timers which are inside of the BackgroundWorker.

How to make div fixed after you scroll to that div?

jquery function is most important

<script>
$(function(){
    var stickyHeaderTop = $('#stickytypeheader').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('#stickytypeheader').css({position: 'fixed', top: '0px'});
                    $('#sticky').css('display', 'block');
            } else {
                    $('#stickytypeheader').css({position: 'static', top: '0px'});
                    $('#sticky').css('display', 'none');
            }
    });
});
</script>

Then use JQuery Lib...

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

Now use HTML

<div id="header">
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
 </div>

<div id="stickytypeheader">
 <table width="100%">
  <tr>
    <td><a href="http://growthpages.com/">Growth pages</a></td>

    <td><a href="http://google.com/">Google</a></td>

    <td><a href="http://yahoo.com/">Yahoo</a></td>

    <td><a href="http://www.bing.com/">Bing</a></td>

    <td><a href="#">Visitor</a></td>
  </tr>
 </table>
</div>

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>

Check DEMO HERE

Convert Datetime column from UTC to local time in select statement

This can be done without a function. Code below will convert a UTC time to Mountain time accounting for daylight savings. Adjust all the -6 and -7 numbers to your timezone accordingly (i.e. for EST you would adjust to -4 and -5 respectively)

--Adjust a UTC value, in the example the UTC field is identified as UTC.Field, to account for daylight savings time when converting out of UTC to Mountain time.
CASE
    --When it's between March and November, it is summer time which is -6 from UTC
    WHEN MONTH ( UTC.Field ) > 3 AND MONTH ( UTC.Field ) < 11 
        THEN DATEADD ( HOUR , -6 , UTC.Field )
    --When its March and the day is greater than the 14, you know it's summer (-6)
    WHEN MONTH ( UTC.Field ) = 3
        AND DATEPART ( DAY , UTC.Field ) >= 14 
        THEN
            --However, if UTC is before 9am on that Sunday, then it's before 2am Mountain which means it's still Winter daylight time.
            CASE 
                WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1 
                    AND UTC.Field < '9:00'
                    --Before 2am mountain time so it's winter, -7 hours for Winter daylight time
                    THEN DATEADD ( HOUR , -7 , UTC.Field )
                --Otherwise -6 because it'll be after 2am making it Summer daylight time
                ELSE DATEADD ( HOUR , -6 , UTC.Field )
            END
    WHEN MONTH ( UTC.Field ) = 3
        AND ( DATEPART ( WEEKDAY , UTC.Field ) + 7 ) <= DATEPART ( day , UTC.Field ) 
        THEN 
            --According to the date, it's moved onto Summer daylight, but we need to account for the hours leading up to 2am if it's Sunday
            CASE 
                WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1 
                    AND UTC.Field < '9:00'
                    --Before 9am UTC is before 2am Mountain so it's winter Daylight, -7 hours
                    THEN DATEADD ( HOUR , -7 , UTC.Field )
                --Otherwise, it's summer daylight, -6 hours
                ELSE DATEADD ( HOUR , -6 , UTC.Field )
            END
    --When it's November and the weekday is greater than the calendar date, it's still Summer so -6 from the time
    WHEN MONTH ( UTC.Field ) = 11
        AND DATEPART ( WEEKDAY , UTC.Field ) > DATEPART ( DAY , UTC.Field ) 
        THEN DATEADD ( HOUR , -6 , UTC.Field )
    WHEN MONTH ( UTC.Field ) = 11
        AND DATEPART ( WEEKDAY , UTC.Field ) <= DATEPART ( DAY , UTC.Field ) 
            --If the weekday is less than or equal to the calendar day it's Winter daylight but we need to account for the hours leading up to 2am.
            CASE 
                WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1 
                    AND UTC.Field < '8:00'
                    --If it's before 8am UTC and it's Sunday in the logic outlined, then it's still Summer daylight, -6 hours
                    THEN DATEADD ( HOUR , -6 , UTC.Field )
                --Otherwise, adjust for Winter daylight at -7
                ELSE DATEADD ( HOUR , -7 , UTC.Field )
            END
    --If the date doesn't fall into any of the above logic, it's Winter daylight, -7
    ELSE
        DATEADD ( HOUR , -7 , UTC.Field )
END

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

Create a unique number with javascript time

This performs faster than creating a Date instance, uses less code and will always produce a unique number (locally):

function uniqueNumber() {
    var date = Date.now();

    // If created at same millisecond as previous
    if (date <= uniqueNumber.previous) {
        date = ++uniqueNumber.previous;
    } else {
        uniqueNumber.previous = date;
    }

    return date;
}

uniqueNumber.previous = 0;

jsfiddle: http://jsfiddle.net/j8aLocan/

I've released this on Bower and npm: https://github.com/stevenvachon/unique-number

You could also use something more elaborate such as cuid, puid or shortid to generate a non-number.

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

Understanding checked vs unchecked exceptions in Java

Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?

For example let say you have some client-server application and client had made a request for some resource that couldn't be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn't get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.

Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.

How to check for changes on remote (origin) Git repository

A good way to have a synthetic view of what's going on "origin" is:

git remote show origin

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

Why is enum class preferred over plain enum?

Enumerations are used to represent a set of integer values.

The class keyword after the enum specifies that the enumeration is strongly typed and its enumerators are scoped. This way enum classes prevents accidental misuse of constants.

For Example:

enum class Animal{Dog, Cat, Tiger};
enum class Pets{Dog, Parrot};

Here we can not mix Animal and Pets values.

Animal a = Dog;       // Error: which DOG?    
Animal a = Pets::Dog  // Pets::Dog is not an Animal

How to resolve the error on 'react-native start'

You can go to...

\node_modules\metro-config\src\defaults\blacklist.js and change...

var sharedBlacklist = [   /node_modules[/\\]react[/\\]dist[/\\].*/,  
/website\/node_modules\/.*/,   /heapCapture\/bundle\.js/,  
/.*\/__tests__\/.*/ ];

for this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Change header text of columns in a GridView

Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.

ASPX:

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
    <Columns>
        <asp:BoundField HeaderText="Date" DataField="CreatedDate" />
    </Columns>
</asp:GridView>

CS:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
            {
                e.Row.Cells[i].Text = "Created Date";
            }
        }
    }
}

htmlentities() vs. htmlspecialchars()

One small example, I needed to have 2 client names indexed in a function:

[1] => Altisoxxce Soluxxons S.à r.l.
[5] => Joxxson & Joxxson

I originally $term = get_term_by('name', htmlentities($name), 'client'); which resulted in term names that only included the ampersand array item (&) but not the accented item. But when I changed the variable setting to htmlspecialchars both were able to run through the function. Hope this helps!

Get user info via Google API

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

Powershell import-module doesn't find modules

The module needs to be placed in a folder with the same name as the module. In your case:

$home/WindowsPowerShell/Modules/XMLHelpers/

The full path would be:

$home/WindowsPowerShell/Modules/XMLHelpers/XMLHelpers.psm1

You would then be able to do:

import-module XMLHelpers

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How to add a custom HTTP header to every WCF call?

A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.

Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.

John

SQL Query for Student mark functionality

I would have said:

select s.stname, s2.subname, highmarks.mark
from students s
join marks m on s.stid = m.stid
join Subject s2 on m.subid = s2.subid
join (select subid, max(mark) as mark
  from marks group by subid) as highmarks
    on highmarks.subid = m.subid and highmarks.mark = m.mark
order by subname, stname;

SQLFiddle here: http://sqlfiddle.com/#!2/5ef84/3

This is a:

  • select on the students table to get the possible students
  • a join to the marks table to match up students to marks,
  • a join to the subjects table to resolve subject ids into names.
  • a join to a derived table of the maximum marks in each subject.

Only the students that get maximum marks will meet all three join conditions. This lists all students who got that maximum mark, so if there are ties, both get listed.

What is the meaning of polyfills in HTML5?

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support canvas (an HTML5 feature) in older browsers.

It's sort of an HTML5 technique, since it is used in conjunction with HTML5, but it's not part of HTML5, and you can have polyfills without having HTML5 (for example, to support CSS3 techniques you want).

Here's a good post:

http://remysharp.com/2010/10/08/what-is-a-polyfill/

Here's a comprehensive list of Polyfills and Shims:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

How to comment/uncomment in HTML code

you can try to replace --> with a different string say, #END# and do search and replace with your editor when you wish to return the closing tags.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Shall we always use [unowned self] inside closure in Swift

I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

  • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
  • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

    class MyViewController: UIViewController {
          @IBOutlet weak var myButton: UIButton!
          let networkManager = NetworkManager()
          let buttonPressClosure: () -> Void // closure must be held in this class. 
    
          override func viewDidLoad() {
              // use unowned here
              buttonPressClosure = { [unowned self] in
                  self.changeDisplayViewMode() // won't happen after vc closes. 
              }
              // use weak here
              networkManager.fetch(query: query) { [weak self] (results, error) in
                  self?.updateUI() // could be called any time after vc closes
              }
          }
          @IBAction func buttonPress(self: Any) {
             buttonPressClosure()
          }
    
          // rest of class below.
     }
    

Returning a file to View/Download in ASP.NET MVC

I believe this answer is cleaner, (based on https://stackoverflow.com/a/3007668/550975)

    public ActionResult GetAttachment(long id)
    {
        FileAttachment attachment;
        using (var db = new TheContext())
        {
            attachment = db.FileAttachments.FirstOrDefault(x => x.Id == id);
        }

        return File(attachment.FileData, "application/force-download", Path.GetFileName(attachment.FileName));
    }

Generate a Hash from string in Javascript

Based on accepted answer in ES6. Smaller, maintainable and works in modern browsers.

_x000D_
_x000D_
function hashCode(str) {_x000D_
  return str.split('').reduce((prevHash, currVal) =>_x000D_
    (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);_x000D_
}_x000D_
_x000D_
// Test_x000D_
console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));
_x000D_
_x000D_
_x000D_

EDIT (2019-11-04):

one-liner arrow function version :

_x000D_
_x000D_
const hashCode = s => s.split('').reduce((a,b) => (((a << 5) - a) + b.charCodeAt(0))|0, 0)_x000D_
_x000D_
// test_x000D_
console.log(hashCode('Hello!'))
_x000D_
_x000D_
_x000D_

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

How to create an Observable from static data similar to http one in Angular?

Perhaps you could try to use the of method of the Observable class:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

Index of Currently Selected Row in DataGridView

Try it:

int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());

I hope it will help you.

Java and SQLite

There is a new project SQLJet that is a pure Java implementation of SQLite. It doesn't support all of the SQLite features yet, but may be a very good option for some of the Java projects that work with SQLite databases.

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

how to check if input field is empty

if you are using jquery-validate.js in your application then use below expression.

if($("#spa").is(":blank"))
{
  //code
}

RecyclerView - Get view at particular position

You can simply use "findViewHolderForAdapterPosition" method of recycler view and you will get a viewHolder object from that then typecast that viewholder into your adapter viewholder so you can directly access your viewholder's views

following is the sample code for kotlin

 val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
 val textview=(viewHolder as YourViewHolder).yourTextView

IndentationError: unexpected unindent WHY?

It's because you have:

def readTTable(fname):
    try:

without a matching except block after the try: block. Every try must have at least one matching except.

See the Errors and Exceptions section of the Python tutorial.

List of IP addresses/hostnames from local network in Python

I have collected the following functionality from some other threads and it works for me in Ubuntu.

import os
import socket    
import multiprocessing
import subprocess
import os


def pinger(job_q, results_q):
    """
    Do Ping
    :param job_q:
    :param results_q:
    :return:
    """
    DEVNULL = open(os.devnull, 'w')
    while True:

        ip = job_q.get()

        if ip is None:
            break

        try:
            subprocess.check_call(['ping', '-c1', ip],
                                  stdout=DEVNULL)
            results_q.put(ip)
        except:
            pass


def get_my_ip():
    """
    Find my IP address
    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = s.getsockname()[0]
    s.close()
    return ip


def map_network(pool_size=255):
    """
    Maps the network
    :param pool_size: amount of parallel ping processes
    :return: list of valid ip addresses
    """

    ip_list = list()

    # get my IP and compose a base like 192.168.1.xxx
    ip_parts = get_my_ip().split('.')
    base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.'

    # prepare the jobs queue
    jobs = multiprocessing.Queue()
    results = multiprocessing.Queue()

    pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]

    for p in pool:
        p.start()

    # cue hte ping processes
    for i in range(1, 255):
        jobs.put(base_ip + '{0}'.format(i))

    for p in pool:
        jobs.put(None)

    for p in pool:
        p.join()

    # collect he results
    while not results.empty():
        ip = results.get()
        ip_list.append(ip)

    return ip_list


if __name__ == '__main__':

    print('Mapping...')
    lst = map_network()
    print(lst)

invalid use of non-static data member

In C++, nested classes are not connected to any instance of the outer class. If you want bar to access non-static members of foo, then bar needs to have access to an instance of foo. Maybe something like:

class bar {
  public:
    int getA(foo & f ) {return foo.a;}
};

Or maybe

class bar {
  private:
    foo & f;

  public:
    bar(foo & g)
    : f(g)
    {
    }

    int getA() { return f.a; }
};

In any case, you need to explicitly make sure you have access to an instance of foo.

CSS3 transition events

Update

All modern browsers now support the unprefixed event:

element.addEventListener('transitionend', callback, false);

https://caniuse.com/#feat=css-transitions


I was using the approach given by Pete, however I have now started using the following

$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', 
function() {
 //do something
});

Alternatively if you use bootstrap then you can simply do

$(".myClass").one($.support.transition.end,
function() {
 //do something
});

This is becuase they include the following in bootstrap.js

+function ($) {
  'use strict';

  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      'WebkitTransition' : 'webkitTransitionEnd',
      'MozTransition'    : 'transitionend',
      'OTransition'      : 'oTransitionEnd otransitionend',
      'transition'       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }

    return false // explicit for ie8 (  ._.)
  }


  $(function () {
    $.support.transition = transitionEnd()
  })

}(jQuery);

Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false, $el = this
    $(this).one($.support.transition.end, function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.

http://blog.alexmaccaw.com/css-transitions

How to format x-axis time scale values in Chart.js v2

Just set all the selected time unit's displayFormat to MMM DD

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
           'millisecond': 'MMM DD',
           'second': 'MMM DD',
           'minute': 'MMM DD',
           'hour': 'MMM DD',
           'day': 'MMM DD',
           'week': 'MMM DD',
           'month': 'MMM DD',
           'quarter': 'MMM DD',
           'year': 'MMM DD',
        }
        ...

Notice that I've set all the unit's display format to MMM DD. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'day',
        unitStepSize: 1,
        displayFormats: {
           'day': 'MMM DD'
        }
        ...

Fiddle - http://jsfiddle.net/prfd1m8q/

In PANDAS, how to get the index of a known value?

The other way around using numpy.where() :

import numpy as np
import pandas as pd

In [800]: df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])

In [801]: df
Out[801]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [802]: np.where(df["c1"]==6)
Out[802]: (array([3]),)

In [803]: indices = list(np.where(df["c1"]==6)[0])

In [804]: df.iloc[indices]
Out[804]: 
   c1  c2
3   6   7

In [805]: df.iloc[indices].index
Out[805]: Int64Index([3], dtype='int64')

In [806]: df.iloc[indices].index.tolist()
Out[806]: [3]

Get the distance between two geo points

Just use the following method, pass it lat and long and get distance in meter:

private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
    double R = 6371000f; // Radius of the earth in m
    double dLat = (lat1 - lat2) * Math.PI / 180f;
    double dLon = (lon1 - lon2) * Math.PI / 180f;
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c;
    return d;
}

When and how should I use a ThreadLocal variable?

Since Java 8 release, there is more declarative way to initialize ThreadLocal:

ThreadLocal<Cipher> local = ThreadLocal.withInitial(() -> "init value");

Until Java 8 release you had to do the following:

ThreadLocal<String> local = new ThreadLocal<String>(){
    @Override
    protected String initialValue() {
        return "init value";
    }
};

Moreover, if instantiation method (constructor, factory method) of class that is used for ThreadLocal does not take any parameters, you can simply use method references (introduced in Java 8):

class NotThreadSafe {
    // no parameters
    public NotThreadSafe(){}
}

ThreadLocal<NotThreadSafe> container = ThreadLocal.withInitial(NotThreadSafe::new);

Note: Evaluation is lazy since you are passing java.util.function.Supplier lambda that is evaluated only when ThreadLocal#get is called but value was not previously evaluated.

Convert ArrayList to String array in Android

try this

List<String> list = new ArrayList<String>();
list.add("List1");
list.add("List2");

String[] listArr = new String[list.size()];
listArr = list.toArray(listArr );

for(String s : listArr )
    System.out.println(s);

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first version is preferable:

  • It works for all kinds of keys, so you can, for example, say {1: 'one', 2: 'two'}. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency.
  • It is faster:

    $ python -m timeit "dict(a='value', another='value')"
    1000000 loops, best of 3: 0.79 usec per loop
    $ python -m timeit "{'a': 'value','another': 'value'}"
    1000000 loops, best of 3: 0.305 usec per loop
    
  • If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

How do I put the image on the right side of the text in a UIButton?

Building on Piotr Tomasik's elegant solution: if you want to have a bit of spacing between the button label and image as well, then include that in your edge insets as follows (copying my code here that works perfectly for me):

    CGFloat spacing          = 3;
    CGFloat insetAmount      = 0.5 * spacing;

    // First set overall size of the button:
    button.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
    [button sizeToFit];

    // Then adjust title and image insets so image is flipped to the right and there is spacing between title and image:
    button.titleEdgeInsets   = UIEdgeInsetsMake(0, -button.imageView.frame.size.width - insetAmount, 0,  button.imageView.frame.size.width  + insetAmount);
    button.imageEdgeInsets   = UIEdgeInsetsMake(0, button.titleLabel.frame.size.width + insetAmount, 0, -button.titleLabel.frame.size.width - insetAmount);

Thanks Piotr for your solution!

Erik

How to show multiline text in a table cell

For my case, I can use like this.

td { white-space:pre-line , word-break: break-all}

Can Windows Containers be hosted on linux?

Solution 1 - Using VirtualBox

As Muhammad Sahputra suggested in this post, it is possible to run Windows OS inside VirtualBox (using VBoxHeadless - without graphical interface) inside Docker container.

Also, a NAT setup inside the VM network configurations can do a port forwarding which gives you the ability to pass-through any traffic that comes to and from the Docker container. This eventually, in a wide perspective, allows you to run any Windows-based service on top of Linux machine.

Maybe this is not a typical use-case of a Docker container, but it definitely an interesting approach to the problem.


Solution 2 - Using Wine

For simple applications and maybe more complicated, you can try to use wine inside a docker container.

This docker hub page may help you to achieve your goal.


I hope that Docker will release a native solution soon, like they did with docker-machine on Windows several years ago.

How to process each output line in a loop?

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done

Can I open a dropdownlist using jQuery

Super simple:

var state = false;
$("a").click(function () {
    state = !state;
    $("select").prop("size", state ? $("option").length : 1);
});

how to count the spaces in a java string?

The most precise and exact plus fastest way to that is :

String Name="Infinity War is a good movie";

    int count =0;

    for(int i=0;i<Name.length();i++){
    if(Character.isWhitespace(Name.charAt(i))){
    count+=1;
        }
    }

    System.out.println(count);

Get MIME type from filename extension

You can use MimeMappings class. I think this is the easiest way. I give import of MimeMappings too. because I felt lots of trouble to find import of those classes.

import org.springframework.boot.web.server.MimeMappings;    
MimeMappings mm=new MimeMappings();
String mimetype = mm.get(fileExtension);
System.out.println(mimetype);

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

Remove duplicates in the list using linq

Try this extension method out. Hopefully this could help.

public static class DistinctHelper
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var identifiedKeys = new HashSet<TKey>();
        return source.Where(element => identifiedKeys.Add(keySelector(element)));
    }
}

Usage:

var outputList = sourceList.DistinctBy(x => x.TargetProperty);

How do I fix the multiple-step OLE DB operation errors in SSIS?

For me the answer was that I was passing two parameters to and execute SQL task, but only using one. I was doing some testing and commented out a section of code using the second parameter. I neglected to remove the parameter mapping.

So ensure you are passing in the correct number of parameters in the parameter mapping if you are using the Execute SQL task.

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

The main reason for this issue will only come from chrome and chrome handles WWW and non www differently depending on how you entered your URL in the browsers and it searches from google and directly shows the results, so the redirection URL sent is different in a different case

enter image description here

Add all the possible combinations you can find the exact url sent from fiddler , the 400 error pop up will not give you the exact http and www infromation

How to shrink temp tablespace in oracle?

alter database datafile  'C:\ORA_SERVER\ORADATA\AXAPTA\AX_DATA.ORA' resize 40M;

If it doesn't help:

  • Create new tablespace
  • Switch to new temporary tablespace
  • Wait until old tablespace will not be used
  • Delete old tablespace

What is token-based authentication?

A token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

Source (Web Archive)

Turn Pandas Multi-Index into column

I ran into Karl's issue as well. I just found myself renaming the aggregated column then resetting the index.

df = pd.DataFrame(df.groupby(['arms', 'success'])['success'].sum()).rename(columns={'success':'sum'})

enter image description here

df = df.reset_index()

enter image description here

Oracle: is there a tool to trace queries, like Profiler for sql server?

Try PL/SQL Developer it has a nice user friendly GUI interface to the profiler. It's pretty nice give the trial a try. I swear by this tool when working on Oracle databases.

http://www.allroundautomations.com/plsqldev.html?gclid=CM6pz8e04p0CFQjyDAodNXqPDw

Get an object attribute

To access field or method of an object use dot .:

user = User()
print user.fullName

If a name of the field will be defined at run time, use buildin getattr function:

field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName

What does the "yield" keyword do?

yield in python is in a way similar to the return statement, except for some differences. If multiple values have to be returned from a function, return statement will return all the values as a list and it has to be stored in the memory in the caller block. But what if we don't want to use extra memory? Instead, we want to get the value from the function when we need it. This is where yield comes in. Consider the following function :-

def fun():
   yield 1
   yield 2
   yield 3

And the caller is :-

def caller():
   print ('First value printing')
   print (fun())
   print ('Second value printing')
   print (fun())
   print ('Third value printing')
   print (fun())

The above code segment (caller function) when called, outputs :-

First value printing
1
Second value printing
2
Third value printing
3

As can be seen from above, yield returns a value to its caller, but when the function is called again, it doesn't start from the first statement, but from the statement right after the yield. In the above example, "First value printing" was printed and the function was called. 1 was returned and printed. Then "Second value printing" was printed and again fun() was called. Instead of printing 1 (the first statement), it returned 2, i.e., the statement just after yield 1. The same process is repeated further.

Maximum Length of Command Line String

Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.

TypeError: '<=' not supported between instances of 'str' and 'int'

input() by default takes the input in form of strings.

if (0<= vote <=24):

vote takes a string input (suppose 4,5,etc) and becomes uncomparable.

The correct way is: vote = int(input("Enter your message")will convert the input to integer (4 to 4 or 5 to 5 depending on the input)

Setting a divs background image to fit its size?

Set your css to this

img {
    max-width:100%,
    max-height100%
}

MySQL - Make an existing Field Unique

CREATE UNIQUE INDEX foo ON table_name (field_name)

You have to remove duplicate values on that column before executes that sql. Any existing duplicate value on that column will lead you to mysql error 1062

How to find the kafka version in linux

Simple way on macOS e.g. installed via homebrew

$ ls -l $(which kafka-topics)
/usr/local/bin/kafka-topics -> ../Cellar/kafka/0.11.0.1/bin/kafka-topics

How to select a column name with a space in MySQL

I think double quotes works too:

SELECT "Business Name","Other Name" FROM your_Table

But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.

Unable to find velocity template resources

VelocityEngine velocityEngin = new VelocityEngine();
velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

velocityEngin.init();

Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");

you could use the above code to set the properties for velocity template. You can then give the name of the tempalte file when initializing the Template and it will find if it exists in the classpath.

All the above classes come from package org.apache.velocity*

How to sort two lists (which reference each other) in the exact same way

If you are using numpy you can use np.argsort to get the sorted indices and apply those indices to the list. This works for any number of list that you would want to sort.

import numpy as np

arr1 = np.array([4,3,1,32,21])
arr2 = arr1 * 10
sorted_idxs = np.argsort(arr1)

print(sorted_idxs)
>>> array([2, 1, 0, 4, 3])

print(arr1[sorted_idxs])
>>> array([ 1,  3,  4, 21, 32])

print(arr2[sorted_idxs])
>>> array([ 10,  30,  40, 210, 320])

Convert HTML to NSAttributedString in iOS

The built in conversion always sets the text color to UIColor.black, even if you pass an attributes dictionary with .forgroundColor set to something else. To support DARK mode on iOS 13, try this version of the extension on NSAttributedString.

extension NSAttributedString {
    internal convenience init?(html: String)                    {
        guard 
            let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

        let options : [DocumentReadingOptionKey : Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        guard
            let string = try? NSMutableAttributedString(data: data, options: options,
                                                 documentAttributes: nil) else { return nil }

        if #available(iOS 13, *) {
            let colour = [NSAttributedString.Key.foregroundColor: UIColor.label]
            string.addAttributes(colour, range: NSRange(location: 0, length: string.length))
        }

        self.init(attributedString: string)
    }
}

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

Pip install - Python 2.7 - Windows 7

you have to first download the get-pip.py and then run the command :

python get-pip.py

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Another reason this can happen:

The component you are using formControl in is not declared in a module that imports the ReactiveFormsModule.

So check the module that declares the component that throws this error.

Hover and Active only when not disabled

You can use :enabled pseudo-class, but notice IE<9 does not support it:

button:hover:enabled{
    /*your styles*/
}
button:active:enabled{
    /*your styles*/
}

How do I write a backslash (\) in a string?

txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";

Put a double backslash instead of a single backslash...

Intent from Fragment to Activity

Hope this code will help

public class ThisFragment extends Fragment {

public Button button = null;
Intent intent;

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

    View rootView = inflater.inflate(R.layout.yourlayout, container, false);

    intent = new Intent(getActivity(), GoToThisActivity.class);
    button = (Button) rootView.findViewById(R.id.theButtonid);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(intent);
        }
    });
    return rootView;
}

You can use this code, make sure you change "ThisFragment" as your fragment name, "yourlayout" as the layout name, "GoToThisActivity" change it to which activity do you want and then "theButtonid" change it with your button id you used.

Ajax LARAVEL 419 POST error

In your action you need first to load companies like so :

$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();

This will make the companies variable available in the view, and it should render the HTML correctly.

Try to use postman chrome extension to debug your view.

How to align the checkbox and label in same line in html?

If you are using bootstrap then use this class in the holding div

radio-inline

Example:

<label for="active" class="col-md-4 control-label">Active</label>
<div class="col-md-6 radio-inline">
    <input type="checkbox" name="active" value="1">
<div>

Here the label Active and the checkbox will appear to be aligned.

Clear the value of bootstrap-datepicker

you have to do it in that way:

$('#datepicker').datepicker('clearDates');

Android: Background Image Size (in Pixel) which Support All Devices

Android Devices Matrices

                            ldpi     mdpi     hdpi    xhdpi    xxhdpi      xxxhdpi
Launcher And Home           36*36    48*48   72*72    96*96    144*144     192*192
Toolbar And Tab             24*24    32*32   48*48    64*64    96*96       128*128
Notification                18*18    24*24   36*36    48*48    72*72       96*96 
Background                 240*320  320*480 480*800  768*1280  1080 *1920  1440*2560 

(For good approach minus Toolbar Size From total height of Background Screen and then Design Graphics of Screens )

For More Help (This link includes tablets also):

https://design.google.com/devices/

Android Native Icons (Recommended) You can change color of these icons programmatically. https://design.google.com/icons/

Auto height div with overflow and scroll when needed

This is a horizontal solution with the use of FlexBox and without the pesky absolute positioning.

_x000D_
_x000D_
body {_x000D_
  height: 100vh;_x000D_
  margin: 0;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
}_x000D_
_x000D_
#left,_x000D_
#right {_x000D_
  flex-grow: 1;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  background-color: lightgrey;_x000D_
  flex-basis: 33%;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  background-color: aliceblue;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-basis: 66%;_x000D_
  overflow: scroll;   /* other browsers */_x000D_
  overflow: overlay;  /* Chrome */_x000D_
}_x000D_
_x000D_
.item {_x000D_
  width: 150px;_x000D_
  background-color: darkseagreen;_x000D_
  flex-shrink: 0;_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <section id="left"></section>_x000D_
  <section id="right">_x000D_
    <div class="item"></div>_x000D_
    <div class="item"></div>_x000D_
    <div class="item"></div>_x000D_
  </section>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

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

firstly shouldn't

data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

be

data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

and secondly you can use

url: this.action + '?NonFormValue=' + NonFormValue,

or if the action already contains any parameters

url: this.action + '&NonFormValue=' + NonFormValue,

How to get text with Selenium WebDriver in Python

The answer is:

driver.find_element_by_class_name("ctsymbol").text

How to render a DateTime object in a Twig template

Dont forget

@ORM\HasLifecycleCallbacks()

Entity :

/**
     * Set gameDate
     *
     * @ORM\PrePersist
     */
    public function setGameDate()
    {
        $this->dateCreated = new \DateTime();

        return $this;
    }

View:

{{ item.gameDate|date('Y-m-d H:i:s') }}

>> Output 2013-09-18 16:14:20

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Converting Long to Date in Java returns 1970

It looks like your longs are seconds, and not milliseconds. Date constructor takes time as millis, so

Date d = new Date(timeInSeconds * 1000);

How do I convert a column of text URLs into active hyperlinks in Excel?

If adding an extra column with the hyperlinks is not an option, the alternative is to use an external editor to enclose your hyperlink into =hyperlink(" and "), in order to obtain =hyperlink("originalCellContent")

If you have Notepad++, this is a recipe you can use to perform this operation semi-automatically:

  • Copy the column of addresses to Notepad++
  • Keeping ALT-SHIFT pressed, extended your cursor from the top left corner to the bottom left corner, and type =hyperlink(". This adds =hyperlink(" at the beginning of each entry.
  • Open "Replace" menu (Ctrl-H), activate regular expressions (ALT-G), and replace $ (end of line) with "\). This adds a closed quote and a closed parenthesis (which needs to be escaped with \ when regular expressions are activated) at the end of each line.
  • Paste back the data in Excel. In practice, just copy the data and select the first cell of the column where you want the data to end up.

Cleanest way to reset forms

Add a reference to the ngForm directive in your html code and this gives you access to the form.

<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </form>

Or pass the form to the function:

<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this._postService.addPost(this.newPost);
    form.resetForm(); // or form.reset();
}

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.


Adding another example for people who can't get the above to work.

With button press:

<form #heroForm="ngForm">
    ...
    <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
</form>

Same thing applies above, you can also choose to pass the form to the newHero function.

How to get year/month/day from a date object?

EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.

function getFormattedDate(today) 
{
    var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var day  = week[today.getDay()];
    var dd   = today.getDate();
    var mm   = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    var hour = today.getHours();
    var minu = today.getMinutes();

    if(dd<10)  { dd='0'+dd } 
    if(mm<10)  { mm='0'+mm } 
    if(minu<10){ minu='0'+minu } 

    return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}

var date = new Date();
var text = getFormattedDate(date);


*For Spanish format, just translate the WEEK variable.

var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');


Output: Monday - 16/11/2015 14:24

How to fix "Headers already sent" error in PHP

Another bad practice can invoke this problem which is not stated yet.

See this code snippet:

<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>

Things are okay,right?

What if "a_important_file.php" is this:

<?php
//some php code 
//another line of php code
//no line above is generating any output
?>

 ----------This is the end of the an_important_file-------------------

This will not work? Why?Because already a new line is generated.

Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.

From PSR-2 2.2 :


  • All PHP files MUST use the Unix LF (linefeed) line ending.
  • All PHP files MUST end with a single blank line.
  • The closing ?> tag MUST be omitted from files containing only php

Believe me , following thse standards can save you a hell lot of hours from your life :)

How to set the authorization header using curl

(for those who are looking for php-curl answer)

$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate

$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);

var_dump($response);

How to extend an existing JavaScript array with another array, without creating a new array

The answer is super simple.

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
(The following code will combine the two arrays.)

a = a.concat(b);

>>> a
[1, 2, 3, 4, 5]

Concat acts very similarly to JavaScript string concatenation. It will return a combination of the parameter you put into the concat function on the end of the array you call the function on. The crux is that you have to assign the returned value to a variable or it gets lost. So for example

a.concat(b);  <--- This does absolutely nothing since it is just returning the combined arrays, but it doesn't do anything with it.

Java Runtime.getRuntime(): getting output from executing a command line program

Also we can use streams for obtain command output:

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

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }

React PropTypes : Allow different types of PropTypes for one prop

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

Javascript one line If...else...else if statement

This is use mostly for assigning variable, and it uses binomial conditioning eg.

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js

In Python, how to display current time in readable format

Take a look at the facilities provided by the time module

You have several conversion functions there.

Edit: see the datetime module for more OOP-like solutions. The time library linked above is kinda imperative.

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

do not forget to insert (or unCommanet) this line at the beginning of your pod file:

platform :iOS, '9.0'

that saves my day

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

set STATICBUILD=true && pip install lxml

run this command instead, must have VS C++ compiler installed first

https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/

It works for me with Python 3.5.2 and Windows 7

Firefox setting to enable cross domain Ajax request

You can check out my add on for firefox. It allows to cross domain in the lastest firefox version: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors/

How to process SIGTERM signal gracefully?

Based on the previous answers, I have created a context manager which protects from sigint and sigterm.

import logging
import signal
import sys


class TerminateProtected:
    """ Protect a piece of code from being killed by SIGINT or SIGTERM.
    It can still be killed by a force kill.

    Example:
        with TerminateProtected():
            run_func_1()
            run_func_2()

    Both functions will be executed even if a sigterm or sigkill has been received.
    """
    killed = False

    def _handler(self, signum, frame):
        logging.error("Received SIGINT or SIGTERM! Finishing this block, then exiting.")
        self.killed = True

    def __enter__(self):
        self.old_sigint = signal.signal(signal.SIGINT, self._handler)
        self.old_sigterm = signal.signal(signal.SIGTERM, self._handler)

    def __exit__(self, type, value, traceback):
        if self.killed:
            sys.exit(0)
        signal.signal(signal.SIGINT, self.old_sigint)
        signal.signal(signal.SIGTERM, self.old_sigterm)


if __name__ == '__main__':
    print("Try pressing ctrl+c while the sleep is running!")
    from time import sleep
    with TerminateProtected():
        sleep(10)
        print("Finished anyway!")
    print("This only prints if there was no sigint or sigterm")

What is the purpose of backbone.js?

Backbone was created by Jeremy Ashkenas who also wrote CoffeeScript. As a JavaScript-heavy application, what we now know as Backbone was responsible for structuring the application into a coherent code base. Underscore.js, backbone's only dependency, was also part of the DocumentCloud application.

Backbone helps developers manage a data model in their client-side web app with as much discipline and structure as you would get in traditional server-side application logic.

Additional benefits of using Backbone.js

  1. See Backbone as a library, not as a framework
  2. Javascript is now getting organized in a structured way, the (MVVM) Model
  3. Large user community

How do I force git pull to overwrite everything on every pull?

To pull a copy of the branch and force overwrite of local files from the origin use:

git reset --hard origin/current_branch

All current work will be lost and it will then be the same as the origin branch

jQuery.each - Getting li elements inside an ul

$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Scala: write string to file in one statement

Through the magic of the semicolon, you can make anything you like a one-liner.

import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
  , StandardCharsets.UTF_8
  , StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

How can I force a long string without any blank to be wrapped?

Use a CSS method to force wrap a string that has no white-spaces. Three methods:

1) Use the CSS white-space property. To cover browser inconsistencies, you have to declare it several ways. So just put your looooong string into some block level element (e.g., div, pre, p) and give that element the following css:

some_block_level_tag {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

2) use the force-wrap mixin from Compass.

3) I was just looking into this as well and I think might also work (but I need to test browser support more completely):

.break-me {
    word-wrap: break-word;
    overflow-wrap: break-word;
}

Reference: wrapping content

What is an Intent in Android?

From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013 link

The intent is understood in some small but effective lines

  1. Android supports a simple form of IPC(inter process communication) via intents
  2. Intent messaging is a framework for asynchronous communication among Android components (activity, service, content providers, broadcast receiver )
  3. Those components may run in the same or across different apps (i.e. processes)
  4. Enables both point-to-point as well as publish subscribe messaging domains
  5. The intent itself represents a message containing the description of the operation to be performed as well as data to be passed to the recipient(s).

From this thread a simple answer of android architect Dianne Hackborn states it as a data container which it actually is.

From android architecture point of view :

Intent is a data container that is used for inter process communication. It is built on top of the Binder from android architecture point of view.

How to put an image in div with CSS?

With Javascript/Jquery:

  • load image with hidden img
  • when image has been loaded, get width and height
  • dynamically create a div and set width, height and background
  • remove the original img

      $(document).ready(function() {
        var image = $("<img>");
        var div = $("<div>")
        image.load(function() {
          div.css({
            "width": this.width,
            "height": this.height,
            "background-image": "url(" + this.src + ")"
          });
          $("#container").append(div);
        });
        image.attr("src", "test0.png");
      });
    

How to add and remove classes in Javascript without jQuery

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

How to validate a file upload field using Javascript/jquery

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

How do you kill all current connections to a SQL Server 2005 database?

I've always used:


ALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO 
SP_RENAMEDB 'DB_NAME','DB_NAME_NEW'
Go 
ALTER DATABASE DB_NAME_NEW  SET MULTI_USER -- set back to multi user 
GO 

docker error - 'name is already in use by container'

When you are building a new image you often want to run a new container each time and with the same name. I found the easiest way was to start the container with the --rm option:

--rm        Automatically remove the container when it exits

e.g.

docker run --name my-micro-service --rm <image>

Sadly it's used almost randomly in the examples from the docs

How to make a function wait until a callback has been called using node.js

One way to achieve this is to wrap the API call into a promise and then use await to wait for the result.

// let's say this is the API function with two callbacks,
// one for success and the other for error
function apiFunction(query, successCallback, errorCallback) {
    if (query == "bad query") {
        errorCallback("problem with the query");
    }
    successCallback("Your query was <" + query + ">");
}

// myFunction wraps the above API call into a Promise
// and handles the callbacks with resolve and reject
function apiFunctionWrapper(query) {
    return new Promise((resolve, reject) => {
        apiFunction(query,(successResponse) => {
            resolve(successResponse);
        }, (errorResponse) => {
            reject(errorResponse);
        });
    });
}

// now you can use await to get the result from the wrapped api function
// and you can use standard try-catch to handle the errors
async function businessLogic() {
    try {
        const result = await apiFunctionWrapper("query all users");
        console.log(result);
        
        // the next line will fail
        const result2 = await apiFunctionWrapper("bad query");
    } catch(error) {
        console.error("ERROR:" + error);
    }
}

// call the main function
businessLogic();

Output:

Your query was <query all users>
ERROR:problem with the query

How do I search for an object by its ObjectId in the mongo console?

If you are working on the mongo shell, Please refer this : Answer from Tyler Brock

I wrote the answer if you are using mongodb using node.js

You don't need to convert the id into an ObjectId. Just use :

db.collection.findById('4ecbe7f9e8c1c9092c000027');

this collection method will automatically convert id into ObjectId.

On the other hand :

db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.

That can be done like this :

let id = '58c85d1b7932a14c7a0a320d';

let o_id = new ObjectId(id);   // id as a string is passed

db.collection.findOne({"_id":o_id});

SQL how to check that two tables has exactly the same data?

SELECT * 
FROM TABLE A
WHERE NOT EXISTS (SELECT 'X' 
                  FROM  TABLE B 
                  WHERE B.KEYFIELD1 = A.KEYFIELD1 
                  AND   B.KEYFIELD2 = A.KEYFIELD2 
                  AND   B.KEYFIELD3 = A.KEYFIELD3)
;

'X' is any value.

Switch the tables to see the different discrepancies.

Make sure to join the key fields in your tables.

Or just use the MINUS operator with 2 select statements, however, MINUS can only work in Oracle.

setting JAVA_HOME & CLASSPATH in CentOS 6

Search here for centos jre install all users:

The easiest way to set an environment variable in CentOS is to use export as in

$> export JAVA_HOME=/usr/java/jdk.1.5.0_12

$> export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots. In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile. For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case: Create a new file called java.sh

vim /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin

export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).

PS: If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

$> source java.sh

Liquibase lock - reasons?

In postgres 12 I needed to use this command:

UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

Differences between C++ string == and compare()?

If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.

Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.

MVC which submit button has been pressed

you can identify your button from there name tag like below, You need to check like this in you controller

if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

One obvious thing is that you will have to remove the comma here

receipt int(10),

but the actual problem is because of the line

amount double(10) NOT NULL,

change it to

amount double NOT NULL,

Full-screen iframe with a height of 100%

I ran into the same problem, I was pulling an iframe into a div. Try this:

<iframe src="http://stackoverflow.com/" frameborder="0" scrolling="yes" seamless="seamless" style="display:block; width:100%; height:100vh;"></iframe>

The height is set to 100vh which stands for viewport height. Also, the width could be set to 100vw, although you'll likely run into problems if the source file is responsive (your frame will become very wide).

Concatenating variables and strings in React

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

How to keep the header static, always on top while scrolling?

Instead of working with positioning and padding/margin and without knowing the header's size, there's a way to keep the header fixed by playing with the scroll.

See the this plunker with a fixed header:

<html lang="en" style="height: 100%">
<body style="height: 100%">
<div style="height: 100%; overflow: hidden">
  <div>Header</div>
  <div style="height: 100%; overflow: scroll">Content - very long Content...

The key here is a mix of height: 100% with overflow.

See a specific question on removing the scroll from the header here and answer here.

What does the "$" sign mean in jQuery or JavaScript?

The $ is just a function. It is actually an alias for the function called jQuery, so your code can be written like this with the exact same results:

jQuery('#Text').click(function () {
  jQuery('#Text').css('color', 'red');
});

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

This problem may also happen if your project set up to have the same intermediate directories in Project Properties -> Configuration Properties -> General

How to edit default dark theme for Visual Studio Code?

You cannot "edit" a default theme, they are "locked in"

However, you can copy it into your own custom theme, with the exact modifications you'd like.

For more info, see these articles: https://code.visualstudio.com/Docs/customization/themes https://code.visualstudio.com/docs/extensions/install-extension#_your-extensions-folder

If all you want to change is the colors for C++ code, you should look at overwriting the c++ support colorizer. For info about that, go here: https://code.visualstudio.com/docs/customization/colorizer

EDIT: The dark theme is found here: https://github.com/Microsoft/vscode/tree/80f8000c10b4234c7b027dccfd627442623902d2/extensions/theme-colorful-defaults

EDIT2: To clarify:

When should I use double or single quotes in JavaScript?

If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.

Streaming video from Android camera to server

I've built an open-source SDK called Kickflip to make streaming video from Android a painless experience.

The SDK demonstrates use of Android 4.3's MediaCodec API to direct the device hardware encoder's packets directly to FFmpeg for RTMP (with librtmp) or HLS streaming of H.264 / AAC. It also demonstrates realtime OpenGL Effects (titling, chroma key, fades) and background recording.

Thanks SO, and especially, fadden.

SQL Server CASE .. WHEN .. IN statement

Try this...

SELECT
    AlarmEventTransactionTableTable.TxnID,
    CASE
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                 '46', '48', '50', '137', '139',
                 '142', '143', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                 '47', '49', '51', '138', '140',
                 '141', '144', '165') THEN '02'
        ELSE 'NA' END AS clocking,
    AlarmEventTransactionTable.DateTimeOfTxn
 FROM
    multiMAXTxn.dbo.AlarmEventTransactionTable

Just remove highlighted string

SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)

Java: How can I compile an entire directory structure of code ?

Windows solution: Assuming all files contained in sub-directory 'src', and you want to compile them to 'bin'.

for /r src %i in (*.java) do javac %i -sourcepath src -d bin

If src contains a .java file immediately below it then this is faster

javac src\\*.java -d bin

Angular Directive refresh on parameter change

What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:

angular.module('myApp').directive('conversation', function() {
  return {
    restrict: 'E',
    replace: true,
    compile: function(tElement, attr) {
      attr.$observe('typeId', function(data) {
            console.log("Updated data ", data);
      }, true);

    }
  };
});

Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.

If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:

<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>

And in the directive:

angular.module('myApp').directive('conversation', function() {
  return {
    scope: {
      typeId: '=',
    },
    link: function(scope, elm, attr) {

      scope.$watch('typeId', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            // You actions here
            console.log("I got the new value! ", newValue);
          }
      }, true);

    }
  };
});

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

Cannot load properties file from resources directory

I use something like this to load properties file.

        final ResourceBundle bundle = ResourceBundle
                .getBundle("properties/errormessages");

        for (final Enumeration<String> keys = bundle.getKeys(); keys
                .hasMoreElements();) {
            final String key = keys.nextElement();
            final String value = bundle.getString(key);
            prop.put(key, value);
        }

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Display a tooltip over a button using Windows Forms

Sure, just handle the mousehover event and tell it to display a tool tip. t is a tooltip defined either in the globals or in the constructor using:

ToolTip t = new ToolTip();

then the event handler:

private void control_MouseHover(object sender, EventArgs e)
{
  t.Show("Text", (Control)sender);
}

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Running a shell script through Cygwin on Windows

One more thing - if You edited the shell script in some Windows text editor, which produces the \r\n line-endings, cygwin's bash wouldn't accept those \r. Just run dos2unix testit.sh before executing the script:

C:\cygwin\bin\dos2unix testit.sh
C:\cygwin\bin\bash testit.sh

Undefined function mysql_connect()

My guess is your PHP installation wasn't compiled with MySQL support.

Check your configure command (php -i | grep mysql). You should see something like '--with-mysql=shared,/usr'.

You can check for complete instructions at http://php.net/manual/en/mysql.installation.php. Although, I would rather go with the solution proposed by @wanovak.

Still, I think you need MySQL support in order to use PDO.

Why does Date.parse give incorrect results?

This light weight date parsing library should solve all similar problems. I like the library because it is quite easy to extend. It's also possible to i18n it (not very straight forward, but not that hard).

Parsing example:

var caseOne = Date.parseDate("Jul 8, 2005", "M d, Y");
var caseTwo = Date.parseDate("2005-07-08", "Y-m-d");

And formatting back to string (you will notice both cases give exactly the same result):

console.log( caseOne.dateFormat("M d, Y") );
console.log( caseTwo.dateFormat("M d, Y") );
console.log( caseOne.dateFormat("Y-m-d") );
console.log( caseTwo.dateFormat("Y-m-d") );

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

how to implement a pop up dialog box in iOS

Here is C# version in Xamarin.iOS

var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

How to annotate MYSQL autoincrement field with JPA annotations

can you check whether you connected to the correct database. as i was faced same issue, but finally i found that i connected to different database.

identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

More Info : http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/mapping.html#mapping-declaration-id

Count the frequency that a value occurs in a dataframe column

If you want to apply to all columns you can use:

df.apply(pd.value_counts)

This will apply a column based aggregation function (in this case value_counts) to each of the columns.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Reference the handle of the associated control in its creator, like so:

Note: Be wary of this solution.If a control has a handle it is much slower to do things like set the size and location of it. This makes InitializeComponent much slower. A better solution is to not background anything before the control has a handle.

Why is the time complexity of both DFS and BFS O( V + E )

Very simplified without much formality: every edge is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices.

The FastCGI process exited unexpectedly

For user using PHP 5.6.x follow this link and install the x86 version.

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How to delete a module in Android Studio

After doing what's referred in [this answer]: https://stackoverflow.com/a/24592192/82788

Select the module(since it's still visible on the Project view),pressing Delete button on the keyboard can delete this module on disk.(Before doing what's referred in that answer, the Delete button has no effect.)

getting file size in javascript

If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.

You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file] element, you can get details about the file from the files collection:

alert(myInp.files[0].size);

How to change font in ipython notebook

You can hover to .ipython folder (i.e. you can type $ ipython locate in your terminal/bash OR CMD.exe Prompt from your Anaconda Navigator to see where is your ipython is located)

Then, in .ipython, you will see profile_default directory which is the default one. This directory will have static/custom/custom.css file located.

You can now apply change to this custom.css file. There are a lot of styles in the custom.css file that you can use or search for. For example, you can see this link (which is my own customize custom.css file)

Basically, this custom.css file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the custom.css file. For example, you can add these chunk to change font in .CodeMirror pre to type Monaco

.CodeMirror pre {font-family: Monaco; font-size: 9pt;}

Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to ~/.jupyter/custom/custom.css instead.

Replace last occurrence of character in string

Keep it simple

var someString = "a_b_c";
var newCharacter = "+";

var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);

How do I get the name of the active user via the command line in OS X?

Define 'active user'.

If the question is 'who is the logged in user', then 'who am i' or 'whoami' is fine (though they give different answers - 'whoami' reports just a user name; 'who am i' reports on terminal and login time too).

If the question is 'which user ID is the effective ID for the shell', then it is often better to use 'id'. This reports on the real and effective user ID and group ID, and on the supplementary group IDs too. This might matter if the shell is running SUID or SGID.

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

How to close IPython Notebook properly?

In the browser session you can also go to Kernel and then click Restart and Clear Output.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Convert JSON string to dict using Python

When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution

import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.

  • One solution would be to add a position: fixed to the CSS definition, but I see this won't work for you
  • Another solution would be to position the ActionBox absolutely (to the document body) and adjust the top.
  • Updated the code to fit with the solution found for others to benefit.

UPDATED:

CSS

#ActionBox {
 position: relative;
 float: right;
}

Script

var alert_top = 0;
var alert_margin_top = 0;

$(function() {
  alert_top = $("#ActionBox").offset().top;
  alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);

  $(window).scroll(function () {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > alert_top) {
      $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
      console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
    } else {
      $("#ActionBox").css("margin-top", alert_margin_top+"px");
    };
  });
});

Also it is important to add a base (10 in this case) to your parseInt(), e.g.

parseInt($("#ActionBox").css("top"),10);

java collections - keyset() vs entrySet() in map

Traversal over the large map entrySet() is much better than the keySet(). Check this tutorial how they optimise the traversal over the large object with the help of entrySet() and how it helps for performance tuning.

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

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

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

Examples

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

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

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

How do I get a list of folders and sub folders without the files?

I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.

dir /b /AD-H

Basic Python client socket example

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

Update UI from Thread in Android

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

JavaScript TypeError: Cannot read property 'style' of null

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

SQL SERVER DATETIME FORMAT

Compatibility Supports Says that Under compatibility level 110, the default style for CAST and CONVERT operations on time and datetime2 data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.

That means by default datetime2 is CAST as varchar to 121 format. For ex; col1 and col2 formats (below) are same (other than the 0s at the end)

SELECT CONVERT(varchar, GETDATE(), 121) col1,
       CAST(convert(datetime2,GETDATE()) as varchar) col2,
       CAST(GETDATE() as varchar) col3

SQL FIDDLE DEMO

--Results
COL1                    | COL2                          | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000   | Feb 8 2013 9:53AM

FYI, if you use CONVERT instead of CAST you can use a third parameter to specify certain formats as listed here on MSDN

Clear terminal in Python

This will be work in Both version Python2 OR Python3

print (u"{}[2J{}[;H".format(chr(27), chr(27)))

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

If table exists drop table then create it, if it does not exist just create it

Well... Huh. For years nobody mentioned one subtle thing.

Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.

The better way is to create brand new table and swap it with an old one (table contents are lost):

CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
  • You should check the result of CREATE ... and do not continue in case of error, because failure means that other thread didn't finish the same script: either because it crashed in the middle or just didn't finish yet -- it's a good idea to inspect things by yourself.
  • Then, you should check the result of first RENAME ... and do not continue in case of success: whole operation is successfully completed; even more, running next RENAME ... can (and will) be unsafe if another thread has already started same sequence (it's better to cover this case than not to cover, see locking note below).
  • Second RENAME ... atomically replaces table definition, refer to MySQL manual for details.
  • At last, DROP ... just cleans up the old table, obviously.

Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.

If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.

Side note 1: You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.

CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;

Side note 2: MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

Tensorflow: Using Adam optimizer

FailedPreconditionError: Attempting to use uninitialized value is one of the most frequent errors related to tensorflow. From official documentation, FailedPreconditionError

This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.

In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading

Basically to initialize the variable you have 3 options:

I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables and check is_variable_initialized.

Can we pass parameters to a view in SQL?

A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like:

CREATE VIEW v_emp 
AS 
SELECT      * 
FROM        emp E
INNER JOIN  settings S
ON          S.Id = 1 AND E.emp_id = S.Param1

HTTP vs HTTPS performance

The HTTPS indeed affects page speed...

The quotes above reveal the foolishness of many people about site security and speed. HTTPS / SSL server handshaking creates an initial stall in making Internet connections. There’s a slow delay before anything starts to render on your visitor’s browser screen. This delay is measured in Time-to-First-Byte information.

HTTPS handshake overhead appears in Time-to-First-Byte information (TTFB). Common TTFB ranges from under 100 milliseconds (best-case) to over 1.5 seconds (worst case). But, of course, with HTTPS it’s 500 milliseconds worse.

Roundtrip, wireless 3G connections can be 500 milliseconds or more. The extra trips double delays to 1 second or more. This is a big, negative impact on mobile performance. Very bad news.

My advice, if you're not exchanging sensitive data then you don't need SSL at all, but if you do like an ecommerce website then you can just enable HTTPS on certain pages where sensitive data is exchanged like Login and checkout.

Source: Pagepipe

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

If using webdriverJs (node.js),

driver.findElement(webdriver.By.name('btnCalculate')).click().then(function() {
    driver.sleep(5000);
});

The code above makes browser wait for 5 seconds after clicking the button.

Change the Value of h1 Element within a Form with JavaScript

You can do it with regular JavaScript this way:

document.getElementById('h1_id').innerHTML = 'h1 content here';

Here is the doc for getElementById and the innerHTML property.

The innerHTML property description:

A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

PLS-00201 - identifier must be declared

you should give permission on your db

grant execute on (packageName or tableName) to user;

How do you properly use WideCharToMultiByte

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}