Programs & Examples On #Doxygen

Doxygen is a multilanguage documentation generation application for C++, C, Java, Objective-C, Python, IDL, Fortran, VHDL, PHP and C# that supports a wide variety of output formats including RTF, HTML, XML and PDF.

How to document Python code using Doxygen

In the end, you only have two options:

You generate your content using Doxygen, or you generate your content using Sphinx*.

  1. Doxygen: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using doxypypy.

  2. Sphinx: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like).

    1. For manual API documentation you have Sphinx autodoc. This is great to write a user guide with embedded API generated elements.
    2. For semi-automatic you have Sphinx autosummary. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the autosummary_generate config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.
    3. Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until AutoAPI came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).

There are other options to note:

  • Breathe: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.
  • pydoctor*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.

How to make an introduction page with Doxygen

Have a look at the mainpage command.

Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox, .txt and .doc. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)

So I would recommend having a mainpage.dox (or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

convert a JavaScript string variable to decimal/money

I made a little helper function to do this and catch all malformed data

function convertToPounds(str) { 
    var n = Number.parseFloat(str);
    if(!str || isNaN(n) || n < 0) return 0;
    return n.toFixed(2);
}

Demo is here

Negation in Python

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.

How to return temporary table from stored procedure

A temp table can be created in the caller and then populated from the called SP.

  create table #GetValuesOutputTable(
     ...   
  );

  exec GetValues; -- populates #GetValuesOutputTable

  select * from #GetValuesOutputTable;

Some advantages of this approach over the "insert exec" is that it can be nested and that it can be used as input or output.

Some disadvantages are that the "argument" is not public, the table creation exists within each caller, and that the name of the table could collide with other temp objects. It helps when the temp table name closely matches the SP name and follows some convention.

Taking it a bit farther, for output only temp tables, the insert-exec approach and the temp table approach can be supported simultaneously by the called SP. This doesn't help too much for chaining SP's because the table still need to be defined in the caller but can help to simplify testing from the cmd line or when calling externally.

  -- The "called" SP
  declare
      @returnAsSelect bit = 0;

  if object_id('tempdb..#GetValuesOutputTable') is null
  begin
      set @returnAsSelect = 1;
      create table #GetValuesOutputTable(
         ...   
      );
  end

  -- populate the table

  if @returnAsSelect = 1
      select * from #GetValuesOutputTable;

How to check if a string in Python is in ASCII?

I use the following to determine if the string is ascii or unicode:

>> print 'test string'.__class__.__name__
str
>>> print u'test string'.__class__.__name__
unicode
>>> 

Then just use a conditional block to define the function:

def is_ascii(input):
    if input.__class__.__name__ == "str":
        return True
    return False

How to read Excel cell having Date with Apache POI?

If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

What is the difference between bottom-up and top-down?

Dynamic programming problems can be solved using either bottom-up or top-down approaches.

Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.

But you can also have bottom-up and top-down approaches using recursion as shown below.

Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.

int n = 5;
fibBottomUp(1, 1, 2, n);

private int fibBottomUp(int i, int j, int count, int n) {
    if (count > n) return 1;
    if (count == n) return i + j;
    return fibBottomUp(j, i + j, count + 1, n);
}

Top-Down: Start with the final condition and recursively get the result of its sub-problems.

int n = 5;
fibTopDown(n);

private int fibTopDown(int n) {
    if (n <= 1) return 1;
    return fibTopDown(n - 1) + fibTopDown(n - 2);
}

How to query nested objects?

Since there is a lot of confusion about queries MongoDB collection with sub-documents, I thought its worth to explain the above answers with examples:

First I have inserted only two objects in the collection namely: message as:

> db.messages.find().pretty()
{
    "_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
    "headers" : {
        "From" : "[email protected]"
    }
}
{
    "_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
    "headers" : {
        "From" : "[email protected]",
        "To" : "[email protected]"
    }
}
>

So what is the result of query: db.messages.find({headers: {From: "[email protected]"} }).count()

It should be one because these queries for documents where headers equal to the object {From: "[email protected]"}, only i.e. contains no other fields or we should specify the entire sub-document as the value of a field.

So as per the answer from @Edmondo1984

Equality matches within sub-documents select documents if the subdocument matches exactly the specified sub-document, including the field order.

From the above statements, what is the below query result should be?

> db.messages.find({headers: {To: "[email protected]", From: "[email protected]"}  }).count()
0

And what if we will change the order of From and To i.e same as sub-documents of second documents?

> db.messages.find({headers: {From: "[email protected]", To: "[email protected]"}  }).count()
1

so, it matches exactly the specified sub-document, including the field order.

For using dot operator, I think it is very clear for every one. Let's see the result of below query:

> db.messages.find( { 'headers.From': "[email protected]" }  ).count()
2

I hope these explanations with the above example will make someone more clarity on find query with sub-documents.

How to simulate a click with JavaScript?

What about something simple like:

document.getElementById('elementID').click();

Supported even by IE.

How can I configure Logback to log different levels for a logger to different destinations?

No programming needed. configuration make your life easy.

Below is the configuration which logs different level of logs to different files

<property name="DEV_HOME" value="./logs" />

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>INFO</level>
    </filter>
    <layout class="ch.qos.logback.classic.PatternLayout">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n
        </Pattern>
    </layout>
</appender>

<appender name="FILE-ERROR"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/app-error.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>${DEV_HOME}/archived/app-error.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <!--output messages of exact level only -->
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
</appender>
<appender name="FILE-INFO"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/app-info.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>${DEV_HOME}/archived/app-info.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>


    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <!--output messages of exact level only -->
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
</appender>


<appender name="FILE-DEBUG"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/app-debug.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>${DEV_HOME}/archived/app-debug.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>DEBUG</level>
        <!--output messages of exact level only -->
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
</appender>

<appender name="FILE-ALL"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/app.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>${DEV_HOME}/archived/app.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
</appender>

<logger name="com.abc.xyz" level="DEBUG" additivity="true">
    <appender-ref ref="FILE-DEBUG" />
    <appender-ref ref="FILE-INFO" />
    <appender-ref ref="FILE-ERROR" />
    <appender-ref ref="FILE-ALL" />
</logger>

<root level="INFO">
    <appender-ref ref="STDOUT" />
</root>

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

Setting Windows PowerShell environment variables

Like JeanT's answer, I wanted an abstraction around adding to the path. Unlike JeanT's answer I needed it to run without user interaction. Other behavior I was looking for:

  • Updates $env:Path so the change takes effect in the current session
  • Persists the environment variable change for future sessions
  • Doesn't add a duplicate path when the same path already exists

In case it's useful, here it is:

function Add-EnvPath {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Path,

        [ValidateSet('Machine', 'User', 'Session')]
        [string] $Container = 'Session'
    )

    if ($Container -ne 'Session') {
        $containerMapping = @{
            Machine = [EnvironmentVariableTarget]::Machine
            User = [EnvironmentVariableTarget]::User
        }
        $containerType = $containerMapping[$Container]

        $persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
        if ($persistedPaths -notcontains $Path) {
            $persistedPaths = $persistedPaths + $Path | where { $_ }
            [Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
        }
    }

    $envPaths = $env:Path -split ';'
    if ($envPaths -notcontains $Path) {
        $envPaths = $envPaths + $Path | where { $_ }
        $env:Path = $envPaths -join ';'
    }
}

Check out my gist for the corresponding Remove-EnvPath function.

How to get a file or blob from an object URL?

Modern solution:

let blob = await fetch(url).then(r => r.blob());

The url can be an object url or a normal url.

Visual Studio Code cannot detect installed git

I faced this problem on MacOS High Sierra 10.13.5 after upgrading Xcode.

When I run git command, I received below message:

Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.

After running sudo xcodebuild -license command, below message appears:

You have not agreed to the Xcode license agreements. You must agree to both license agreements below in order to use Xcode.

Hit the Enter key to view the license agreements at '/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'

Typing Enter key to open license agreements and typing space key to review details of it, until below message appears:

By typing 'agree' you are agreeing to the terms of the software license agreements. Type 'print' to print them or anything else to cancel, [agree, print, cancel]

The final step is simply typing agree to sign with the license agreement.


After typing git command, we can check that VSCode detected git again.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Disabling Use command-line client from the settings on IntelliJ Ultimate 14.0.3 works for me.

I checked IDEA's document, IDEA don't need a SVN client software anymore. see below description from https://www.jetbrains.com/idea/help/using-subversion-integration.html

=================================================================

Prerequisites

IntelliJ IDEA comes bundled with Subversion plugin. This plugin is turned on by default. If it is not, make sure that the plugin is enabled. IntelliJ IDEA's Subversion integration does not require a standalone Subversion client. All you need is an account in your Subversion repository. Subversion integration is enabled for the current project root or directory.

==================================================================

Font size relative to the user's screen resolution?

You might try this tool: http://fittextjs.com/

I haven't used this second tool, but it seems similar: https://github.com/zachleat/BigText

System.MissingMethodException: Method not found?

In my case it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:

using AutoMapper;

namespace Your.Namespace
{
    public class MappingProfile : Profile
    {
        MappingProfile()
        {
            CreateMap<Animal, AnimalDto>();
        }
    }
}

(take note of the missing "public" in front of the ctor)

which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can't (of course!) find the constructor!

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

id1.keySet().stream()
        .filter(x -> x == 1)
        .map(x -> id1.get(x))
        .collect(Collectors.toList())

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

How to set HttpResponse timeout for Android in Java

To set settings on the client:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(client.getParams(), 5000);

I've used this successfully on JellyBean, but should also work for older platforms ....

HTH

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Hide Text with CSS, Best Practice?

the way most developers will do is:

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

.webname {
   display: none;
}

I used to do it too, until i realized that you are hiding content for devices. aka screen-readers and such.

So by passing:

#web-title span {text-indent: -9000em;}

you ensure that the text still is readable.

"Unable to find remote helper for 'https'" during git clone

The easiest way to fix this problem is to ensure that the git-core is added to the path for your current user

If you add the following to your bash profile file in ~/.bash_profile this should normally resolve the issue

PATH=$PATH:/usr/libexec/git-core

Resize a picture to fit a JLabel

The best and easy way for image resize using Java Swing is:

jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));

For better display, identify the actual height & width of image and resize based on width/height percentage

Using HTTPS with REST in Java

Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.

How To Accept a File POST

I had a similar problem for the preview Web API. Did not port that part to the new MVC 4 Web API yet, but maybe this helps:

REST file upload with HttpRequestMessage or Stream?

Please let me know, can sit down tomorrow and try to implement it again.

What do I use on linux to make a python program executable

You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.

http://pythonhosted.org/PyInstaller/#using-pyinstaller

Python 3 has the native option of create a build dist also:

https://docs.python.org/3/distutils/builtdist.html

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

change it to Console (/SUBSYSTEM:CONSOLE) it will work

How can I check whether Google Maps is fully loaded?

I'm creating html5 mobile apps and I noticed that the idle, bounds_changed and tilesloaded events fire when the map object is created and rendered (even if it is not visible).

To make my map run code when it is shown for the first time I did the following:

google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    //this part runs when the mapobject is created and rendered
    google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
        //this part runs when the mapobject shown for the first time
    });
});

How can I divide two integers stored in variables in Python?

The 1./2 syntax works because 1. is a float. It's the same as 1.0. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float() on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division at the top of the module.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Get Month name from month number

You want GetAbbreviatedMonthName

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

OK so I think i know the issue you're having.

Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.

How to fix it (possibly) You need to add some extra information to your composer.json file.

"autoload": {
    "classmap": [
        "PATH TO YOUR MIGRATIONS FOLDER"
    ],
}

You need to add the path to your migrations folder to the classmap array. Then run the following three commands...

php artisan clear-compiled 
composer dump-autoload
php artisan optimize

This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.

Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).

Hope you can manage to get this sorted, as its very annoying indeed :(

Big-oh vs big-theta

There are a lot of good answers here but I noticed something was missing. Most answers seem to be implying that the reason why people use Big O over Big Theta is a difficulty issue, and in some cases this may be true. Often a proof that leads to a Big Theta result is far more involved than one that results in Big O. This usually holds true, but I do not believe this has a large relation to using one analysis over the other.

When talking about complexity we can say many things. Big O time complexity is just telling us what an algorithm is guarantied to run within, an upper bound. Big Omega is far less often discussed and tells us the minimum time an algorithm is guarantied to run, a lower bound. Now Big Theta tells us that both of these numbers are in fact the same for a given analysis. This tells us that the application has a very strict run time, that can only deviate by a value asymptoticly less than our complexity. Many algorithms simply do not have upper and lower bounds that happen to be asymptoticly equivalent.

So as to your question using Big O in place of Big Theta would technically always be valid, while using Big Theta in place of Big O would only be valid when Big O and Big Omega happened to be equal. For instance insertion sort has a time complexity of Big ? at n^2, but its best case scenario puts its Big Omega at n. In this case it would not be correct to say that its time complexity is Big Theta of n or n^2 as they are two different bounds and should be treated as such.

Using underscores in Java variables and method names

sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs();

as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();

How to cancel a pull request on github?

Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Message Queue vs. Web Services?

Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.

The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.

How to get file creation date/time in Bash/Debian?

ls -i menus.xml

94490 menus.xml Here the number 94490 represents inode

Then do a:

df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg-root   4.0G  3.4G  408M  90% /
tmpfs                 1.9G     0  1.9G   0% /dev/shm
/dev/sda1             124M   27M   92M  23% /boot
/dev/mapper/vg-var    7.9G  1.1G  6.5G  15% /var

To find the mounting point of the root "/" filesystem, because the file menus.xml is on '/' that is '/dev/mapper/vg-root'

debugfs -R 'stat <94490>' /dev/mapper/vg-root

The output may be like the one below:

debugfs -R 'stat <94490>' /dev/mapper/vg-root

debugfs 1.41.12 (17-May-2010)
Inode: 94490   Type: regular    Mode:  0644   Flags: 0x0
Generation: 2826123170    Version: 0x00000000
User:     0   Group:     0   Size: 4441
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 16
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
atime: 0x5266e47b -- Wed Oct 23 09:47:55 2013
mtime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
Size of extra inode fields: 4
Extended attributes stored in inode body: 
  selinux = "unconfined_u:object_r:usr_t:s0\000" (31)
BLOCKS:
(0-1):375818-375819
TOTAL: 2

Where you can see the creation time:

ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013

Android SeekBar setOnSeekBarChangeListener

onProgressChanged is called every time you move the cursor.

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    textView.setText(String.valueOf(new Integer(progress)));        
}

so textView should show the progress and alter always if the seekbar is being moved.

Understanding "VOLUME" instruction in DockerFile

To better understand the volume instruction in dockerfile, let us learn the typical volume usage in mysql official docker file implementation.

VOLUME /var/lib/mysql

Reference: https://github.com/docker-library/mysql/blob/3362baccb4352bcf0022014f67c1ec7e6808b8c5/8.0/Dockerfile

The /var/lib/mysql is the default location of MySQL that store data files.

When you run test container for test purpose only, you may not specify its mounting point,e.g.

docker run mysql:8

then the mysql container instance will use the default mount path which is specified by the volume instruction in dockerfile. the volumes is created with a very long ID-like name inside the Docker root, this is called "unnamed" or "anonymous" volume. In the folder of underlying host system /var/lib/docker/volumes.

/var/lib/docker/volumes/320752e0e70d1590e905b02d484c22689e69adcbd764a69e39b17bc330b984e4

This is very convenient for quick test purposes without the need to specify the mounting point, but still can get best performance by using Volume for data store, not the container layer.

For a formal use, you will need to specify the mount path by using named volume or bind mount, e.g.

docker run  -v /my/own/datadir:/var/lib/mysql mysql:8

The command mounts the /my/own/datadir directory from the underlying host system as /var/lib/mysql inside the container.The data directory /my/own/datadir won't be automatically deleted, even the container is deleted.

Usage of the mysql official image (Please check the "Where to Store Data" section):

Reference: https://hub.docker.com/_/mysql/

How do I set up NSZombieEnabled in Xcode 4?

In Xcode 4.2

  • Project Name/Edit Scheme/Diagnostics/
  • Enable Zombie Objects check box
  • You're done

Implementing Singleton with an Enum (in Java)

In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Ignore outliers in ggplot2 boxplot

Here is a solution using boxplot.stats

# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))

# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))


# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]

# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)

Use curly braces to initialize a Set in Python

There are two obvious issues with the set literal syntax:

my_set = {'foo', 'bar', 'baz'}
  1. It's not available before Python 2.7

  2. There's no way to express an empty set using that syntax (using {} creates an empty dict)

Those may or may not be important to you.

The section of the docs outlining this syntax is here.

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

These are options to fix this problem:

Option 1: change you host into 127.0.0.1

staging:
  adapter: mysql2
  host: 127.0.0.1
  username: root
  password: xxxx
  database: xxxx
  socket: your-location-socket

Option 2: It seems like you have 2 connections into you server MySql. To find your socket file location do this:

mysqladmin variables | grep socket

for me gives:

mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' exists!

or

mysql --help 

I get this error because I installed XAMPP in my OS X Version 10.9.5 for PHP application. Choose one of the default socket location here.

I choose for default rails apps:

socket: /tmp/mysql.sock

For my PHP apps, I install XAMPP so I set my socket here:

socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

OTHERS Socket Location in OS X

For MAMPP:

socket: /Applications/MAMP/tmp/mysql/mysql.sock

For Package Installer from MySQL:

socket: /tmp/mysql.sock

For MySQL Bundled with Mac OS X Server:

socket: /var/mysql/mysql.sock

For Ubuntu:

socket: /var/run/mysqld/mysql.sock

Option 3: If all those setting doesn't work you can remove your socket location:

staging:
  # socket: /var/run/mysqld/mysql.sock

I hope this help you.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Choose newline character in Notepad++

For a new document: Settings -> Preferences -> New Document/Default Directory -> New Document -> Format -> Windows/Mac/Unix

And for an already-open document: Edit -> EOL Conversion

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Guzzlehttp - How get the body of a response from Guzzle 6?

If expecting JSON back, the simplest way to get it:

$data = json_decode($response->getBody()); // returns an object

// OR

$data = json_decode($response->getBody(), true); // returns an array

json_decode() will automatically cast the body to string, so there is no need to call getContents().

jQuery has deprecated synchronous XMLHTTPRequest

This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:

<script src="http://somesite.net/js/somefile.js">

It did not have anything to do with JQuery.

You would probably see the same doing something like this:

var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);

But I haven't tested that idea.

How to read a PEM RSA private key from .NET

I've tried the accepted answer for PEM-encoded PKCS#8 RSA private key and it resulted in PemException with malformed sequence in RSA private key message. The reason is that Org.BouncyCastle.OpenSsl.PemReader seems to only support PKCS#1 private keys.

I was able to get the private key by switching to Org.BouncyCastle.Utilities.IO.Pem.PemReader (note that type names match!) like this

private static RSAParameters GetRsaParameters(string rsaPrivateKey)
{
    var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
    using (var ms = new MemoryStream(byteArray))
    {
        using (var sr = new StreamReader(ms))
        {
            var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr);
            var pem = pemReader.ReadPemObject();
            var privateKey = PrivateKeyFactory.CreateKey(pem.Content);

            return DotNetUtilities.ToRSAParameters(privateKey as RsaPrivateCrtKeyParameters);
        }
    }
}

How do I replace text in a selection?

ST2 has a feature for changing multiple selections at once.

  1. Double click the first instance of 0 that you want to change.
  2. Press the key for Find->Quick Add Next* to select the next instance of 0, and repeat until you've selected all the instances of 0 that you want to change.
    If this method selects an instance that you want to skip, press the key for Find->Quick Skip Next.
  3. Verify that the multiple highlighted fields are what you want to replace. Next, type in '255' and it should modify all of the selected instances simultaneously.

*Look at the Find menu on the menu bar to find the correct shortcut key for your system. For vanilla Windows, the menu tells you that Find->Quick Add Next is Ctrl+D and Find->Quick Skip Next is Ctrl+K,Ctrl+D.

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

Two onClick actions one button

Give your button an id something like this:


<input id="mybutton" type="button" value="Dont show this again! " />

Then use jquery (to make this unobtrusive) and attach click action like so:


$(document).ready(function (){
    $('#mybutton').click(function (){
       fbLikeDump();
       WriteCookie();
    });
});

(this part should be in your .js file too)

I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>

The reason to add just before body closing tag is for performance of perceived page loading times

SyntaxError: "can't assign to function call"

You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )

subsequent_amount = invest(initial_amount,top_company(5,year,year+1))

Android getting value from selected radiobutton

For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:

    for(int i = 0; i < myNames.length; i++) {
        rB = new RadioButton(getContext());
        rB.setText(myNames[i]);
        rB.setTag(i);
        myRadioGroup.addView(rB,i);
    }

Then in your listener:

    myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            int mySelectedIndex = (int) radioButton.getTag();
        }
    });

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

adb -d shell (or adb -e shell).

This command will help you in most of the cases, if you are too lazy to type the full ID.

From http://developer.android.com/tools/help/adb.html#commandsummary:

-d - Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e - Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

How to find my realm file?

To get the DB path for iOS, the simplest way is to:

  1. Launch your app in a simulator
  2. Pause it at any time in the debugger
  3. Go to the console (where you have (lldb)) and type: po RLMRealm.defaultRealmPath

Tada...you have the path to your realm database

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

Remove all values within one list from another list?

a = range(1,10)
itemsToRemove = set([2, 3, 7])
b = filter(lambda x: x not in itemsToRemove, a)

or

b = [x for x in a if x not in itemsToRemove]

Don't create the set inside the lambda or inside the comprehension. If you do, it'll be recreated on every iteration, defeating the point of using a set at all.

What is the best way to test for an empty string with jquery-out-of-the-box?

Since you can also input numbers as well as fixed type strings, the answer should actually be:

function isBlank(value) {
  return $.trim(value);
}

How to compress a String in Java?

Compression algorithms almost always have some form of space overhead, which means that they are only effective when compressing data which is sufficiently large that the overhead is smaller than the amount of saved space.

Compressing a string which is only 20 characters long is not too easy, and it is not always possible. If you have repetition, Huffman Coding or simple run-length encoding might be able to compress, but probably not by very much.

Open firewall port on CentOS 7

The answer by ganeshragav is correct, but it is also useful to know that you can use:

firewall-cmd --permanent --zone=public --add-port=2888/tcp 

but if is a known service, you can use:

firewall-cmd --permanent --zone=public --add-service=http 

and then reload the firewall

firewall-cmd --reload

[ Answer modified to reflect Martin Peter's comment, original answer had --permanent at end of command line ]

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

Query to list number of records in each table in a database

Well luckily SQL Server management studio gives you a hint on how to do this. Do this,

  1. start a SQL Server trace and open the activity you are doing (filter by your login ID if you're not alone and set the application Name to Microsoft SQL Server Management Studio), pause the trace and discard any results you have recorded till now;
  2. Then, right click a table and select property from the pop up menu;
  3. start the trace again;
  4. Now in SQL Server Management studio select the storage property item on the left;

Pause the trace and have a look at what TSQL is generated by microsoft.

In the probably last query you will see a statement starting with exec sp_executesql N'SELECT

when you copy the executed code to visual studio you will notice that this code generates all the data the engineers at microsoft used to populate the property window.

when you make moderate modifications to that query you will get to something like this:

SELECT
SCHEMA_NAME(tbl.schema_id)+'.'+tbl.name as [table], --> something I added
p.partition_number AS [PartitionNumber],
prv.value AS [RightBoundaryValue],
 fg.name AS [FileGroupName],
CAST(pf.boundary_value_on_right AS int) AS [RangeType],
CAST(p.rows AS float) AS [RowCount],
p.data_compression AS [DataCompression]
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and idx.index_id < 2
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int) AND p.index_id=idx.index_id
LEFT OUTER JOIN sys.destination_data_spaces AS dds ON dds.partition_scheme_id = idx.data_space_id and dds.destination_id = p.partition_number
LEFT OUTER JOIN sys.partition_schemes AS ps ON ps.data_space_id = idx.data_space_id
LEFT OUTER JOIN sys.partition_range_values AS prv ON prv.boundary_id = p.partition_number and prv.function_id = ps.function_id
LEFT OUTER JOIN sys.filegroups AS fg ON fg.data_space_id = dds.data_space_id or fg.data_space_id = idx.data_space_id
LEFT OUTER JOIN sys.partition_functions AS pf ON  pf.function_id = prv.function_id

Now the query is not perfect and you could update it to meet other questions you might have, the point is, you can use the knowledge of microsoft to get to most of the questions you have by executing the data you're interested in and trace the TSQL generated using profiler.

I kind of like to think that MS engineers know how SQL server work and, it will generate TSQL that works on all items you can work with using the version on SSMS you are using so it's quite good on a large variety releases prerviouse, current and future.

And remember, don't just copy, try to understand it as well else you might end up with the wrong solution.

Walter

Open Source Alternatives to Reflector?

Well, Reflector itself is a .NET assembly so you can open Reflector.exe in Reflector to check out how it's built.

How do I get currency exchange rates via an API such as Google Finance?

If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.

Disclaimer, I'm the author of the website and I use it for one of my other websites.

The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.

A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}

How to send and retrieve parameters using $state.go toParams and $stateParams?

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

In the state add your params to end of state and define the params:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

How do you change the colour of each category within a highcharts column chart?

Just add this...or you can change the colors as per your demand.

Highcharts.setOptions({
        colors: ['#811010', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
        plotOptions: {
            column: {
                colorByPoint: true
            }
        }

    });

Custom Date Format for Bootstrap-DatePicker

var type={
      format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);

Pip error: Microsoft Visual C++ 14.0 is required

I got this error when I tried to install pymssql even though Visual C++ 2015 (14.0) is installed in my system.

I resolved this error by downloading the .whl file of pymssql from here.

Once downloaded, it can be installed by the following command :

pip install python_package.whl

Hope this helps

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Batch file: Find if substring is in string (not in a file)

I'm probably coming a bit too late with this answer, but the accepted answer only works for checking whether a "hard-coded string" is a part of the search string.

For dynamic search, you would have to do this:

SET searchString=abcd1234
SET key=cd123

CALL SET keyRemoved=%%searchString:%key%=%%

IF NOT "x%keyRemoved%"=="x%searchString%" (
    ECHO Contains.
)

Note: You can take the two variables as arguments.

Why does AngularJS include an empty option in select?

A simple solution is to set an option with a blank value "" I found this eliminates the extra undefined option.

How do I push a new local branch to a remote Git repository and track it too?

Simply put, to create a new local branch, do:

git branch <branch-name>

To push it to the remote repository, do:

git push -u origin <branch-name>

How do I autoindent in Netbeans?

Here's the complete procedure to auto-indent a file with Netbeans 8.

First step is to go to Tools -> Options and click on Editor button and Formatting tab as it is shown on the following image.

enter image description here

When you have set your formatting options, click the Apply button and OK. Note that my example is with C++ language, but this also apply for Java as well.

The second step is to CTRL + A on the file where you want to apply your new formatting setting. Then, ALT + SHIFT + F or click on the menu Source -> Format.

Hope this will help.

get everything between <tag> and </tag> with php

You can also try:

function getTagValue($string, $tag)
{
    $pattern = "/<{$tag}>(.*?)<\/{$tag}>/s";
    preg_match($pattern, $string, $matches);
    return isset($matches[1]) ? $matches[1] : '';
}

It returns empty string in case of no match.

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

How do I make Java register a string input with spaces?

I found a very weird thing in Java today, so it goes like -

If you are inputting more than 1 thing from the user, say

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s

But, the output that you will get is -

10
2.5

And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().

So changing my code to something like this -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.

Please if anybody knows help me with an explanation for this.

How to inject Javascript in WebBrowser control?

Also, in .NET 4 this is even easier if you use the dynamic keyword:

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How to get hex color value rather than RGB value?

full cases (rgb, rgba, transparent...etc) solution (coffeeScript)

 rgb2hex: (rgb, transparentDefault=null)->
    return null unless rgb
    return rgb if rgb.indexOf('#') != -1
    return transparentDefault || 'transparent' if rgb == 'rgba(0, 0, 0, 0)'
    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
    hex = (x)->
      ("0" + parseInt(x).toString(16)).slice(-2)

    '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3])

Unable to call the built in mb_internal_encoding method?

If someone is having trouble with installing php-mbstring package in ubuntu do following sudo apt-get install libapache2-mod-php5

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

Capture Video of Android's Screen

I guess screencast is no go cause of tegra 2 incompatibility, i already tried it,but no whey! So i tried using Z-ScreeNRecorder from market,installed it on my LG Optimus 2x, but it record's only blank screen,i tried for 5min. and there i get 5min. of blank screen file of 6mb size... so there is no point trying until they release some peace of software that is compatible with tegra2 chipset!

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case, my App icon files were not in the camel case notation. For example:

My Filename: Appicon57x57

Should be: AppIcon57x57 (note the capital 'i' here)

So, in my case the solution was this:

  1. Remove all the icon files from the Asset Catalog.
  2. Rename the file as mentioned above.
  3. Add the renamed files back to the Asset Catalog again.

This should fix the problem.

#include errors detected in vscode

Tried these solutions and many others over 1 hour. Ended up with closing VS Code and opening it again. That's simple.

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

Swap two items in List<T>

Maybe someone will think of a clever way to do this, but you shouldn't. Swapping two items in a list is inherently side-effect laden but LINQ operations should be side-effect free. Thus, just use a simple extension method:

static class IListExtensions {
    public static void Swap<T>(
        this IList<T> list,
        int firstIndex,
        int secondIndex
    ) {
        Contract.Requires(list != null);
        Contract.Requires(firstIndex >= 0 && firstIndex < list.Count);
        Contract.Requires(secondIndex >= 0 && secondIndex < list.Count);
        if (firstIndex == secondIndex) {
            return;
        }
        T temp = list[firstIndex];
        list[firstIndex] = list[secondIndex];
        list[secondIndex] = temp;
    }
}

Setting the filter to an OpenFileDialog to allow the typical image formats?

Follow this pattern if you browsing for image files:

dialog.Filter =  "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";

Change Circle color of radio button

Working on API pre 21 as well as post 21. In your styles.xml put:

<!-- custom style -->
<style name="radionbutton"
       parent="Base.Widget.AppCompat.CompoundButton.RadioButton">
    <item name="android:button">@drawable/radiobutton_drawable</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>

Your radio button in xml should look like:

<RadioButton
    android:layout_width="wrap_content"
    style="@style/radionbutton"
    android:checked="false"
    android:layout_height="wrap_content"
    />

Now all you need to do is make a radiobutton_drawable.xml in your drawable folder. Here is what you need to put in it:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="false"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="false"/>
</selector>

Your radio_unchecked.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="oval">
  <stroke android:width="1dp" android:color="@color/colorAccent"/>
  <size android:width="30dp" android:height="30dp"/>
</shape>

Your radio_checked.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="oval">
      <stroke android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="30dp" android:height="30dp"/>
    </shape>
  </item>
  <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
    <shape android:shape="oval">
      <solid android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="10dp" android:height="10dp"/>
    </shape>
  </item>
</layer-list>

Just replace @color/colorAccent with the color of your choice.

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Find by key deep in a nested array

Another recursive solution, that works for arrays/lists and objects, or a mixture of both:

function deepSearchByKey(object, originalKey, matches = []) {

    if(object != null) {
        if(Array.isArray(object)) {
            for(let arrayItem of object) {
                deepSearchByKey(arrayItem, originalKey, matches);
            }
        } else if(typeof object == 'object') {

            for(let key of Object.keys(object)) {
                if(key == originalKey) {
                    matches.push(object);
                } else {
                    deepSearchByKey(object[key], originalKey, matches);
                }

            }

        }
    }


    return matches;
}

usage:

let result = deepSearchByKey(arrayOrObject, 'key'); // returns an array with the objects containing the key

importing external ".txt" file in python

The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:

text = open("words.txt", "rb").read()

How to set variable from a SQL query?

declare @ModelID uniqueidentifer

--make sure to use brackets
set @ModelID = (select modelid from models
where areaid = 'South Coast')

select @ModelID

C# Listbox Item Double Click Event

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    int index = this.listBox1.IndexFromPoint(e.Location);
    if (index != System.Windows.Forms.ListBox.NoMatches)
    {
        MessageBox.Show(index.ToString());
    }
}

This should work...check

How to display HTML tags as plain text

The native JavaScript approach -

('<strong>Look just ...</strong>').replace(/</g, '&lt;').replace(/>/g, '&gt;');

Enjoy!

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

How to get user's high resolution profile picture on Twitter?

for me the "workaround" solution was to remove the "_normal" from the end of the string

Check it out below:

What is polymorphism, what is it for, and how is it used?

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

Here is an example in C#. Create four classes within a console application:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

Now create the following in the Main() of the module for the console application:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

We then add a Bicycle, Car and Truck to the list.

Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

I hope that this helps you.

Iterate keys in a C++ map

With C++11 the iteration syntax is simple. You still iterate over pairs, but accessing just the key is easy.

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> myMap;

    myMap["one"] = 1;
    myMap["two"] = 2;
    myMap["three"] = 3;

    for ( const auto &myPair : myMap ) {
        std::cout << myPair.first << "\n";
    }
}

Unable to start MySQL server

You should start by checking the error log and/or the startup message log when managing the instance using MySQL Workbench. There could be clues as to what is going wrong, which may be different than this scenario.

When I had this issue, it was because I used a space in the service name during installation. While it is technically valid, you should not do that. It seems that the MySQL Installer (and MySQL Notifier) does not put the name in quotes which causes it to use an incorrect service name later on. There are two ways to fix the problem (all commands should be run from an elevated command prompt).

Reinstall the server

The first is to simply reinstall MySQL Server 5.6 using the default, no-space service name MySQL56.

The installer uses the same value for the service name and service display name. The name that I had originally specified was for a display name, when it should have been a simple service name. After installation, if you so choose, the display name can safely be changed to use spaces and other characters by using:

sc config MySQL56 DisplayName= "MySQL 5.6"

Recreate the service

If you don't want to reinstall the server however, you will have to recreate the service. Start by removing the old service:

mysqld --remove "service_name"

Now install the replacement. You can use --install to create a service that starts with the system automatically, or --install-manual to create a service that requires you to start it.

mysqld --install-manual "service_name" --local-service --defaults-file="C:\path\to\mysql\my.ini"

This creates a service that runs as the LocalService account which presents anonymous credentials on the network however. Under most circumstances this is fine, but if you want to use the NetworkService account (which is what the installer creates the service as) you can change it using the Services administrative tool.

What's the whole point of "localhost", hosts and ports at all?

Yes, localhost just means that you are talking to the webserver om the same machine that you are currently using.

Other servers are contacted through either their IP-address or a given name.

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

Can a shell script set environment variables of the calling shell?

Under OS X bash you can do the following:
Create the bash script file to unset the variable

#!/bin/bash
unset http_proxy

Make the file executable

sudo chmod 744 unsetvar

Create alias

alias unsetvar='source /your/path/to/the/script/unsetvar'

It should be ready to use so long you have the folder containing your script file appended to the path.

How to automatically add user account AND password with a Bash script?

You could also use chpasswd:

echo username:new_password | chpasswd

so, you change password for user username to new_password.

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

How to position a table at the center of div horizontally & vertically

I discovered that I had to include

body { width:100%; }

for "margin: 0 auto" to work for tables.

warning: implicit declaration of function

I think the question is not 100% answered. I was searching for issue with missing typeof(), which is compile time directive.

Following links will shine light on the situation:

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Typeof.html

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Alternate-Keywords.html#Alternate-Keywords

as of conculsion try to use __typeof__() instead. Also gcc ... -Dtypeof=__typeof__ ... can help.

How to resolve "Server Error in '/' Application" error?

I had this error when the .NET version was wrong - make sure the site is configured to the one you need.

See aspnet_regiis.exe for details.

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

How to convert Blob to File in JavaScript

For me to work I had to explicitly provide the type although it is contained in the blob by doing so:

const file = new File([blob], 'untitled', { type: blob.type })

How to Identify port number of SQL server

PowerShell solution that shows all of the instances on the host as well as their incoming traffic addresses. The second bit might be helpful if all you know is the DNS:

ForEach ($SQL_Proc in Get-Process | Select-Object -Property ProcessName, Id | Where-Object {$_.ProcessName -like "*SQL*"})
{
    Get-NetTCPConnection | `
     Where-Object {$_.OwningProcess -eq $SQL_Proc.id} | `
      Select-Object -Property `
                                @{Label ="Process_Name";e={$SQL_Proc.ProcessName}}, `
                                @{Label ="Local_Address";e={$_.LocalAddress + ":" + $_.LocalPort }},  `
                                @{Label ="Remote_Address";e={$_.RemoteAddress + ":" + $_.RemotePort}}, State | `
      Format-Table
} 

jQuery set radio button

Using .filter() also works, and is flexible for id, value, name:

$('input[name="cols"]').filter("[value='Site']").attr('checked', true);

(seen on this blog)

Set Background color programmatically

If you save color code in the colors.xml which is under the values folder,then you should call the following:

root.setBackgroundColor(getResources().getColor(R.color.name));

name means you declare in the <color/> tag.

How to create a DB for MongoDB container on start up?

If you are looking to remove usernames and passwords from your docker-compose.yml you can use Docker Secrets, here is how I have approached it.

version: '3.6'

services:
  db:
    image: mongo:3
    container_name: mycontainer
  secrets:
    - MONGO_INITDB_ROOT_USERNAME
    - MONGO_INITDB_ROOT_PASSWORD
  environment:
    - MONGO_INITDB_ROOT_USERNAME_FILE=/var/run/secrets/MONGO_INITDB_ROOT_USERNAME
    - MONGO_INITDB_ROOT_PASSWORD_FILE=/var/run/secrets/MONGO_INITDB_ROOT_PASSWORD
secrets:
  MONGO_INITDB_ROOT_USERNAME:
    file:  secrets/${NODE_ENV}_mongo_root_username.txt
  MONGO_INITDB_ROOT_PASSWORD:
    file:  secrets/${NODE_ENV}_mongo_root_password.txt

I have use the file: option for my secrets however, you can also use external: and use the secrets in a swarm.

The secrets are available to any script in the container at /var/run/secrets

The Docker documentation has this to say about storing sensitive data...

https://docs.docker.com/engine/swarm/secrets/

You can use secrets to manage any sensitive data which a container needs at runtime but you don’t want to store in the image or in source control, such as:

Usernames and passwords TLS certificates and keys SSH keys Other important data such as the name of a database or internal server Generic strings or binary content (up to 500 kb in size)

javascript compare strings without being case sensitive

Another method using a regular expression (this is more correct than Zachary's answer):

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

RegExp.test() will return true or false.

Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.

It might just be easier to use the string.toLowerCase() method.

So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.

There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php

This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/

How to concatenate two layers in keras?

Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

Result:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

Display animated GIF in iOS

#import <QuickLook/QuickLook.h>
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    QLPreviewController *preview = [[QLPreviewController alloc] init];
    preview.dataSource = self;

    [self addChildViewController:preview];
    [self.view addSubview:preview.view];
}

#pragma mark - QLPreviewControllerDataSource

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController
{
    return 1;
}

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
    NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myanimated.gif" ofType:nil]];
    return fileURL;
}

@end

Locate Git installation folder on Mac OS X

Mostly in /usr/local/git (there are also /etc/paths.d/git and /etc/manpaths.d/git items).

Add items to comboBox in WPF

I think comboBox1.Items.Add("X"); will add string to ComboBox, instead of ComboBoxItem.

The right solution is

ComboBoxItem item = new ComboBoxItem();
item.Content = "A";
comboBox1.Items.Add(item);

Integer division: How do you produce a double?

Type Casting Is The Only Way

May be you will not do it explicitly but it will happen.

Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-

  1. with explicit casting:
  • double d = (double) num / denom;
  • double d = ((double) num) / denom;
  • double d = num / (double) denom;
  • double d = (double) num / (double) denom;

but not double d = (double) (num / denom);

  1. with implicit casting:
  • double d = num * 1.0 / denom;
  • double d = num / 1d / denom;
  • double d = ( num + 0.0 ) / denom;
  • double d = num; d /= denom;

but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );


Now if you are asking- Which one is better? explicit? or implicit?

Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.

Also, an extra operation will definitely not make your code more efficient. Right?

DateTime.ToString() format that can be used in a filename or extension?

Personally I like it this way:

DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")

Because it distinguishes between the date and the time.

Force IE8 Into IE7 Compatiblity Mode

one more if you want to switch IE 8 page render in IE 8 standard mode

<meta http-equiv="X-UA-Compatible" content="IE=100" /> <!-- IE8 mode -->

How do you display a Toast from a background thread on Android?

I encountered the same problem:

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.languoguang.welcomeapp, PID: 4724
              java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
                  at android.widget.Toast$TN.<init>(Toast.java:393)
                  at android.widget.Toast.<init>(Toast.java:117)
                  at android.widget.Toast.makeText(Toast.java:280)
                  at android.widget.Toast.makeText(Toast.java:270)
                  at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
                  at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4724 SIG: 9
Application terminated.

Before: onCreate function

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});
thread.start();

After: onCreate function

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});

it worked.

Programmatically trigger "select file" dialog box

<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
     <input id="myInput" type="file" />
</form>
<script>
  const uploadButton = document.getElementById('uploadButton');
  const myInput = document.getElementById('myInput');

  uploadButton.addEventListener('click', () => {
    myInput.click();
  });
</script>

How to convert xml into array in php?

See https://github.com/gaarf/XML-string-to-PHP-array/blob/master/xmlstr_to_array.php

<?php
/**
  * convert xml string to php array - useful to get a serializable value
  *
  * @param string $xmlstr
  * @return array
  *
  * @author Adrien aka Gaarf & contributors
  * @see http://gaarf.info/2009/08/13/xml-string-to-php-array/
*/
function xmlstr_to_array($xmlstr) {
  $doc = new DOMDocument();
  $doc->loadXML($xmlstr);
  $root = $doc->documentElement;
  $output = domnode_to_array($root);
  $output['@root'] = $root->tagName;
  return $output;
}
function domnode_to_array($node) {
  $output = array();
  switch ($node->nodeType) {
    case XML_CDATA_SECTION_NODE:
    case XML_TEXT_NODE:
      $output = trim($node->textContent);
    break;
    case XML_ELEMENT_NODE:
      for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
        $child = $node->childNodes->item($i);
        $v = domnode_to_array($child);
        if(isset($child->tagName)) {
          $t = $child->tagName;
          if(!isset($output[$t])) {
            $output[$t] = array();
          }
          $output[$t][] = $v;
        }
        elseif($v || $v === '0') {
          $output = (string) $v;
        }
      }
      if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
        $output = array('@content'=>$output); //Change output into an array.
      }
      if(is_array($output)) {
        if($node->attributes->length) {
          $a = array();
          foreach($node->attributes as $attrName => $attrNode) {
            $a[$attrName] = (string) $attrNode->value;
          }
          $output['@attributes'] = $a;
        }
        foreach ($output as $t => $v) {
          if(is_array($v) && count($v)==1 && $t!='@attributes') {
            $output[$t] = $v[0];
          }
        }
      }
    break;
  }
  return $output;
}

Simplest way to detect a mobile device in PHP

function isMobileDev(){
    if(isset($_SERVER['HTTP_USER_AGENT']) and !empty($_SERVER['HTTP_USER_AGENT'])){
       $user_ag = $_SERVER['HTTP_USER_AGENT'];
       if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
          return true;
       };
    };
    return false;
}

How to increase an array's length

You can make use of ArrayList. Array has the fixed number of size.

This Example here can help you. The example is pretty easy with its output.

Output:
2 5 1 23 14 
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29

How to hide Bootstrap modal with javascript?

I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:

$("a.close").on("click", function(e){
  $("#modal").modal("hide");
  e.stopPropagation();
});

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

If this happens to you with an OpenJDK install on Mac OS X (as opposed to Linux), and you do have the official Mac OS X Java (i.e. latest Java 6) installed through Software Update, you can just do this:

cd $OPENJDK_HOME/Contents/Home/jre/lib/security
ln -s /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts
ln -s /System/Library/Java/Support/Deploy.bundle/Contents/Home/lib/security/blacklist 
ln -s /System/Library/Java/Support/Deploy.bundle/Contents/Home/lib/security/trusted.libraries 

where $OPENJDK_HOME is the root directory of your OpenJDK install, typically OPENJDK_HOME=/Library/Java/JavaVirtualMachines/1.7.0u.jdk. This is identical to how official Java installs on Mac OS X acquire these files - they also just symlink them from those system bundles. Works for Lion, not sure for earlier versions of the OS.

Append to the end of a Char array in C++

If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.

#include <cstring>
#include <iostream>

int main()
{
    char array1[] ="The dog jumps ";
    char array2[] = "over the log";
    char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
    std::strcpy(newArray,array1);
    std::strcat(newArray,array2);
    std::cout << newArray << std::endl;
    delete [] newArray;
    return 0;
}

This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.

Edit, a safe version with the "enough buffer space" assumption:

#include <cstring>
#include <iostream>

int main()
{
    const unsigned BUFFER_SIZE = 50;
    char array1[BUFFER_SIZE];
    std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
    char array2[] = "over the log";
    std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
    std::cout << array1 << std::endl;
    return 0;
}

jQuery DataTables: control table width

You have to leave at least one field without fixed field, for example:

$('.data-table').dataTable ({

 "bAutoWidth": false,
 "aoColumns" : [
    null,
    null,
    null,                    
    null,
    {"sWidth": "20px"},
    { "sWidth": "20px"}]
});

You can change all, but leave only one as null, so it can stretch. If you put widths on ALL it will not work. Hope I helped somebody today!

Increasing the Command Timeout for SQL command

Setting command timeout to 2 minutes.

 scGetruntotals.CommandTimeout = 120;

but you can optimize your stored Procedures to decrease that time! like

  • removing courser or while and etc
  • using paging
  • using #tempTable and @variableTable
  • optimizing joined tables

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

How can I send large messages with Kafka (over 15MB)?

The idea is to have equal size of message being sent from Kafka Producer to Kafka Broker and then received by Kafka Consumer i.e.

Kafka producer --> Kafka Broker --> Kafka Consumer

Suppose if the requirement is to send 15MB of message, then the Producer, the Broker and the Consumer, all three, needs to be in sync.

Kafka Producer sends 15 MB --> Kafka Broker Allows/Stores 15 MB --> Kafka Consumer receives 15 MB

The setting therefore should be:

a) on Broker:

message.max.bytes=15728640 
replica.fetch.max.bytes=15728640

b) on Consumer:

fetch.message.max.bytes=15728640

jQuery Scroll To bottom of the page

You can just animate to scroll down the page by animating the scrollTop property, no plugin required, like this:

$(window).load(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, 1000);
});

Note the use of window.onload (when images are loaded...which occupy height) rather than document.ready.

To be technically correct, you need to subtract the window's height, but the above works:

$("html, body").animate({ scrollTop: $(document).height()-$(window).height() });

To scroll to a particular ID, use its .scrollTop(), like this:

$("html, body").animate({ scrollTop: $("#myID").scrollTop() }, 1000);

jQuery delete all table rows except first


$("#p-items").find( 'tr.row-items' ).remove();

Node.js: Python not found exception due to node-sass and node-gyp

so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:

  1. delete node_modulesfolder
  2. running npm install --global windows-build-tools
  3. reinstalling node modules or node-sass with npm install

How to link to part of the same document in Markdown?

There is no such directive in the Markdown spec. Sorry.

How to output (to a log) a multi-level array in a format that is human-readable?

Syntax

print_r(variable, return);

variable Required. Specifies the variable to return information about

return Optional. When set to true, this function will return the information (not print it). Default is false

Example

error_log( print_r(<array Variable>, TRUE) );

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

Using a PHP variable in a text input value = statement

Try something like this:

<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />

That is, the same as what thirtydot suggested, except preventing XSS attacks as well.

You could also use the <?= syntax (see the note), although that might not work on all servers. (It's enabled by a configuration option.)

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I had the same error message, my mistake was that I had a semicolon at the end of COMMIT TRANSACTION line

PHP 7 simpleXML

For all those using Ubuntu with ppa:ondrej/php PPA this will fix the problem:

apt install php7.0-mbstring php7.0-zip php7.0-xml

(see https://launchpad.net/~ondrej/+archive/ubuntu/php)

Thanks @Alexandre Barbosa for pointing this out!

EDIT 20160423:

One-liner to fix this issue:

sudo add-apt-repository -y ppa:ondrej/php && sudo apt update && sudo apt install -y php7.0-mbstring php7.0-zip php7.0-xml

(this will add the ppa noted above and will also make sure you always have the latest php. We use Ondrej's PHP ppa for almost two years now and it's working like charm)

Deadly CORS when http://localhost is the origin

The real problem is that if we set -Allow- for all request (OPTIONS & POST), Chrome will cancel it. The following code works for me with POST to LocalHost with Chrome

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
} 
?>

Get GMT Time in Java

From my experience, the bundled Calendar and Date classes in Java can yield undersired effect. If you wouldn't mind upgrading to Java 8, then consider using ZonedDateTime

like so:

ZonedDateTime currentDate = ZonedDateTime.now( ZoneOffset.UTC );

JAX-WS client : what's the correct path to access the local WSDL?

The best option is to use jax-ws-catalog.xml

When you compile the local WSDL file , override the WSDL location and set it to something like

http://localhost/wsdl/SOAService.wsdl

Don't worry this is only a URI and not a URL , meaning you don't have to have the WSDL available at that address.
You can do this by passing the wsdllocation option to the wsdl to java compiler.

Doing so will change your proxy code from

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "file:/C:/local/path/to/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'file:/C:/local/path/to/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

to

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "http://localhost/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'http://localhost/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

Notice file:// changed to http:// in the URL constructor.

Now comes in jax-ws-catalog.xml. Without jax-ws-catalog.xml jax-ws will indeed try to load the WSDL from the location

http://localhost/wsdl/SOAService.wsdl
and fail, as no such WSDL will be available.

But with jax-ws-catalog.xml you can redirect jax-ws to a locally packaged WSDL whenever it tries to access the WSDL @

http://localhost/wsdl/SOAService.wsdl
.

Here's jax-ws-catalog.xml

<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
        <system systemId="http://localhost/wsdl/SOAService.wsdl"
                uri="wsdl/SOAService.wsdl"/>
    </catalog>

What you are doing is telling jax-ws that when ever it needs to load WSDL from

http://localhost/wsdl/SOAService.wsdl
, it should load it from local path wsdl/SOAService.wsdl.

Now where should you put wsdl/SOAService.wsdl and jax-ws-catalog.xml ? That's the million dollar question isn't it ?
It should be in the META-INF directory of your application jar.

so something like this

ABCD.jar  
|__ META-INF    
    |__ jax-ws-catalog.xml  
    |__ wsdl  
        |__ SOAService.wsdl  

This way you don't even have to override the URL in your client that access the proxy. The WSDL is picked up from within your JAR, and you avoid having to have hard-coded filesystem paths in your code.

More info on jax-ws-catalog.xml http://jax-ws.java.net/nonav/2.1.2m1/docs/catalog-support.html

Hope that helps

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Amazon Linux AMI

Permanent solution for ohmyzsh:

$ vim ~/.zshrc

Write there below:

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

Update changes in current shell by: $ source ~/.zshrc

How do I find out what License has been applied to my SQL Server installation?

SELECT SERVERPROPERTY('LicenseType') as Licensetype, 
       SERVERPROPERTY('NumLicenses') as LicenseNumber,
       SERVERPROPERTY('productversion') as Productverion, 
       SERVERPROPERTY ('productlevel')as ProductLevel, 
       SERVERPROPERTY ('edition') as SQLEdition,@@VERSION as SQLversion

I had installed evaluation edition.Refer screenshot enter image description here

dotnet ef not found in .NET Core 3

if your using snap package dotnet-sdk on linux this can resolve by updating your ~.bashrc / etc. as follows:

#!/bin/bash
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"

how to use math.pi in java

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^

How can I stop the browser back button using JavaScript?

Some of the solutions here will not prevent a back event from occurring - they let a back event happen (and data held about the page in the browsers memory is lost) and then they play a forward event to try and hide the fact that a back event just happened. Which is unsuccessful if the page held transient state.

I wrote this solution for React (when react router is not being used), which is based on vrfvr's answer.

It will truly stop the back button from doing anything unless the user confirms a popup:

  const onHashChange = useCallback(() => {
    const confirm = window.confirm(
      'Warning - going back will cause you to loose unsaved data. Really go back?',
    );
    window.removeEventListener('hashchange', onHashChange);
    if (confirm) {
      setTimeout(() => {
        window.history.go(-1);
      }, 1);
    } else {
      window.location.hash = 'no-back';
      setTimeout(() => {
        window.addEventListener('hashchange', onHashChange);
      }, 1);
    }
  }, []);

  useEffect(() => {
    window.location.hash = 'no-back';
    setTimeout(() => {
      window.addEventListener('hashchange', onHashChange);
    }, 1);
    return () => {
      window.removeEventListener('hashchange', onHashChange);
    };
  }, []);

What is the shortcut to Auto import all in Android Studio?

You can make short cut key for missing import in android studio which you like

  1. Click on file Menu
  2. Click on Settting
  3. click on key map
  4. Search for "auto-import"
  5. double click on auto import and select add keyboard short cut key
  6. that's all

enter image description here

enter image description here

enter image description here

Note: You can import single missing import using alt+enter which shown in pop up

enter image description here

Copy Paste Values only( xlPasteValues )

Personally, I would shorten it a touch too if all you need is the columns:

For i = LBound(arr1) To UBound(arr1)
    Sheets("SheetA").Columns(arr1(i)).Copy
    Sheets("SheetB").Columns(arr2(i)).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
Next

as from this code snippet, there isnt much point in lastrow or firstrowDB

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

Spring @Transactional - isolation, propagation

Isolation level defines how the changes made to some data repository by one transaction affect other simultaneous concurrent transactions, and also how and when that changed data becomes available to other transactions. When we define a transaction using the Spring framework we are also able to configure in which isolation level that same transaction will be executed.

@Transactional(isolation=Isolation.READ_COMMITTED)
public void someTransactionalMethod(Object obj) {

}

READ_UNCOMMITTED isolation level states that a transaction may read data that is still uncommitted by other transactions.

READ_COMMITTED isolation level states that a transaction can't read data that is not yet committed by other transactions.

REPEATABLE_READ isolation level states that if a transaction reads one record from the database multiple times the result of all those reading operations must always be the same.

SERIALIZABLE isolation level is the most restrictive of all isolation levels. Transactions are executed with locking at all levels (read, range and write locking) so they appear as if they were executed in a serialized way.

Propagation is the ability to decide how the business methods should be encapsulated in both logical or physical transactions.

Spring REQUIRED behavior means that the same transaction will be used if there is an already opened transaction in the current bean method execution context.

REQUIRES_NEW behavior means that a new physical transaction will always be created by the container.

The NESTED behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions.

The MANDATORY behavior states that an existing opened transaction must already exist. If not an exception will be thrown by the container.

The NEVER behavior states that an existing opened transaction must not already exist. If a transaction exists an exception will be thrown by the container.

The NOT_SUPPORTED behavior will execute outside of the scope of any transaction. If an opened transaction already exists it will be paused.

The SUPPORTS behavior will execute in the scope of a transaction if an opened transaction already exists. If there isn't an already opened transaction the method will execute anyway but in a non-transactional way.

Check if my SSL Certificate is SHA1 or SHA2

You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Automatically pass $event with ng-click?

I wouldn't recommend doing this, but you can override the ngClick directive to do what you are looking for. That's not saying, you should.

With the original implementation in mind:

compile: function($element, attr) {
  var fn = $parse(attr[directiveName]);
  return function(scope, element, attr) {
    element.on(lowercase(name), function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  };
}

We can do this to override it:

// Go into your config block and inject $provide.
app.config(function ($provide) {

  // Decorate the ngClick directive.
  $provide.decorator('ngClickDirective', function ($delegate) {

    // Grab the actual directive from the returned $delegate array.
    var directive = $delegate[0];

    // Stow away the original compile function of the ngClick directive.
    var origCompile = directive.compile;

    // Overwrite the original compile function.
    directive.compile = function (el, attrs) {

      // Apply the original compile function. 
      origCompile.apply(this, arguments);

      // Return a new link function with our custom behaviour.
      return function (scope, el, attrs) {

        // Get the name of the passed in function. 
        var fn = attrs.ngClick;

        el.on('click', function (event) {
          scope.$apply(function () {

            // If no property on scope matches the passed in fn, return. 
            if (!scope[fn]) {
              return;
            }

            // Throw an error if we misused the new ngClick directive.
            if (typeof scope[fn] !== 'function') {
              throw new Error('Property ' + fn + ' is not a function on ' + scope);
            }

            // Call the passed in function with the event.
            scope[fn].call(null, event);

          });
        });          
      };
    };    

    return $delegate;
  });
});

Then you'd pass in your functions like this:

<div ng-click="func"></div>

as opposed to:

<div ng-click="func()"></div>

jsBin: http://jsbin.com/piwafeke/3/edit

Like I said, I would not recommend doing this but it's a proof of concept showing you that, yes - you can in fact overwrite/extend/augment the builtin angular behaviour to fit your needs. Without having to dig all that deep into the original implementation.

Do please use it with care, if you were to decide on going down this path (it's a lot of fun though).

Rails: Check output of path helper from console

Remember if your route is name-spaced, Like:

product GET  /products/:id(.:format)  spree/products#show

Then try :

helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)

output

Spree::Product Load (0.4ms)  SELECT  "spree_products".* FROM "spree_products"  WHERE "spree_products"."deleted_at" IS NULL  ORDER BY "spree_products"."id" ASC LIMIT 1
=> "<a data-method=\"get\" href=\"/products/this-is-the-title\">test</a>" 

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

How do I stop a program when an exception is raised in Python?

import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.

How to use foreach with a hash reference?

In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference

use v5.13.7;

foreach my $key (keys $ad_grp_ref) {
    ...
}

How to get a variable name as a string in PHP?

You could use compact() to achieve this.

$FooBar = "a string";

$newArray = compact('FooBar');

This would create an associative array with the variable name as the key. You could then loop through the array using the key name where you needed it.

foreach($newarray as $key => $value) {
    echo $key;
}

Action bar navigation modes are deprecated in Android L

I think a suitable replacement for when you have three to five screens of equal importance is the BottomNavigationActivity,this can be used to switch fragments.

You will notice a wizard exists for this in Android Studio, take care however as Android Studio has a tendency to produce overly complex boiler plate code.

A tutorial can be found here: https://android.jlelse.eu/ultimate-guide-to-bottom-navigation-on-android-75e4efb8105f

Another quality tutorial can be found at Android Hive here: https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/

How to Programmatically Add Views to Views

The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.

All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild() method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].

Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:

Step 1:

In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".

Step 2 Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :

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

</TextView>

BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.

android:layout_width="wrap_content"
android:layout_height="wrap_content"

If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.

Step 3

In your onCreate method, do this :

FrameLayout frameLayout = findViewById(R.id.container);
                TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
                frameLayout.addView(textView);

(Note that setting last parameter of findViewById to null and adding view by calling addView() on container view (frameLayout) is same as simply attaching the inflated view by passing true in 3rd parameter of findViewById(). For more, see this.)

Search in lists of lists by given index

the above all look good

but do you want to keep the result?

if so...

you can use the following

result = [element for element in data if element[1] == search]

then a simple

len(result)

lets you know if anything was found (and now you can do stuff with the results)

of course this does not handle elements which are length less than one (which you should be checking unless you know they always are greater than length 1, and in that case should you be using a tuple? (tuples are immutable))

if you know all items are a set length you can also do:

any(second == search for _, second in data)

or for len(data[0]) == 4:

any(second == search for _, second, _, _ in data)

...and I would recommend using

for element in data:
   ...

instead of

for i in range(len(data)):
   ...

(for future uses, unless you want to save or use 'i', and just so you know the '0' is not required, you only need use the full syntax if you are starting at a non zero value)

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

How do I get the number of days between two dates in JavaScript?

Using moment will be much easier in this case, You could try this:

    let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');

It will give you integer value like 1,2,5,0etc so you can easily use condition check like:

if(days < 1) {

Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:

let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);

Let me know if you have any further query

Iterate over values of object

In the sense I think you intended, in ES5 or ES2015, no, not without some work on your part.

In ES2016, probably with object.values.

Mind you Arrays in JavaScript are effectively a map from an integer to a value, and the values in JavaScript arrays can be enumerated directly.

['foo', 'bar'].forEach(v => console.log(v)); // foo bar

Also, in ES2015, you can make an object iterable by placing a function on a property with the name of Symbol.iterator:

var obj = { 
    foo: '1', 
    bar: '2',
    bam: '3',
    bat: '4',
};

obj[Symbol.iterator] = iter.bind(null, obj);

function* iter(o) {
    var keys = Object.keys(o);
    for (var i=0; i<keys.length; i++) {
        yield o[keys[i]];
    }
}

for(var v of obj) { console.log(v); } // '1', '2', '3', '4'

Also, per other answers, there are other built-ins that provide the functionality you want, like Map (but not WeakMap because it is not iterable) and Set for example (but these are not present in all browsers yet).

Get The Current Domain Name With Javascript (Not the path, etc.)

Let's suppose you have this url path:

http://localhost:4200/landing?query=1#2

So, you can serve yourself by the location values, as follow:

window.location.hash: "#2"
?
window.location.host: "localhost:4200"
?
window.location.hostname: "localhost"
?
window.location.href: "http://localhost:4200/landing?query=1#2"
?
window.location.origin: "http://localhost:4200"
?
window.location.pathname: "/landing"
?
window.location.port: "4200"
?
window.location.protocol: "http:"

window.location.search: "?query=1"

Now we can conclude you're looking for:

window.location.hostname

Split string into tokens and save them in an array

You can use strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

while(array[i]!=NULL)
{
   array[++i] = strtok(NULL,"/");
}

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

Delete specific values from column with where condition?

Try this SQL statement:

update Table set Column =( Column - your val )

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

Where is Android Studio layout preview?

I am using Android studio 3.3 and this method worked for me: open settings from file/settings from the left panel select Editor then layout Editor then from the right panel uncheck third option which is "Hide preview window when editing non-layout files" then hit apply then ok. then go to view/tool windows/preview is enable now in the design tab of layout XD. Do not forget up vote and marking this answer as the right answer. Happy coding. enter image description here

Batch files : How to leave the console window open

I just written last line as Pause it worked fine with both .bat and .cmd. It will display message also as 'Press any key to continue'.

How to determine the current iPhone/device model?

Here an modification without force unwrap and Swift 3.0:

import Foundation
import UIKit


public enum Model : String {
    case simulator = "simulator/sandbox",
    iPod1          = "iPod 1",
    iPod2          = "iPod 2",
    iPod3          = "iPod 3",
    iPod4          = "iPod 4",
    iPod5          = "iPod 5",
    iPad2          = "iPad 2",
    iPad3          = "iPad 3",
    iPad4          = "iPad 4",
    iPhone4        = "iPhone 4",
    iPhone4S       = "iPhone 4S",
    iPhone5        = "iPhone 5",
    iPhone5S       = "iPhone 5S",
    iPhone5C       = "iPhone 5C",
    iPadMini1      = "iPad Mini 1",
    iPadMini2      = "iPad Mini 2",
    iPadMini3      = "iPad Mini 3",
    iPadAir1       = "iPad Air 1",
    iPadAir2       = "iPad Air 2",
    iPhone6        = "iPhone 6",
    iPhone6plus    = "iPhone 6 Plus",
    iPhone6S       = "iPhone 6S",
    iPhone6Splus   = "iPhone 6S Plus",
    iPhoneSE       = "iPhone SE",
    iPhone7        = "iPhone 7",
    iPhone7plus    = "iPhone 7 Plus",
    unrecognized   = "?unrecognized?"
}

public extension UIDevice {
    public var type: Model {
        var systemInfo = utsname()
        uname(&systemInfo)
        let modelCode = withUnsafePointer(to: &systemInfo.machine) {
            $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                ptr in String.init(validatingUTF8: ptr)

            }
        }
        var modelMap : [ String : Model ] = [
            "i386"      : .simulator,
            "x86_64"    : .simulator,
            "iPod1,1"   : .iPod1,
            "iPod2,1"   : .iPod2,
            "iPod3,1"   : .iPod3,
            "iPod4,1"   : .iPod4,
            "iPod5,1"   : .iPod5,
            "iPad2,1"   : .iPad2,
            "iPad2,2"   : .iPad2,
            "iPad2,3"   : .iPad2,
            "iPad2,4"   : .iPad2,
            "iPad2,5"   : .iPadMini1,
            "iPad2,6"   : .iPadMini1,
            "iPad2,7"   : .iPadMini1,
            "iPhone3,1" : .iPhone4,
            "iPhone3,2" : .iPhone4,
            "iPhone3,3" : .iPhone4,
            "iPhone4,1" : .iPhone4S,
            "iPhone5,1" : .iPhone5,
            "iPhone5,2" : .iPhone5,
            "iPhone5,3" : .iPhone5C,
            "iPhone5,4" : .iPhone5C,
            "iPad3,1"   : .iPad3,
            "iPad3,2"   : .iPad3,
            "iPad3,3"   : .iPad3,
            "iPad3,4"   : .iPad4,
            "iPad3,5"   : .iPad4,
            "iPad3,6"   : .iPad4,
            "iPhone6,1" : .iPhone5S,
            "iPhone6,2" : .iPhone5S,
            "iPad4,1"   : .iPadAir1,
            "iPad4,2"   : .iPadAir2,
            "iPad4,4"   : .iPadMini2,
            "iPad4,5"   : .iPadMini2,
            "iPad4,6"   : .iPadMini2,
            "iPad4,7"   : .iPadMini3,
            "iPad4,8"   : .iPadMini3,
            "iPad4,9"   : .iPadMini3,
            "iPhone7,1" : .iPhone6plus,
            "iPhone7,2" : .iPhone6,
            "iPhone8,1" : .iPhone6S,
            "iPhone8,2" : .iPhone6Splus,
            "iPhone8,4" : .iPhoneSE,
            "iPhone9,1" : .iPhone7,
            "iPhone9,2" : .iPhone7plus,
            "iPhone9,3" : .iPhone7,
            "iPhone9,4" : .iPhone7plus,
            ]

        guard let safeModelCode = modelCode else {
            return Model.unrecognized
        }

        guard let modelString = String.init(validatingUTF8: safeModelCode) else {
            return Model.unrecognized
        }

        guard let model = modelMap[modelString] else {
            return Model.unrecognized
        }

        return model
    }
}

Get all table names of a particular database by SQL query?

In order if someone would like to list all tables within specific database without using the "use" keyword:

SELECT TABLE_NAME FROM databasename.INFORMATION_SCHEMA.TABLES