Programs & Examples On #Createparams

Winforms issue - Error creating window handle

The out of memory suggestion doesn't seem like a bad lead.

What is your program doing that it gets this error?

Is it creating a great many windows or controls? Does it create them programatically as opposed to at design time? If so, do you do this in a loop? Is that loop infinite? Are you consuming staggering boatloads of memory in some other way?

What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.

How do include paths work in Visual Studio?

To resume the working solutions in VisualStudio 2013 and 2015 too:

Add an include-path to the current project only

In Solution Explorer (a palette-window of the VisualStudio-mainwindow), open the shortcut menu for the project and choose Properties, and then in the left pane of the Property Pages dialog box, expand Configuration Properties and select VC++ Directories. Additional include- or lib-paths are specifyable there.

Its the what Stackunderflow and user1741137 say in the answers above. Its the what Microsoft explains in MSDN too.

Add an include-path to every new project automatically

Its the question, what Jay Elston is asking in a comment above and what is a very obvious and burning question in my eyes, what seems to be nonanswered here yet.

There exist regular ways to do it in VisualStudio (see CurlyBrace.com), what in my experience are not working properly. In the sense, that it works only once, and thereafter, it is no more expandable and nomore removable. The approach of Steve Wilkinson in another close related thread of StackOverflow, editing the Microsoft-Factory-XML-file in the ‘program files’ - directory is probably a risky hack, as it isnt expected by Microsoft to meet there something foreign. The effect is potentally unpredictable. Well, I like rather to judge it risky not much, but anyway the best way to make VisualStudio work incomprehensible at least for someone else.

The what is working fine compared to, is the editing the corresponding User-XML-file:

C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.Win32.user.props

or/and

C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.x64.user.props

For example:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets">
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IncludePath>C:\any-name\include;$(IncludePath)</IncludePath>
    <LibraryPath>C:\any-name\lib;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <ItemDefinitionGroup />
  <ItemGroup />
</Project>

Where the directory ‘C:\any-name\include’ will get prepended to the present include-path and the directory ‘C:\any-name\lib’ to the library-path. Here, we can edit it ago in an extending and removing sense and remove it all, removing thewhole content of the tag .

Its the what makes VisualStudio itself, doing it in the regular way what CurlyBrace describes. As said, it isnt editable in the CurlyBrace-way thereafter nomore, but in the XML-editing-way it is.

For more insight, see Brian Tyler@MSDN-Blog 2009, what is admittedly not very fresh, but always the what Microsoft is linking to.

What is ".NET Core"?

It is a sub-set of the .NET Framework, started with the Compact Framework edition. It progressed into Silverlight, Windows Store and Windows Phone. It focused on keeping the deployment small, suitable for quick downloads and devices with limited storage capabilities. And it is easier to bring up on non-Windows platforms, and surely this was the reason it was chosen as the open sourced edition. The "difficult" and "expensive" parts of the CLR and the base class libraries are omitted.

Otherwise, it is always easy to recognize when you target such a framework version, because lots of goodies will be missing. You'll be using a distinct set of reference assemblies that only expose what is supported by the runtime. It is stored on your machine in the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore directory.


Update: after the .NET Core 2.0 release I've seen some representative numbers that gives a decent insight. They have been hard at work back-porting framework APIs to .NET Core over the past two years. .NET Core 1.0 originally supported 13,000 APIs. .NET Core 2.0 added 20,000 APIs, bringing the total to 32,000 and allowing about 70% of existing NuGet packages to be ported. There are a set of APIs that are too heavily wedded to Windows to be easy to port to Linux and MacOS. Covered by the recently released Windows Compatibility Pack, it adds another 20,000 APIs.

How to parse JSON data with jQuery / JavaScript?

Use that code.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

Clone contents of a GitHub repository (without the folder itself)

You can specify the destination directory as second parameter of the git clone command, so you can do:

git clone <remote> .

This will clone the repository directly in the current local directory.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

The solution is very simple. git checkout <filename> tries to check out file from the index, and therefore fails on merge.

What you need to do is (i.e. checkout a commit):

To checkout your own version you can use one of:

git checkout HEAD -- <filename>

or

git checkout --ours -- <filename>

(Warning!: If you are rebasing --ours and --theirs are swapped.)

or

git show :2:<filename> > <filename> # (stage 2 is ours)

To checkout the other version you can use one of:

git checkout test-branch -- <filename>

or

git checkout --theirs -- <filename>

or

git show :3:<filename> > <filename> # (stage 3 is theirs)

You would also need to run 'add' to mark it as resolved:

git add <filename>

When to use StringBuilder in Java

If you use String concatenation in a loop, something like this,

String s = "";
for (int i = 0; i < 100; i++) {
    s += ", " + i;
}

then you should use a StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.

If you have a single statement,

String s = "1, " + "2, " + "3, " + "4, " ...;

then you can use Strings, because the compiler will use StringBuilder automatically.

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

Codeigniter LIKE with wildcard(%)

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

Jump to function definition in vim

As Paul Tomblin mentioned you have to use ctags. You could also consider using plugins to select appropriate one or to preview the definition of the function under cursor. Without plugins you will have a headache trying to select one of the hundreds overloaded 'doAction' methods as built in ctags support doesn't take in account the context - just a name.

Also you can use cscope and its 'find global symbol' function. But your vim have to be compiled with +cscope support which isn't default one option of build.

If you know that the function is defined in the current file, you can use 'gD' keystrokes in a normal mode to jump to definition of the symbol under cursor.

Here is the most downloaded plugin for navigation
http://www.vim.org/scripts/script.php?script_id=273

Here is one I've written to select context while jump to tag
http://www.vim.org/scripts/script.php?script_id=2507

How do you detect the clearing of a "search" HTML5 input?

The search or onclick works... but the issue I found was with the older browsers - the search fails. Lots of plugins (jquery ui autocomplete or fancytree filter) have blur and focus handlers. Adding this to an autocomplete input box worked for me(used this.value == "" because it was faster to evaluate). The blur then focus kept the cursor in the box when you hit the little 'x'.

The PropertyChange and input worked for both IE 10 and IE 8 as well as other browsers:

$("#INPUTID").on("propertychange input", function(e) { 
    if (this.value == "") $(this).blur().focus(); 
});

For FancyTree filter extension, you can use a reset button and force it's click event as follows:

var TheFancyTree = $("#FancyTreeID").fancytree("getTree");

$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
    var n,
    leavesOnly = false,
    match = $(this).val();
    // check for the escape key or empty filter
    if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
        $("button#btnResetSearch").click();
        return;
    }

    n = SiteNavTree.filterNodes(function (node) {
        return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
        }, leavesOnly);

    $("button#btnResetSearch").attr("disabled", false);
    $("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();

// handle the reset and check for empty filter field... 
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
    if ($("input[name=FT_FilterINPUT]").val() != "")
        $("input[name=FT_FilterINPUT]").val("");
    $("span#SiteNavMatches").text("");
    SiteNavTree.clearFilter();
}).attr("disabled", true);

Should be able to adapt this for most uses.

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

Make xargs handle filenames that contain spaces

Try

find . -name \*.mp3 -print0 | xargs -0 mplayer

instead of

ls | grep mp3 

Persist javascript variables across pages?

For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.

http://www.w3.org/TR/2009/WD-webstorage-20091222/

https://www.w3.org/TR/webstorage/. (second edition)

Here are some sample code for setting and getting the values using sessionStorage and localStorage :

 // HTML5 session Storage
 sessionStorage.setItem("variableName","test");
 sessionStorage.getItem("variableName");


//HTML5 local storage 
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");

Show week number with Javascript?

Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.

Here is a revised and working version:

Date.prototype.getWeek = function() { 

  // Create a copy of this date object  
  var target  = new Date(this.valueOf());  

  // ISO week date weeks start on monday, so correct the day number  
  var dayNr   = (this.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week with january 4th in it  
  var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
    // Calculate week number: Week 1 (january 4th) plus the    
    // number of weeks between target date and january 4th    
    return 1 + Math.ceil(dayDiff / 7);    
  }
  else {  // jan 4th is on the next week (so next week is week 1)
    return Math.ceil(dayDiff / 7); 
  }
}; 

Show values from a MySQL database table inside a HTML table on a webpage

First, connect to the database:

$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);

You can use this to display a single record:

For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.

<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);

echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>

Or, if you want to list all values that match the criteria in a table:

<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>

How do I create a GUI for a windows application using C++?

Avoid QT (for noobs) or any useless libraries (absurd for a such basic thing)

Just use the VS Win32 api Wizard, ad the button and text box...and that's all !

In 25 seconds !

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

What is the difference between Serializable and Externalizable in Java?

https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serialTOC.html

Default serialization is somewhat verbose, and assumes the widest possible usage scenario of the serialized object, and accordingly the default format (Serializable) annotates the resultant stream with information about the class of the serialized object.

Externalization give the producer of the object stream complete control over the precise class meta-data (if any) beyond the minimal required identification of the class (e.g. its name). This is clearly desirable in certain situations, such as closed environments, where producer of the object stream and its consumer (which reifies the object from the stream) are matched, and additional metadata about the class serves no purpose and degrades performance.

Additionally (as Uri point out) externalization also provides for complete control over the encoding of the data in the stream corresponding to Java types. For (a contrived) example, you may wish to record boolean true as 'Y' and false as 'N'. Externalization allows you to do that.

What is the difference between Set and List?

Few note worthy differences between List and Set in Java are given as following :

1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older value. Any implementation of Set in Java will only contains unique elements.

2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.

3) Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular implementation of Set interface includes HashSet, TreeSet and LinkedHashSet.

Its pretty clear that if you need to maintain insertion order or object and you collection can contain duplicates than List is a way to go. On the other hand if your requirement is to maintain unique collection without any duplicates than Set is the way to go.

When to use Interface and Model in TypeScript / Angular

I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:

1- Interfaces:

interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.

interface User {
 id: number;
 username: string;
}
// inheritance
interface UserDetails extends User {
 birthdate: Date;
 biography?: string;  // use the '?' annotation to mark this property as optionnal
}

Mapping server response to an interface is straight forward if you are using HttpClient from HttpClientModule if you are using Angular 4.3.x and above.

getUsers() :Observable<User[]> {
 return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())' 
}

when to use interfaces:

  • You only need the definition for the server data without introducing additional overhead for the final output.
  • You only need to transmit data without any behaviors or logic (constructor initialization, methods)
  • You do not instantiate/create objects from your interface very often
    • Using simple object-literal notationlet instance: FooInterface = { ... };, you risk having semi-instances all over the place.
    • That doesn't enforce the constraints given by a class ( constructor or initialization logic, validation, encapsulation of private fields...Etc)
  • You need to define contracts/configurations for your systems (global configurations)

2- Classes:

A class defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.

class User {
 id: number;
 username: string;
 constructor(id :number, username: string)  {
  this.id = id;
  this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
 }
}
// inheritance
class UserDetails extends User {
 birthdate: Date;
 biography?: string;  
 constructor(id :number, username: string, birthdate:Date, biography? :string )  {
   super(id,username);
  this.birthdate = ...;
 }
}

when to use classes:

  • You instantiate your class and change the instances state over time.
  • Instances of your class will need methods to query or mutate its state
  • When you want to associate behaviors with data more closely;
  • You enforce constraints on the creation of your instaces.
  • If you only write a bunch of properties assignments in your class, you might consider using a type instead.

2- Types:

With the latest versions of typescript, interfaces and types becoming more similar. types do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects. Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.

type User = {
 id: number;
 username: string;
}
// inheritance
type UserDetails = User & {
  birthDate :Date;
  biography?:string;
}

when to use types:

  • pass it around as concise function parameters
  • describe a class constructor parameters
  • document small or medium objects coming in or out from an API.
  • they don't carry state nor behavior

Find running median from a stream of integers

An intuitive way to think about this is that if you had a full balanced binary search tree, then the root would be the median element, since there there would be the same number of smaller and greater elements. Now, if the tree isn't full this won't be quite the case since there will be elements missing from the last level.

So what we can do instead is have the median, and two balanced binary trees, one for elements less than the median, and one for elements greater than the median. The two trees must be kept at the same size.

When we get a new integer from the data stream, we compare it to the median. If it's greater than the median, we add it to the right tree. If the two tree sizes differ more than 1, we remove the min element of the right tree, make it the new median, and put the old median in the left tree. Similarly for smaller.

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

"git pull" or "git merge" between master and development branches

This workflow works best for me:

git checkout -b develop

...make some changes...

...notice master has been updated...

...commit changes to develop...

git checkout master
git pull

...bring those changes back into develop...

git checkout develop
git rebase master

...make some more changes...

...commit them to develop...

...merge them into master...

git checkout master
git pull
git merge develop

Count how many files in directory PHP

$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
    foreach ($it as $fileinfo) {
        echo $fileinfo->getFilename() . "<br/>\n";
    } 

This should work enter the directory in dirname. and let the magic happen.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Angular IE Caching issue for $http

You can either append a unique querystring (I believe this is what jQuery does with the cache: false option) to the request.

$http({
    url: '...',
    params: { 'foobar': new Date().getTime() }
})

A perhaps better solution is if you have access to the server, then you can make sure that necessary headers are set to prevent caching. If you're using ASP.NET MVC this answer might help.

Android Studio : unmappable character for encoding UTF-8

I have the problem with encoding in javadoc generated by intellij idea. The solution is to add

-encoding UTF-8 -docencoding utf-8 -charset utf-8

into command line arguments!

UPDATE: more information about compilation Javadoc in Intellij IDEA see in my post

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

Determine path of the executing script

I would use a variant of @steamer25 's approach. The point is that I prefer to obtain the last sourced script even when my session was started through Rscript. The following snippet, when included on a file, will provided a variable thisScript containing the normalized path of the script. I confess the (ab)use of source'ing, so sometimes I invoke Rscript and the script provided in the --file argument sources another script that sources another one... Someday I will invest in making my messy code turns into a package.

thisScript <- (function() {
  lastScriptSourced <- tail(unlist(lapply(sys.frames(), function(env) env$ofile)), 1)

  if (is.null(lastScriptSourced)) {
    # No script sourced, checking invocation through Rscript
    cmdArgs <- commandArgs(trailingOnly = FALSE)
    needle <- "--file="
    match <- grep(needle, cmdArgs)
    if (length(match) > 0) {
      return(normalizePath(sub(needle, "", cmdArgs[match]), winslash=.Platform$file.sep, mustWork=TRUE))
    }
  } else {
    # 'source'd via R console
    return(normalizePath(lastScriptSourced, winslash=.Platform$file.sep, mustWork=TRUE))
  }
})()

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can also use the toBase64Image() method setting animation: false

var options = {
    bezierCurve : false,
    animation: false
};

Updated Fiddle

download csv file from web api in angular js

I think the best way to download any file generated by REST call is to use window.location example :

_x000D_
_x000D_
    $http({_x000D_
        url: url,_x000D_
        method: 'GET'_x000D_
    })_x000D_
    .then(function scb(response) {_x000D_
        var dataResponse = response.data;_x000D_
        //if response.data for example is : localhost/export/data.csv_x000D_
        _x000D_
        //the following will download the file without changing the current page location_x000D_
        window.location = 'http://'+ response.data_x000D_
    }, function(response) {_x000D_
      showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
    });
_x000D_
_x000D_
_x000D_

What is difference between INNER join and OUTER join

This is the best and simplest way to understand joins:

enter image description here

Credits go to the writer of this article HERE

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

get client time zone from browser

For now, the best bet is probably jstz as suggested in mbayloon's answer.

For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:

> Intl.DateTimeFormat().resolvedOptions().timeZone
"America/Los_Angeles"

(This doesn't actually follow the standard, which is one more reason to stick with the library)

Set The Window Position of an application via command line

Bill K.'s answer was the most elegant if you just want to start a window at startup or start from a shortcut on the desktop.

Just open the window where you want it, right click and choose properties. select Layout uncheck "let system position window" and click OK.

Window will now open just where you want it. You can set font and window colors at the same time on other tabs. sweet.

Flatten an irregular list of lists

Generator using recursion and duck typing (updated for Python 3):

def flatten(L):
    for item in L:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

list(flatten([[[1, 2, 3], [4, 5]], 6]))
>>>[1, 2, 3, 4, 5, 6]

Anaconda / Python: Change Anaconda Prompt User Path

Just Type the Drive Location you want to work with: This worked for me! For example you want to change to D drive in windows:

D:\

If you want to change to particular folder in the drive:

cd D:\Newfolder

How to terminate a python subprocess launched with shell=True

As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

Maven compile: package does not exist

the issue happened with me, I resolved by removing the scope tag only and built successfully.

Removing highcharts.com credits link

Both of the following code will work fine for removing highchart.com from the chart:-

credits: false

or

credits:{
 enabled:false,
}

How to comment multiple lines in Visual Studio Code?

How to comment out multiline / single line in VS Code:


MacOS:

Shift + Option + A:

/* multiline    
   comment */

CMD + /:

// single line comment    

Windows:

Shift + Alt + A:

 /* multiline
    comment */

CTRL + /:

// single line comment

How to remap / change these shortcuts?

Windows: File > Preferences > Keyboard Shortcuts.

MacOS: Code > Preferences > Keyboard Shortcuts.

You can search through the list both by keybindings (key names) and command names.


Read: How to set shortcuts from another text editor (Sublime, Atom etc)?

Official docs: Key Bindings for Visual Studio Code

Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.

JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.

setTimeout(myFunction, 3000);

// if you have defined a function named myFunction 
// it will run after 3 seconds (3000 milliseconds)

Remember, this is completely different from how sleep method, if it existed, would behave.

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.

function test2()
{
    // defer the execution of anonymous function for 
    // 3 seconds and go to next line of code.
    setTimeout(function(){ 

        alert('hello');
    }, 3000);  

    alert('hi');
}

If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

Resetting a setTimeout

You will have to remember the timeout "Timer", cancel it, then restart it:

g_timer = null;

$(document).ready(function() {
    startTimer();
});

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

Accessing a Dictionary.Keys Key through a numeric index

One alternative would be a KeyedCollection if the key is embedded in the value.

Just create a basic implementation in a sealed class to use.

So to replace Dictionary<string, int> (which isn't a very good example as there isn't a clear key for a int).

private sealed class IntDictionary : KeyedCollection<string, int>
{
    protected override string GetKeyForItem(int item)
    {
        // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
        return item.ToString();
    }
}

KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();

intCollection.Add(7);

int valueByIndex = intCollection[0];

Displaying a vector of strings in C++

Your vector<string> userString has size 0, so the loop is never entered. You could start with a vector of a given size:

vector<string> userString(10);      
string word;        
string sentence;           
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
    cin >> word;
    userString[i] = word;
    sentence += userString[i] + " ";
}

although it is not clear why you need the vector at all:

string word;        
string sentence;           
for (int i = 0; i < 10; ++i)
{
    cin >> word;
    sentence += word + " ";
}

If you don't want to have a fixed limit on the number of input words, you can use std::getline in a while loop, checking against a certain input, e.g. "q":

while (std::getline(std::cin, word) && word != "q")
{
    sentence += word + " ";
}

This will add words to sentence until you type "q".

How to remove leading and trailing spaces from a string

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery: is typically used when there is nothing returned from the Sql statements like insert ,update, delete operations.

cmd.ExcecuteNonQuery();

ExecuteScalar:

It will be used when Sql query returns single value.

Int b = cmd.ExcecuteScalar();

ExecuteReader

It will be used when Sql query or Stored Procedure returns multiple rows/columns

SqlDataReader dr = cmd.ExecuteReader();

for more information you can click here http://www.dotnetqueries.com/Article/148/-difference-between-executescalar-executereader-executenonquery

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

Java replace all square brackets in a string

You may also do it like this:

String data = "[yourdata]";
String regex = "\\[|\\]";
data  = data .replaceAll(regex, "");
System.out.println(data);

Loading scripts after page load?

http://jsfiddle.net/c725wcn9/2/embedded

You will need to inspect the DOM to check this works. Jquery is needed.

$(document).ready(function(){
   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "http://schema.org",  "@type": "Recipe", "name": "My recipe name" });

   document.querySelector('head').appendChild(el);
});

Reading PDF content with itextsharp dll in VB.NET or C#

Here is a VB.NET solution based on ShravankumarKumar's solution.

This will ONLY give you the text. The images are a different story.

Public Shared Function GetTextFromPDF(PdfFileName As String) As String
    Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)

    Dim sOut = ""

    For i = 1 To oReader.NumberOfPages
        Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy

        sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
    Next

    Return sOut
End Function

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Xampp-mysql - "Table doesn't exist in engine" #1932

  1. stop mysql
  2. copy xampp\mysql\data\ib* from old server to new server
  3. start mysql

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Changing width property of a :before css selector using JQuery

Pseudo elements are part of the shadow DOM and can not be modified (but can have their values queried).

However, sometimes you can get around that by using classes, for example.

jQuery

$('#element').addClass('some-class');

CSS

.some-class:before {
    /* change your properties here */
}

This may not be suitable for your query, but it does demonstrate you can achieve this pattern sometimes.

To get a pseudo element's value, try some code like...

var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
  .getPropertyValue('content')

How to map an array of objects in React

I think you want to print the name of the person or both the name and email :

const renObjData = this.props.data.map(function(data, idx) {
    return <p key={idx}>{data.name}</p>;
});

or :

const renObjData = this.props.data.map(function(data, idx) {
   return ([
       <p key={idx}>{data.name}</p>,
       <p key={idx}>{data.email}</p>,
   ]);
});

Using G++ to compile multiple .cpp and .h files

Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make), it should suffice to write that:

# "all" is the name of the default target, running "make" without params would use it
all: executable1

# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)

# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

Representing Directory & File Structure in Markdown Syntax

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

How can I check if a MySQL table exists with PHP?

Or you could use

show tables where Tables_in_{insert_db_name}='tablename';

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

Add padding on view programmatically

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

Generating PDF files with JavaScript

I maintain PDFKit, which also powers pdfmake (already mentioned here). It works in both Node and the browser, and supports a bunch of stuff that other libraries do not:

  • Embedding subsetted fonts, with support for unicode.
  • Lots of advanced text layout stuff (columns, page breaking, full unicode line breaking, basic rich text, etc.).
  • Working on even more font stuff for advanced typography (OpenType/AAT ligatures, contextual substitution, etc.). Coming soon: see the fontkit branch if you're interested.
  • More graphics stuff: gradients, etc.
  • Built with modern tools like browserify and streams. Usable both in the browser and node.

Check out http://pdfkit.org/ for a full tutorial to see for yourself what PDFKit can do. And for an example of what kinds of documents can be produced, check out the docs as a PDF generated from some Markdown files using PDFKit itself: http://pdfkit.org/docs/guide.pdf.

You can also try it out interactively in the browser here: http://pdfkit.org/demo/browser.html.

Send POST request using NSURLSession

You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server.

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
                     @"IOS TYPE", @"typemap",
                     nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];

Hope this helps (I'm trying to sort a CSRF authenticity issue with the above - but it does send the params in the NSDictionary).

How to fix a collation conflict in a SQL Server query?

I resolved a similar issue by wrapping the query in another query...

Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.

I encountered the collation error after attempting to create a single field of output with...

select
rtrim(field1)+','+rtrim(field2)+','+...

The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.

Wound up fixing it with something like...

select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z

Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.

Apache Proxy: No protocol handler was valid

This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:

... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.

The configuration related to this was:

  ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
  ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/

"No protocol handler was valid for the URL /~socket.io/" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/"

I had proxy_http loaded, but also needed proxy_wstunnel. Once that was enabled all was good.

How can I detect when the mouse leaves the window?

This worked for me. A combination of some of the answers here. And I included the code showing a model only once. And the model goes away when clicked anywhere else.

<script>
    var leave = 0
    //show modal when mouse off of page
    $("html").mouseleave(function() {
       //check for first time
       if (leave < 1) {
          modal.style.display = "block";
          leave = leave + 1;
       }
    });

    // Get the modal with id="id01"
       var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
       window.onclick = function(event) {
          if (event.target == modal) {
             modal.style.display = "none";
          }
       }
</script>

Deserialize JSON string to c# object

solution :

 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:

 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

Laravel - Return json along with http status code

It's better to do it with helper functions rather than Facades. This solution will work well from Laravel 5.7 onwards

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

Android Studio - debug keystore

On Mac, you will find it here: /Users/$username/.android

Change span text?

document.getElementById("serverTime").innerHTML = ...;

7-zip commandline

In this 7-zip forum thread, in which many people express their desire for this feature, 7-zip's developer Igor points to the FAQ question titled "How can I store full path of file in archive?" to achieve a similar outcome.

In short:

  • separate files by volume (one list for files on C:\, one for D:\, etc)
  • then for each volume's list of files,
    1. chdir to the root directory of the appropriate volume (eg, cd /d C:\)
    2. create a file listing with paths relative to the volume's root directory (eg, C:\Foo\Bar becomes Foo\Bar)
    3. perform 7z a archive.7z @filelist as before with this new file list
    4. when extracting with full paths, make sure to chdir to the appropriate volume's root directory first

Using find command in bash script

If you want to loop over what you "find", you should use this:

find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
done

Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Android 9 and Android 11 emulators have support for arm binaries.

https://developer.android.com/studio/releases/emulator#support_for_arm_binaries_on_android_9_and_11_system_images

I had the same issue while using x86 emulator with API level 29, trying to install an apk targeting arm ABI.

I tried x86 emulator with API level 30 and it worked fine.

$(window).width() not the same as media query

if(window.matchMedia('(max-width: 768px)').matches)
    {
        $(".article-item").text(function(i, text) {

            if (text.length >= 150) {
                text = text.substring(0, 250);
                var lastIndex = text.lastIndexOf(" ");     
                text = text.substring(0, lastIndex) + '...'; 
            }

            $(this).text(text);

        });

    }

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

Difference between Static and final?

Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

Declaring

static final String color = "Black"; 

will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.

public class Speaker {

static String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //will provide output as "Black"
            Speaker.color = "white";
    System.out.println(Speaker.color);  //will provide output as "White"
}}

Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.

public class Speaker {

static final String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //should provide output as "Black"
            Speaker.color = "white"; //Error because the value of color is fixed.  
    System.out.println(Speaker.color); //Code won't execute.
}}

You may copy/paste this code directly into your emulator and try.

How can I make a horizontal ListView in Android?

You know, it might be possible to use an existing ListView with some judicious overriding of dispatchDraw() (to rotate the Canvas by 90 degrees), onTouch() (to swap the X and Y of the MotionEvent coords) and maybe onMeasure() or whatever to fool it into thinking it's y by x rather than x by y...

I have no idea if this would actually work but it'd be fun to find out. :)

Send inline image in email

Some minimal c# code to embed an image, can be:

MailMessage mailWithImg = GetMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!

private MailMessage GetMailWithImg() {
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png"));
    mail.From = new MailAddress("yourAddress@yourDomain");
    mail.To.Add("recipient@hisDomain");
    mail.Subject = "yourSubject";
    return mail;
}

private AlternateView GetEmbeddedImage(String filePath) {
    LinkedResource res = new LinkedResource(filePath);
    res.ContentId = Guid.NewGuid().ToString();
    string htmlBody = @"<img src='cid:" + res.ContentId + @"'/>";
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}

Select rows which are not present in other table

this can also be tried...

SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM   login_log l 
LEFT   JOIN (SELECT ip_location.ip, ip_location.hostname
             FROM ip_location
             WHERE ip_location.ip is null)tbl2

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Python strptime() and timezones?

Ran into this exact problem.

What I ended up doing:

# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'

# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)

# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))

# set timezone
import pendulum
tz = pendulum.timezone('utc')

dt_tz = datetime(*dt_vals,tzinfo=tz)

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

Access XAMPP Localhost from Internet

I know this very old but for future's sake:

I also used a dynamic dns provider. Wanted to test the website (IIS) BEHIND my (home) router. So i thought i use something like this:

my.dynamic.dnss.ip:8080 (because my router's port 80 was used to admin it).

So this seemed to be the only solution.
But: Paypal seemed to not like port 8080: only port 80 and 443 are allowed (don't know why!!)

Display calendar to pick a date in java

I wrote a DateTextField component.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());
    }

    public DateTextField(String dateFormatPattern, Date date) {
        this(date);
        DEFAULT_DATE_FORMAT = dateFormatPattern;
    }

    public DateTextField(Date date) {
        setDate(date);
        setEditable(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        addListeners();
    }

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                }
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);
            }
        });
    }

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
                .getWindowAncestor(DateTextField.this);
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        }
        dateDialog.setLocation(getAppropriateLocation(owner, position));
        dateDialog.setVisible(true);
    }

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.setUndecorated(true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;
    }

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;
        }

        if (offsetY > 0) {
            result.y -= offsetY;
        }

        return result;
    }

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        }
        return dateFormat;
    }

    public void setText(Date date) {
        setDate(date);
    }

    public void setDate(Date date) {
        super.setText(getDefaultDateFormat().format(date));
    }

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();
        }
    }

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor = Color.orange;
        Color weekFontColor = Color.blue;
        Color dateFontColor = Color.black;
        Color weekendFontColor = Color.red;

        Color controlLineColor = Color.pink;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));
            setBackground(backGroundColor);

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);

            reflushWeekAndDay();
        }

        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.setBackground(controlLineColor);

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setName("Year");
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
            yearSpin.addChangeListener(this);
            panel.add(yearSpin);

            JLabel yearLabel = new JLabel("Year");
            yearLabel.setForeground(controlTextColor);
            panel.add(yearLabel);

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));
            monthSpin.setName("Month");
            monthSpin.addChangeListener(this);
            panel.add(monthSpin);

            JLabel monthLabel = new JLabel("Month");
            monthLabel.setForeground(controlTextColor);
            panel.add(monthLabel);

            return panel;
        }

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));
            panel.setBackground(Color.white);

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                cell.setHorizontalAlignment(JLabel.RIGHT);
                if (i == 0 || i == 6) {
                    cell.setForeground(weekendFontColor);
                } else {
                    cell.setForeground(weekFontColor);
                }
                panel.add(cell);
            }

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.setBorder(null);
                    numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
                    numBtn.setActionCommand(String
                            .valueOf(actionCommandId));
                    numBtn.setBackground(palletTableColor);
                    numBtn.setForeground(dateFontColor);
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                                return;
                            }
                            dayColorUpdate(true);
                            source.setForeground(todayBackColor);
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);
                            setDate(cal.getTime());

                            dateDialog.setVisible(false);
                        }
                    });

                    if (j == 0 || j == 6)
                        numBtn.setForeground(weekendFontColor);
                    else
                        numBtn.setForeground(dateFontColor);
                    daysButton[i][j] = numBtn;
                    panel.add(numBtn);
                    actionCommandId++;
                }

            return panel;
        }

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDate());
            return calendar;
        }

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();
        }

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();
        }

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
                daysButton[i][j].setForeground(dateFontColor);
            } else {
                daysButton[i][j].setForeground(todayBackColor);
            }
        }

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);
                    }
                    daysButton[i][j].setText(s);
                    dayNo++;
                }
            }
            dayColorUpdate(false);
        }

        public void stateChanged(ChangeEvent e) {
            dayColorUpdate(true);

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            setDate(cal.getTime());
            reflushWeekAndDay();
        }
    }
}

Button background as transparent

Step 1: Create a new resource file in drawable and copy paste

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

    <stroke android:color="#fff" android:width="2dp"/>
    <corners android:radius="25dp"/>
    <padding android:right="15dp" android:top="15dp" android:bottom="15dp" android:left="15dp"/>
</shape>

save it as ButtonUI(let's say)

Step 2: Apply the UI to the button xml

<Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="join the crew"
  android:background="@drawable/ButtonUI"
  android:textColor="#fff"/>

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

Undo git pull, how to bring repos to old state

Try run

git reset --keep HEAD@{1}

SQL Bulk Insert with FIRSTROW parameter skips the following line

To let SQL handle quote escape and everything else do this

BULK INSERT Test_CSV
FROM  'C:\MyCSV.csv' 
WITH (
 FORMAT='CSV'
 --FIRSTROW = 2,  --uncomment this if your CSV contains header, so start parsing at line 2
);

In regards to other answers, here is valuable info as well:

I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL

In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'

enter image description here

enter image description here

Style bottom Line in Android

I think you do not need to use shape if I understood you.

If you are looking as shown in following image then use following layout.

enter image description here

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="#1bd4f6"
    android:paddingBottom="4dp" >

    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="#ababb2"
        android:padding="5dp"
        android:text="Hello Android" />
 </RelativeLayout>

 </RelativeLayout>

EDIT

play with these properties you will get result

    android:top="dimension"
    android:right="dimension"
    android:bottom="dimension"
    android:left="dimension"

try like this

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

<item>
    <shape android:shape="rectangle" >
        <solid android:color="#1bd4f6" />
    </shape>
</item>

<item android:top="20px"
    android:left="0px">
    <shape android:shape="line"  >
        <padding android:bottom="1dp" />

        <stroke
            android:dashGap="10px"
            android:dashWidth="10px"
            android:width="1dp"
            android:color="#ababb2" />
    </shape>
</item>

</layer-list>

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

Use find command but exclude files in two directories

You can try below:

find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'

Check if list is empty in C#

If you're using a gridview then use the empty data template: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        runat="server">

        <emptydatarowstyle backcolor="LightBlue"
          forecolor="Red"/>

        <emptydatatemplate>

          <asp:image id="NoDataImage"
            imageurl="~/images/Image.jpg"
            alternatetext="No Image" 
            runat="server"/>

            No Data Found.  

        </emptydatatemplate> 

      </asp:gridview>

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

Similarity String Comparison in Java

There are indeed a lot of string similarity measures out there:

  • Levenshtein edit distance;
  • Damerau-Levenshtein distance;
  • Jaro-Winkler similarity;
  • Longest Common Subsequence edit distance;
  • Q-Gram (Ukkonen);
  • n-Gram distance (Kondrak);
  • Jaccard index;
  • Sorensen-Dice coefficient;
  • Cosine similarity;
  • ...

You can find explanation and java implementation of these here: https://github.com/tdebatty/java-string-similarity

How to convert string to boolean php

If your "boolean" variable comes from a global array such as $_POST and $_GET, you can use filter_input() filter function.

Example for POST:

$isSleeping  = filter_input(INPUT_POST, 'is_sleeping',  FILTER_VALIDATE_BOOLEAN);

If your "boolean" variable comes from other source you can use filter_var() filter function.

Example:

filter_var('true', FILTER_VALIDATE_BOOLEAN); // true

What are callee and caller saved registers?

Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.

For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.

It's normal to let a call destroy temporary values in these registers, though.

Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.

When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.

iOS 7 - Failing to instantiate default view controller

I have experienced this with my Tab Bar Controller not appearing in the Simulator along with a black screen. I did the following in order for my app to appear in the Simulator.

  1. Go to Main.storyboard.
  2. Check the Is Initial View Controller under the Attributes inspector tab.

Is Initial View Controller in the Attributes Inspector.

If you accidentally deleted that view controller, or otherwise made it not the default, then you’ll see the error “Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?” when your app launches, along with a plain black screen.

To fix the problem, open your Main.storyboard file and find whichever view controller you want to be shown when your app first runs. When it’s selected, go to the attributes inspector and check the box marked “Is Initial View Controller”. You should see a right-facing arrow appear to the left of that view controller, showing that it’s your storyboard’s entry point.

Matplotlib: Specify format of floats for tick labels

The answer above is probably the correct way to do it, but didn't work for me.

The hacky way that solved it for me was the following:

ax = <whatever your plot is> 
# get the current labels 
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family 
plt.show()

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

How can I print the contents of an array horizontally?

I would suggest:

foreach(var item in array)
  Console.Write("{0}", item);

As written above, except it does not raise an exception if one item is null.

Console.Write(string.Join(" ", array));

would be perfect if the array is a string[].

Test a weekly cron job

I'm using Webmin because its a productivity gem for someone who finds command line administration a bit daunting and impenetrable.

There is a "Save and Run Now" button in the "System > Scheduled Cron Jobs > Edit Cron Job" web interface.

It displays the output of the command and is exactly what I needed.

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

Get week of year in JavaScript like in PHP

Shortest workaround for Angular2+ DatePipe, adjusted for ISO-8601:

import {DatePipe} from "@angular/common";

public rightWeekNum: number = 0;
  
constructor(private datePipe: DatePipe) { }
    
calcWeekOfTheYear(dateInput: Date) {
  let falseWeekNum = parseInt(this.datePipe.transform(dateInput, 'ww'));
  this.rightWeekNum = (dateInput.getDay() == 0) ? falseWeekNumber-1 : falseWeekNumber;
}

Angular ReactiveForms: Producing an array of checkbox values?

Make an event when it's clicked and then manually change the value of true to the name of what the check box represents, then the name or true will evaluate the same and you can get all the values instead of a list of true/false. Ex:

component.html

<form [formGroup]="customForm" (ngSubmit)="onSubmit()">
    <div class="form-group" *ngFor="let parameter of parameters"> <!--I iterate here to list all my checkboxes -->
        <label class="control-label" for="{{parameter.Title}}"> {{parameter.Title}} </label>
            <div class="checkbox">
              <input
                  type="checkbox"
                  id="{{parameter.Title}}"
                  formControlName="{{parameter.Title}}"
                  (change)="onCheckboxChange($event)"
                  > <!-- ^^THIS^^ is the important part -->
             </div>
      </div>
 </form>

component.ts

onCheckboxChange(event) {
    //We want to get back what the name of the checkbox represents, so I'm intercepting the event and
    //manually changing the value from true to the name of what is being checked.

    //check if the value is true first, if it is then change it to the name of the value
    //this way when it's set to false it will skip over this and make it false, thus unchecking
    //the box
    if(this.customForm.get(event.target.id).value) {
        this.customForm.patchValue({[event.target.id] : event.target.id}); //make sure to have the square brackets
    }
}

This catches the event after it was already changed to true or false by Angular Forms, if it's true I change the name to the name of what the checkbox represents, which if needed will also evaluate to true if it's being checked for true/false as well.

How to extract numbers from a string and get an array of ints?

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
  System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

What's the difference between git reset --mixed, --soft, and --hard?

When you modify a file in your repository, the change is initially unstaged. In order to commit it, you must stage it—that is, add it to the index—using git add. When you make a commit, the changes that are committed are those that have been added to the index.

git reset changes, at minimum, where the current branch (HEAD) is pointing. The difference between --mixed and --soft is whether or not your index is also modified. So, if we're on branch master with this series of commits:

- A - B - C (master)

HEADpoints to C and the index matches C.

When we run git reset --soft B, master (and thus HEAD) now points to B, but the index still has the changes from C; git status will show them as staged. So if we run git commit at this point, we'll get a new commit with the same changes as C.


Okay, so starting from here again:

- A - B - C (master)

Now let's do git reset --mixed B. (Note: --mixed is the default option). Once again, master and HEAD point to B, but this time the index is also modified to match B. If we run git commit at this point, nothing will happen since the index matches HEAD. We still have the changes in the working directory, but since they're not in the index, git status shows them as unstaged. To commit them, you would git add and then commit as usual.


And finally, --hard is the same as --mixed (it changes your HEAD and index), except that --hard also modifies your working directory. If we're at C and run git reset --hard B, then the changes added in C, as well as any uncommitted changes you have, will be removed, and the files in your working copy will match commit B. Since you can permanently lose changes this way, you should always run git status before doing a hard reset to make sure your working directory is clean or that you're okay with losing your uncommitted changes.


And finally, a visualization: enter image description here

How to make readonly all inputs in some div in Angular2?

You can do like this. Open a ts file ad there make an interface with inputs you want and in the page you want to show under export class write

readonly yourinterface = yourinterface
readonly level: number[] = [];

and in your template do like this *ngFor="let yourtype of yourinterface"

Get/pick an image from Android's built-in Gallery app programmatically


Retrieve a specific type of file

This example will get a copy of the image.

static final int REQUEST_IMAGE_GET = 1;

public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        Uri fullPhotoUri = data.getData();
        // Do work with photo saved at fullPhotoUri
        ...
    }
}

Open a specific type of file

When running on 4.4 or higher, you request to open a file that's managed by another app

static final int REQUEST_IMAGE_OPEN = 1;

public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
    startActivityForResult(intent, REQUEST_IMAGE_OPEN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
        Uri fullPhotoUri = data.getData();
        // Do work with full size photo saved at fullPhotoUri
        ...
    }
}

Original source

Javascript set img src

If you're using WinJS you can change the src through the Utilities functions.

WinJS.Utilities.id("pic1").setAttribute("src", searchPic.src);

How to vertically align text in input type="text"?

input[type=text]
{
   height: 15px; 
   line-height: 15px;
}

this is correct way to set vertical-middle position.

What is the correct way to start a mongod service on linux / OS X?

mongod wasn't working to start the daemon for me but after I ran the following, it started working:

'mongod --fork --logpath /var/log/mongodb.log'

(from here: https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/)

Fastest way to convert string to integer in PHP

You can simply convert long string into integer by using FLOAT

$float = (float)$num;

Or if you want integer not floating val then go with

$float = (int)$num;

For ex.

(int)   "1212.3"   = 1212 
(float) "1212.3"   = 1212.3

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

While I'm all for unblocking people's work issues, I don't think "push --force" or "--allow_unrelated_histories" should be taught to new users as general solutions because they can cause real havoc to a repository when one uses them without understand why things aren't working in the first place.

When you have a situation like this where you started with a local repository, and want to make a remote on GitHub to share your work with, there is something to watch out for.

When you create the new online repository, there's an option "Initialize this repository with a README". If you read the fine print, it says "Skip this step if you’re importing an existing repository."

You may have checked that box. Or similarly, you made an add/commit online before you attempted an initial push. What happens is you create a unique commit history in each place and they can't be reconciled without the special allowance mentioned in Nevermore's answer (because git doesn't want you to operate that way). You can follow some of the advice mentioned here, or more simply just don't check that option next time you want to link some local files to a brand new remote; keeping the remote clean for that initial push.

Reference: my first experience with git + hub was to run into this same problem and do a lot of learning to understand what had happened and why.

Using the passwd command from within a shell script

This is the definitive answer for a teradata node admin.

Go to your /etc/hosts file and create a list of IP's or node names in a text file.

SMP007-1
SMP007-2
SMP007-3

Put the following script in a file.

#set a password across all nodes
printf "User ID: "
read MYUSERID
printf "New Password: "
read MYPASS

while read -r i; do
    echo changing password on "$i"
    ssh root@"$i" sudo echo "$MYUSERID":"$MYPASS" | chpasswd
    echo password changed on "$i"
done< /usr/bin/setpwd.srvrs

Okay I know I've broken a cardinal security rule with ssh and root but I'll let you security folks deal with it.

Now put this in your /usr/bin subdir along with your setpwd.srvrs config file.

When you run the command it prompts you one time for the User ID then one time for the password. Then the script traverses all nodes in the setpwd.srvrs file and does a passwordless ssh to each node, then sets the password without any user interaction or secondary password validation.

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

How to switch from POST to GET in PHP CURL

Add this before calling curl_exec($curl_handle)

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

SQL recursive query on self referencing table (Oracle)

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

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

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

What does bundle exec rake mean?

I have not used bundle exec much, but am setting it up now.

I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.

Here's how to set up RVM so you can use bundle exec by default within a specific project directory:

https://thoughtbot.com/blog/use-bundlers-binstubs

Regular cast vs. static_cast vs. dynamic_cast

Static cast

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

Reinterpret cast

To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.

int *r = reinterpret_cast<int*>(&c); // forced conversion

This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.

Dynamic cast

This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.

Dynamic cast examples

In the example below, a MyChild pointer is converted into a MyBase pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.

class MyBase 
{ 
  public:
  virtual void test() {}
};
class MyChild : public MyBase {};



int main()
{
  MyChild *child = new MyChild();
  MyBase  *base = dynamic_cast<MyBase*>(child); // ok
}

The next example attempts to convert a MyBase pointer to a MyChild pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.

MyBase  *base = new MyBase();
MyChild *child = dynamic_cast<MyChild*>(base);

 
if (child == 0) 
std::cout << "Null pointer returned";

If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a bad_cast exception. This needs to be handled using a try-catch statement.

#include <exception>
// …  
try
{ 
  MyChild &child = dynamic_cast<MyChild&>(*base);
}
catch(std::bad_cast &e) 
{ 
  std::cout << e.what(); // bad dynamic_cast
}

Dynamic or static cast

The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.

MyBase *base = static_cast<MyBase*>(child); // ok

However, in the second example the conversion may either succeed or fail. It will fail if the MyBase object contains a MyBase instance and it will succeed if it contains a MyChild instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.

// Succeeds for a MyChild object
MyChild *child = dynamic_cast<MyChild*>(base);

If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.

// Allowed, but invalid
MyChild *child = static_cast<MyChild*>(base);
 
// Incomplete MyChild object dereferenced
(*child);

Const cast

This one is primarily used to add or remove the const modifier of a variable.

const int myConst = 5;
int *nonConst = const_cast<int*>(&myConst); // removes const

Although const cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.

*nonConst = 10; // potential run-time error

Const cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.

void print(int *p) 
{
   std::cout << *p;
}

The function can then be passed a constant variable by using a const cast.

print(&myConst); // error: cannot convert 
                 // const int* to int*
 
print(nonConst); // allowed

Source and More Explanations

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

How to restore default perspective settings in Eclipse IDE

Alt+w-->or click on window tab -->ResetPerspective

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How do I revert a Git repository to a previous commit?

You can do this by the following two commands:

git reset --hard [previous Commit SHA id here]
git push origin [branch Name] -f

It will remove your previous Git commit.

If you want to keep your changes, you can also use:

git reset --soft [previous Commit SHA id here]

Then it will save your changes.

Jquery click not working with ipad

UPDATE: I switched .bind to .on because it's now the preferred way says jQuery.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. jquery.com

EXAMPLE:

$('.button').on("click touchstart", function() {

});

Below is the ultimate version of the click and touchstart event because it still fires even with new DOM objects that are added after the DOM has been loaded. Incorporating this ultimate click event solution for any scenario.

$(document).on("click touchstart", ".button", function () {

});

Facebook Javascript SDK Problem: "FB is not defined"

I had the same problem. The solutions was to use core.js instead of debug.core.js

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

Newtonsoft JSON Deserialize

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
    // Do something with typeStr
} 

string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

How to remove all non-alpha numeric characters from a string in MySQL?

Be careful, characters like ’ or » are considered as alpha by MySQL. It better to use something like :

IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND '9' OR c = '-' THEN

What is a non-capturing group in regular expressions?

Let me try this with an example:

Regex Code: (?:animal)(?:=)(\w+)(,)\1\2

Search String:

Line 1 - animal=cat,dog,cat,tiger,dog

Line 2 - animal=cat,cat,dog,dog,tiger

Line 3 - animal=dog,dog,cat,cat,tiger

(?:animal) --> Non-Captured Group 1

(?:=)--> Non-Captured Group 2

(\w+)--> Captured Group 1

(,)--> Captured Group 2

\1 --> result of captured group 1 i.e In Line 1 is cat, In Line 2 is cat, In Line 3 is dog.

\2 --> result of captured group 2 i.e comma (,)

So in this code by giving \1 and \2 we recall or repeat the result of captured group 1 and 2 respectively later in the code.

As per the order of code (?:animal) should be group 1 and (?:=) should be group 2 and continues..

but by giving the ?: we make the match-group non captured (which do not count off in matched group, so the grouping number starts from the first captured group and not the non captured), so that the repetition of the result of match-group (?:animal) can't be called later in code.

Hope this explains the use of non capturing group.

enter image description here

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

What are bitwise shift (bit-shift) operators and how do they work?

The Bitwise operators are used to perform operations a bit-level or to manipulate bits in different ways. The bitwise operations are found to be much faster and are some times used to improve the efficiency of a program. Basically, Bitwise operators can be applied to the integer types: long, int, short, char and byte.

Bitwise Shift Operators

They are classified into two categories left shift and the right shift.

  • Left Shift(<<): The left shift operator, shifts all of the bits in value to the left a specified number of times. Syntax: value << num. Here num specifies the number of position to left-shift the value in value. That is, the << moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each shift left, the high-order bit is shifted out (and ignored/lost), and a zero is brought in on the right. This means that when a left shift is applied to 32-bit compiler, bits are lost once they are shifted past bit position 31. If the compiler is of 64-bit then bits are lost after bit position 63.

enter image description here

Output: 6, Here the binary representation of 3 is 0...0011(considering 32-bit system) so when it shifted one time the leading zero is ignored/lost and all the rest 31 bits shifted to left. And zero is added at the end. So it became 0...0110, the decimal representation of this number is 6.

  • In the case of a negative number:

Code for Negative number.

Output: -2, In java negative number, is represented by 2's complement. SO, -1 represent by 2^32-1 which is equivalent to 1....11(Considering 32-bit system). When shifted one time the leading bit is ignored/lost and the rest 31 bits shifted to left and zero is added at the last. So it becomes, 11...10 and its decimal equivalent is -2. So, I think you get enough knowledge about the left shift and how its work.

  • Right Shift(>>): The right shift operator, shifts all of the bits in value to the right a specified of times. Syntax: value >> num, num specifies the number of positions to right-shift the value in value. That is, the >> moves/shift all of the bits in the specified value of the right the number of bit positions specified by num. The following code fragment shifts the value 35 to the right by two positions:

enter image description here

Output: 8, As a binary representation of 35 in a 32-bit system is 00...00100011, so when we right shift it two times the first 30 leading bits are moved/shifts to the right side and the two low-order bits are lost/ignored and two zeros are added at the leading bits. So, it becomes 00....00001000, the decimal equivalent of this binary representation is 8. Or there is a simple mathematical trick to find out the output of this following code: To generalize this we can say that, x >> y = floor(x/pow(2,y)). Consider the above example, x=35 and y=2 so, 35/2^2 = 8.75 and if we take the floor value then the answer is 8.

enter image description here

Output:

enter image description here

But remember one thing this trick is fine for small values of y if you take the large values of y it gives you incorrect output.

  • In the case of a negative number: Because of the negative numbers the Right shift operator works in two modes signed and unsigned. In signed right shift operator (>>), In case of a positive number, it fills the leading bits with 0. And In case of a negative number, it fills leading bits with 1. To keep the sign. This is called 'sign extension'.

enter image description here

Output: -5, As I explained above the compiler stores the negative value as 2's complement. So, -10 is represented as 2^32-10 and in binary representation considering 32-bit system 11....0110. When we shift/ move one time the first 31 leading bits got shifted in the right side and the low-order bit got lost/ignored. So, it becomes 11...0011 and the decimal representation of this number is -5 (How I know the sign of number? because the leading bit is 1). It is interesting to note that if you shift -1 right, the result always remains -1 since sign extension keeps bringing in more ones in the high-order bits.

  • Unsigned Right Shift(>>>): This operator also shifts bits to the right. The difference between signed and unsigned is the latter fills the leading bits with 1 if the number is negative and the former fills zero in either case. Now the question arises why we need unsigned right operation if we get the desired output by signed right shift operator. Understand this with an example, If you are shifting something that does not represent a numeric value, you may not want sign extension to take place. This situation is common when you are working with pixel-based values and graphics. In these cases, you will generally want to shift a zero into the high-order bit no matter what it's the initial value was.

enter image description here

Output: 2147483647, Because -2 is represented as 11...10 in a 32-bit system. When we shift the bit by one, the first 31 leading bit is moved/shifts in right and the low-order bit is lost/ignored and the zero is added to the leading bit. So, it becomes 011...1111 (2^31-1) and its decimal equivalent is 2147483647.

Get input value from TextField in iOS alert in Swift

In Swift5 ans Xcode 10

Add two textfields with Save and Cancel actions and read TextFields text data

func alertWithTF() {
    //Step : 1
    let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
    //Step : 2
    let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0] as UITextField
        let textField2 = alert.textFields![1] as UITextField
        if textField.text != "" {
            //Read TextFields text data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }

        if textField2.text != "" {
            print(textField2.text!)
            print("TF 2 : \(textField2.text!)")
        } else {
            print("TF 2 is Empty...")
        }
    }

    //Step : 3
    //For first TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your first name"
        textField.textColor = .red
    }
    //For second TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your last name"
        textField.textColor = .blue
    }

    //Step : 4
    alert.addAction(save)
    //Cancel action
    let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
    alert.addAction(cancel)
    //OR single line action
    //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })

    self.present(alert, animated:true, completion: nil)

}

For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

Onchange open URL via select - jQuery

<select name="xx" class="xxx" onchange="_name(this.options[this.selectedIndex].value,this.options[this.selectedIndex].getAttribute('rel'))">
  <option value="x" rel="xy">aa</option>
  <option value="xxx" rel="xyy">bb</option>
</select>


//for javascript
function _name(value,rel) {
alert(value+"-"+rel);
}

generate random double numbers in c++

Here's how

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

Remember to call srand() with a proper seed each time your program starts.

[Edit] This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons answer) But, this still applies to C

Force an SVN checkout command to overwrite current files

I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:

rm -rf lib
svn up

This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.

Illegal character in path at index 16

Did you try this?

new File("<PATH OF YOUR FILE>").toURI().toString();

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

How to define partitioning of DataFrame?

Use the DataFrame returned by:

yourDF.orderBy(account)

There is no explicit way to use partitionBy on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.

I just stumbled upon the same exact issue, with a dataframe that I want to partition by account. I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions() etc), right?

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

How to check if a String contains any of some strings

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

Java: recommended solution for deep cloning/copying an instance

For deep cloning implement Serializable on every class you want to clone like this

public static class Obj implements Serializable {
    public int a, b;
    public Obj(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

And then use this function:

public static Object deepClone(Object object) {
    try {
        ByteArrayOutputStream baOs = new ByteArrayOutputStream();
        ObjectOutputStream oOs = new ObjectOutputStream(baOs);
        oOs.writeObject(object);
        ByteArrayInputStream baIs = new ByteArrayInputStream(baOs.toByteArray());
        ObjectInputStream oIs = new ObjectInputStream(baIs);
        return oIs.readObject();
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

like this: Obj newObject = (Obj)deepClone(oldObject);

How to replace values at specific indexes of a python list?

A little slower, but readable I think:

>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d  #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

I'm an occasional iOS dev (soon to be more) but I still couldn't find the setting as guided by the other answer (since I did not have that Keychain item the answer shows), so now that I found it I thought I might just add this snapshot with the highlighted locations that you will need to click and find.

  1. Start in the upper left
  2. Choose the project folder icon
  3. Choose your main project name below the project folder icon.
  4. Choose Build Settings on the right side.
  5. Choose your project under TARGETS.
  6. Scroll very far down (or search for the word inference in search text box)

Finding the setting

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

how to check if input field is empty

As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

var input = $.trim($("#spa").val());

if (input) {
    // Do Stuff
}

You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

$(".test").each(function () {
    $(this).keyup(function () {
        $("#submit").prop("disabled", CheckInputs());
    });
});

which would then call the following and return a boolean value to assign to the disabled property:

function CheckInputs() {
    var valid = false;
    $(".test").each(function () {
        if (valid) { return valid; }
        valid = !$.trim($(this).val());
    });
    return valid;
}

You can see a working example of everything I've mentioned in this JSFiddle.

Spring REST Service: how to configure to remove null objects in json response

Since Jackson 2.0 you can use JsonInclude

@JsonInclude(Include.NON_NULL)
public class Shop {
    //...
}

How can I create and style a div using JavaScript?

Depends on how you're doing it. Pure javascript:

var div = document.createElement('div');
div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
div.style.color = 'red';
// better to use CSS though - just set class
div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
document.body.appendChild(div);

Doing the same using jquery is embarrassingly easy:

$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');

Cheers!

Reading specific columns from a text file in python

It may help:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

How to check whether java is installed on the computer

Using Apache Commons-Lang's SystemUtils.isJavaVersionAtLeast(JavaVersion)

import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;

if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)
    System.out.println("Java version was 8 or greater!");

Change text color with Javascript?

<div id="about">About Snakelane</div>

<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
<script>
var about;   
function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

How to import classes defined in __init__.py

Maybe this could work:

import __init__ as lib

how to convert binary string to decimal?

        var num = 10;

        alert("Binary " + num.toString(2));   //1010
        alert("Octal " + num.toString(8));    //12
        alert("Hex " + num.toString(16));     //a

        alert("Binary to Decimal "+ parseInt("1010", 2));  //10
        alert("Octal to Decimal " + parseInt("12", 8));    //10
        alert("Hex to Decimal " + parseInt("a", 16));      //10

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

SQL Server 2008 can't login with newly created user

Login to Server as Admin

Go To Security > Logins > New Login

Step 1:

Login Name : SomeName

Step 2:

Select  SQL Server / Windows Authentication.

More Info on, what is the differences between sql server authentication and windows authentication..?

Choose Default DB and Language of your choice

Click OK

Try to connect with the New User Credentials, It will prompt you to change the password. Change and login

OR

Try with query :

USE [master] -- Default DB
GO

CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO

--123456 is the Password And Username is Login User 
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO

Autoincrement VersionCode with gradle extra properties

To increment versionCode only in release version do it:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    def versionPropsFile = file('version.properties')
    def code = 1;
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))
        List<String> runTasks = gradle.startParameter.getTaskNames();
        def value = 0
        for (String item : runTasks)
        if ( item.contains("assembleRelease")) {
            value = 1;
        }
        code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value
        versionProps['VERSION_CODE']=code.toString()
        versionProps.store(versionPropsFile.newWriter(), null)
    }
    else {
        throw new GradleException("Could not read version.properties!")
    }

    defaultConfig {
        applicationId "com.pack"
        minSdkVersion 14
        targetSdkVersion 21
        versionName "1.0."+ code
        versionCode code
    }

expects an existing c://YourProject/app/version.properties file, which you would create by hand before the first build to have VERSION_CODE=8

File version.properties:

VERSION_CODE=8

Convert InputStream to JSONObject

This worked for me:

JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

How to create a date object from string in javascript

There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,

function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1   = parseInt(str1.substring(0,2));
var mon1  = parseInt(str1.substring(3,5));
var yr1   = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

How to use "like" and "not like" in SQL MSAccess for the same field?

If you're doing it in VBA (and not in a query) then: where field like "AA" and field not like "BB" then would not work.

You'd have to use: where field like "AA" and field like "BB" = false then

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

Why are Python lambdas useful?

I use lambdas to avoid code duplication. It would make the function easily comprehensible Eg:

def a_func()
  ...
  if some_conditon:
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)
  else
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)

I replace that with a temp lambda

def a_func()
  ...
  call_big_f = lambda args_that_change: call_some_big_func(arg1, arg2, arg3, args_that_change)
  if some_conditon:
     ...
     call_big_f(argX)
  else
     ...
     call_big_f(argY)

How to upgrade safely php version in wamp server

For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/

I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.

Enjoy!

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

Converts scss to css

First of all, you have to install Ruby if it is not on your machine.

1.Open a terminal window. 2.Run the command which ruby.

If you see a path such as /usr/bin/ruby, Ruby is installed. If you don't see any response or get an error message, Ruby is not installed. To verify that you have a current version of Ruby, run the command ruby -v.

If ruby is not installed on your machine then

sudo apt-get install ruby2.0
sudo apt-get install ruby2.0-dev
sudo update-alternatives --install /usr/bin/gem gem /usr/bin/gem2.0 1 

After then install Sass gem by running this command

sudo gem install sass --no-user-install

Then copy or add any .sass file and go to that file path and then

sass --watch style.scss:style.css 

When ever it notices a change in the .scss file it will update your .css

This only works when your .scss is on your local machine. Try copying the code to a file and running it locally.

How do I store an array in localStorage?

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars).

How to add composite primary key to table

In Oracle, you could do this:

create table D (
  ID numeric(1),
  CODE varchar(2),
  constraint PK_D primary key (ID, CODE)
);

Addition for BigDecimal

Using Java8 lambdas

List<BigDecimal> items = Arrays.asList(a, b, c, .....);

items.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

This covers cases where the some or all of the objects in the list is null.

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.

UNION with WHERE clause

In my experience, Oracle is very good at pushing simple predicates around. The following test was made on Oracle 11.2. I'm fairly certain it produces the same execution plan on all releases of 10g as well.

(Please people, feel free to leave a comment if you run an earlier version and tried the following)

create table table1(a number, b number);
create table table2(a number, b number);

explain plan for
select *
  from (select a,b from table1
        union 
        select a,b from table2
       )
 where a > 1;

select * 
  from table(dbms_xplan.display(format=>'basic +predicate'));

PLAN_TABLE_OUTPUT
---------------------------------------
| Id  | Operation            | Name   |
---------------------------------------
|   0 | SELECT STATEMENT     |        |
|   1 |  VIEW                |        |
|   2 |   SORT UNIQUE        |        |
|   3 |    UNION-ALL         |        |
|*  4 |     TABLE ACCESS FULL| TABLE1 |
|*  5 |     TABLE ACCESS FULL| TABLE2 |
---------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------    
   4 - filter("A">1)
   5 - filter("A">1)

As you can see at steps (4,5), the predicate is pushed down and applied before the sort (union).

I couldn't get the optimizer to push down an entire sub query such as

 where a = (select max(a) from empty_table)

or a join. With proper PK/FK constraints in place it might be possible, but clearly there are limitations :)

Bootstrap 3 offset on right not left

I'm using the following simple custom CSS I wrote to achieve this.

.col-xs-offset-right-12 {
  margin-right: 100%;
}
.col-xs-offset-right-11 {
  margin-right: 91.66666667%;
}
.col-xs-offset-right-10 {
  margin-right: 83.33333333%;
}
.col-xs-offset-right-9 {
  margin-right: 75%;
}
.col-xs-offset-right-8 {
  margin-right: 66.66666667%;
}
.col-xs-offset-right-7 {
  margin-right: 58.33333333%;
}
.col-xs-offset-right-6 {
  margin-right: 50%;
}
.col-xs-offset-right-5 {
  margin-right: 41.66666667%;
}
.col-xs-offset-right-4 {
  margin-right: 33.33333333%;
}
.col-xs-offset-right-3 {
  margin-right: 25%;
}
.col-xs-offset-right-2 {
  margin-right: 16.66666667%;
}
.col-xs-offset-right-1 {
  margin-right: 8.33333333%;
}
.col-xs-offset-right-0 {
  margin-right: 0;
}
@media (min-width: 768px) {
  .col-sm-offset-right-12 {
    margin-right: 100%;
  }
  .col-sm-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-sm-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-sm-offset-right-9 {
    margin-right: 75%;
  }
  .col-sm-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-sm-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-sm-offset-right-6 {
    margin-right: 50%;
  }
  .col-sm-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-sm-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-sm-offset-right-3 {
    margin-right: 25%;
  }
  .col-sm-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-sm-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-sm-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .col-md-offset-right-12 {
    margin-right: 100%;
  }
  .col-md-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-md-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-md-offset-right-9 {
    margin-right: 75%;
  }
  .col-md-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-md-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-md-offset-right-6 {
    margin-right: 50%;
  }
  .col-md-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-md-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-md-offset-right-3 {
    margin-right: 25%;
  }
  .col-md-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-md-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-md-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .col-lg-offset-right-12 {
    margin-right: 100%;
  }
  .col-lg-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-lg-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-lg-offset-right-9 {
    margin-right: 75%;
  }
  .col-lg-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-lg-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-lg-offset-right-6 {
    margin-right: 50%;
  }
  .col-lg-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-lg-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-lg-offset-right-3 {
    margin-right: 25%;
  }
  .col-lg-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-lg-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-lg-offset-right-0 {
    margin-right: 0;
  }
}

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

How to read numbers separated by space using scanf

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

NotificationCompat.Builder deprecated in Android O

This constructor was deprecated in API level 26.1.0. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

PHP - find entry by object property from an array of objects

I solved this problem by keying the array with the ID. It's simpler and possibly faster for this scenario where the ID is what you're looking for.

[420] => stdClass Object
        (
            [name] => Mary
         )

[10957] => stdClass Object
        (
            [name] => Blah
         )
...

Now I can directly address the array:

$array[$v]->name = ...

Or, if I want to verify the existence of an ID:

if (array_key_exists($v, $array)) { ...

Execute jQuery function after another function completes

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

So, you pass a function as parameter (callback) that will be called in that if before return.

Also, this is a good article about callbacks.

_x000D_
_x000D_
function Typer(callback)_x000D_
{_x000D_
    var srcText = 'EXAMPLE ';_x000D_
    var i = 0;_x000D_
    var result = srcText[i];_x000D_
    var interval = setInterval(function() {_x000D_
        if(i == srcText.length - 1) {_x000D_
            clearInterval(interval);_x000D_
            callback();_x000D_
            return;_x000D_
        }_x000D_
        i++;_x000D_
        result += srcText[i].replace("\n", "<br />");_x000D_
        $("#message").html(result);_x000D_
    },_x000D_
    100);_x000D_
    return true;_x000D_
        _x000D_
    _x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
    alert("Play BGM function");_x000D_
    $('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
    playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Python equivalent of D3.js

Another option is bokeh which just went to version 0.3.

Oracle 11g Express Edition for Windows 64bit?

There is

I used this blog post to install it in my machine: http://luminite.wordpress.com/2012/09/06/installing-oracle-database-xe-11g-on-windows-7-64-bit-machine/

The only thing you have to do is replace a registry value during the installation, I've done it about three times already, and every time found a different reference on-line, none here on stackoverflow.

EDIT: as @kc2001 noted, regedit must be run as Administrator, and added this tutorial: (a bit more colorful): http://www.hanmiaojuan.com/2013/03/install-oracle-xe-11g-for-windows7-64bits.html

Error TF30063: You are not authorized to access ... \DefaultCollection

I had to "run as a different user" to get Visual Studio to connect using my TFS account. It seemed to be trying to use my Microsoft account instead.

Text and image from: https://www.visualstudio.com/en-us/docs/connect/connect-team-projects

To change accounts

To run Visual Studio under an account that is different from your logged on Windows account, open the context menu for devenv.exe to access your run as options.

Context menu for Visual Studio devenv.exe

You can locate the executable in the following folder: Drive:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE.

Removing X-Powered-By

Try adding a header() call before sending headers, like:

header('X-Powered-By: Our company\'s development team');

regardless of the expose_php setting in php.ini

How to determine if a number is positive or negative?

The following is a terrible approach that would get you fired at any job...

It depends on you getting a Stack Overflow Exception [or whatever Java calls it]... And it would only work for positive numbers that don't deviate from 0 like crazy.

Negative numbers are fine, since you would overflow to positive, and then get a stack overflow exception eventually [which would return false, or "yes, it is negative"]

Boolean isPositive<T>(T a)
{
  if(a == 0) return true;
  else
  {
    try
    {
      return isPositive(a-1);
    }catch(StackOverflowException e)
    {
      return false; //It went way down there and eventually went kaboom
    }
  }
}

Preventing twitter bootstrap carousel from auto sliding on page load

--Use data-interval="false" to stop automatic slide --Use data-wrap="false" to stop circular slide

...

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

If the time is in milliseconds and one need to preserve them:

DECLARE @value VARCHAR(32) = '1561487667713';

SELECT DATEADD(MILLISECOND, CAST(RIGHT(@value, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(@value, 10) AS INT), '1970-01-01T00:00:00'))