Programs & Examples On #File inclusion

What does the ELIFECYCLE Node.js error mean?

Likewise, I saw this error as a result of too little RAM. I cranked up the RAM on the VM and the error disappeared.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I had a similar issue with pods. Basically trying to run my UI tests, Xcode complained about missing pods. Solution to this was much simpler than any described above:

  1. go to project file (main not a target)
  2. click on the "Info" tab (most left)
  3. set proper pod configuration for UI tests target ("Configurations" section right under "Deployment Target")

Working!

I found it in a thread: https://github.com/CocoaPods/CocoaPods/issues/2695

Sounds a bit like a bug for cocoa pods but I can see reasons why it might be tricky case.

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

Using Abizern code for swift 2.2

let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)

How do I delete an item or object from an array using ng-click?

In case you're inside an ng-repeat

you could use a one liner option

    <div ng-repeat="key in keywords"> 
        <button ng-click="keywords.splice($index, 1)">

            {{key.name}}
        </button>
    </div>

$index is used by angular to show current index of the array inside ng-repeat

Maven – Always download sources and javadocs

I am using Maven 3.3.3 and cannot get the default profile to work in a user or global settings.xml file.

As a workaround, you may also add an additional build plugin to your pom.xml file.

<properties>
    <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
</properties>
<build>
    <plugins>
        <!-- Download Java source JARs. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven-dependency-plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>sources</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at the DateDiff() function.

-- Syntax
-- DATEDIFF ( datepart , startdate , enddate )

-- Example usage
SELECT DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDiff
SELECT DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDiff
SELECT DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDiff
SELECT DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDiff
SELECT DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDiff
...

You can see it in action / play with it here

Python Inverse of a Matrix

Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.

See Don't invert that matrix.

How to empty the content of a div

In jQuery it would be as simple as $('#yourDivID').empty()

See the documentation.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Get index of current item in a PowerShell loop

For PowerShell 3.0 and later, there is one built in :)

foreach ($item in $array) {
    $array.IndexOf($item)
}

Accessing elements by type in javascript

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type.toLowerCase() == 'text') {
        alert(inputs[i].value);
    }
}

In jQuery, you would just do:

// select all inputs of type 'text' on the page
$("input:text")

// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();

How to get city name from latitude and longitude coordinates in Google Maps?

Please refer below code

 Geocoder geocoder = new Geocoder(this, Locale.getDefault());
     List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
     String cityName = addresses.get(0).getAddressLine(0);
     String stateName = addresses.get(0).getAddressLine(1);
     String countryName = addresses.get(0).getAddressLine(2);

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

How do I compare two strings in Perl?

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:

Quote:

JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.

Another quote: for the code

var a
a
=
3 console.log(a)

JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;

and:

two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements

... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.

... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:

x 
++ 
y

It is parsed as x; ++y;, not as x++; y

So I think to simplify it, that means:

In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return, break, continue, and (2) if it sees ++ or -- on a new line, then it will add the ; at the end of the previous line.

The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.

With the above said, that means for return with a line break, the JavaScript interpreter will insert a ;

(quoted again: If a line break appears after any of these words [such as return] ... JavaScript will always interpret that line break as a semicolon)

and due to this reason, the classic example of

return
{ 
  foo: 1
}

will not work as expected, because the JavaScript interpreter will treat it as:

return;   // returning nothing
{
  foo: 1
}

There has to be no line-break immediately after the return:

return { 
  foo: 1
}

for it to work properly. And you may insert a ; yourself if you were to follow the rule of using a ; after any statement:

return { 
  foo: 1
};

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The argument order seems to matter... to exclude subdirectories, I used

robocopy \\source\folder C:\destinationfolder /XD * /MIR

...and that works for me (Windows 10 copy from Windows Server 2016)

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

How to pass command line arguments to a shell alias?

This works in ksh:

$ alias -x mkcd="mkdir \$dirname; cd \$dirname;"
$ alias mkcd
mkcd='mkdir $dirname; cd $dirname;'
$ dirname=aaa 
$ pwd
/tmp   
$ mkcd
$ pwd
/tmp/aaa

The "-x" option make the alias "exported" - alias is visible in subshells.

And be aware of fact that aliases defined in a script are not visible in that script (because aliases are expanded when a script is loaded, not when a line is interpreted). This can be solved with executing another script file in same shell (using dot).

JPA Query selecting only specific columns without using Criteria Query?

Projections can be used to select only specific properties(columns) of an entity object.

From the docs

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.

Define an interface with only the getters you want.

interface CustomObject {  
    String getA(); // Actual property name is A
    String getB(); // Actual property name is B 
}

Now return CustomObject from your repository like so :

public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
    CustomObject findByObjectName(String name);
}

How to change Git log date formats

I needed the same thing and found the following working for me:

git log -n1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'

The --date=format formats the date output where the --pretty tells what to print.

Conditional formatting, entire row based

=$G1="X"

would be the correct (and easiest) method. Just select the entire sheet first, as conditional formatting only works on selected cells. I just tried it and it works perfectly. You must start at G1 rather than G2 otherwise it will offset the conditional formatting by a row.

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

How to initialize static variables

In PHP 7.0.1, I was able to define this:

public static $kIdsByActions = array(
  MyClass1::kAction => 0,
  MyClass2::kAction => 1
);

And then use it like this:

MyClass::$kIdsByActions[$this->mAction];

Regular expression to find URLs within a string

I use this Regex:

/((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]/ig

It works fine for many URLs, like: http://google.com, https://dev-site.io:8080/home?val=1&count=100, www.regexr.com, localhost:8080/path, ...

How to check the version of GitLab?

You can access the version through a URL, the web GUI, and the ReST API.

Via a URL

An HTML page displaying the version can be displayed in a browser at https://your-gitlab-url/help. The version is displayed only if you are signed in.

Via a menu in the web GUI

If you do not care to type this URL, you can also access the same HTML page from a menu in the GitLab web GUI:

In GitLab 11 and later

  1. Log in to GitLab
  2. Click on the ? drop down menu in the upper right. Select Help.
  3. The GitLab version appears at the top of the page

In earlier versions, like GitLab 9

  1. Log in to GitLab
  2. Click on the three lines drop down menu in the upper left. Select Help.
  3. And then the version appears at the top of the page

Via the ReST API

Log in as any user, select the user icon in the upper right of the screen. Select Settings > Access Tokens. Create a personal access token and copy it to your clipboard.

In a Linux shell, use curl to access the GitLab version:

curl --header "PRIVATE-TOKEN: personal-access-token" your-gitlab-url/api/v4/version

MongoDB/Mongoose querying at a specific date?

You can use following approach for API method to get results from specific day:

# [HTTP GET]
getMeals: (req, res) ->
  options = {}
  # eg. api/v1/meals?date=Tue+Jan+13+2015+00%3A00%3A00+GMT%2B0100+(CET)
  if req.query.date?
    date = new Date req.query.date
    date.setHours 0, 0, 0, 0
    endDate = new Date date
    endDate.setHours 23, 59, 59, 59
    options.date =
      $lt: endDate
      $gte: date

  Meal.find options, (err, meals) ->
      if err or not meals
        handleError err, meals, res
      else
        res.json createJSON meals, null, 'meals'

Bootstrap 3 navbar active li not changing background-color

You need to add CSS to .active instead of .active a.

Fiddle: http://jsfiddle.net/T5X6h/2/

Something like this:

.navbar-default .navbar-nav > .active{
    color: #000;
    background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #000;
    background: #d65c14;
}

ContractFilter mismatch at the EndpointDispatcher exception

A "ContractFilter mismatch at the EndpointDispatcher" means the receiver could not process the message because it did not match any of the contracts the receiver has configured for the endpoint which received the message.

This can be because:

  • You have different contracts between client and sender.
  • You're using a different binding between client and sender.
  • The message security settings are not consistent between client and sender.

Have at look at the EndpointDispatcher class for more information on the subject.

So:

Make certain that your client and server contracts match.

  • If you've generated your client from a WSDL, is the WSDL up-to-date?
  • If you've made a recent change to the contract, have you deployed the right version of both client and server?
  • If you've hand-crafted your client contract classes, make sure the namespaces, elements names and action names match the ones expected by the server.

Check the bindings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the binding elements match.

Check the security settings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the security elements match.

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

Why do I get a SyntaxError for a Unicode escape in my file path?

I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.

In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

Contain form within a bootstrap popover?

Either replace double quotes around type="text" with single quotes, Like

"<form><input type='text'/></form>"

OR

replace double quotes wrapping data-content with singe quotes, Like

data-content='<form><input type="text"/></form>'

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

https://issuetracker.google.com/issues/72479188 indicates that plugins sometimes can introduce "compile" dependencies and that's what triggers the warning. Probably just easiest to star that issue and wait until they fix it to point out which plugins are causing the issue.

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

How to fix Git error: object file is empty?

This also happens to me almost regularly. Haven't made a protocol when this happens exactly, but I have a suspicion that it occurs whenever my virtual machine exists "unexpectedly". If I close the VM window (I am using Ubuntu 18.04) and start again, things always(?) work. But if the VM window is still open when my laptop is shut down (Windows host system), then I encounter this problem rather frequently.

As to all the answers given here:

  1. thank you - they are very useful; I usually save a local copy of my code, restore the repo from remote, and move the backup copy back into the local folder.

  2. as the underlying problem is not really a git issue, but rather a VM and/or Linux issue, I wonder if there shouldn't be a way to cure the reason rather the symptoms? Doesn't this kind of error indicate that some file system changes are not "applied" in any reasonable time, but only cached? (see for example https://unix.stackexchange.com/questions/464184/are-file-edits-in-linux-directly-saved-into-disk) -- to me it appears as if virtual Linux machines don't fsynch their stuff frequently enough. Whether this is an issue of Oracle's VirtualBox (which otherwise works very nicely) or of the guest file system, or of some settings, which we all overlook, is beyond my expertise. But I would be happy if someone could shed light on this.

Type or namespace name does not exist

I am referencing Microsoft.CommerceServer.Runtime.Orders and experienced this error. This project is old and has Target framework .NET 2.0. In output I had this error:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3268: The primary reference "Microsoft.CommerceServer.Runtime" could not be resolved because it has an indirect dependency on the framework assembly "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v2.0". To resolve this problem, either remove the reference "Microsoft.CommerceServer.Runtime" or retarget your application to a framework version which contains "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

I simply changed the target framework to .NET 4 and now it builds.

Simple way to measure cell execution time in ipython notebook

you may also want to look in to python's profiling magic command %prunwhich gives something like -

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

then

%prun sum_of_lists(1000000)

will return

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.

Microsoft Web API: How do you do a Server.MapPath?

Since Server.MapPath() does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:

string AppContext.BaseDirectory { get;}

You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \ and not / like they are in mvc.

Ex:

System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");

returns true- positing that this is a sound path in your example

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

Two options

for(int i = 0, n = s.length() ; i < n ; i++) { 
    char c = s.charAt(i); 
}

or

for(char c : s.toCharArray()) {
    // process c
}

The first is probably faster, then 2nd is probably more readable.

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Its a security issue, Gmail by default prevents access for your e-mail account from custom applications. You can set it up to accept the login from your application.

After Logging in to your e-mail, CLICK HERE

This will take you to the following page

Less Secure Apps Page

Java ArrayList for integers

You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be

ArrayList<Integer> list = new ArrayList<>();

or better

List<Integer> list = new ArrayList<>();

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

How to install SQL Server 2005 Express in Windows 8

Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.

After you run the install file SQLExpr.exe look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)

After that, find the file sqlncli_x64.msi in the setup folder, and run it.

Now you are ready the run the setup.exe file and install SQL server 2005 without errors

enter image description here

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

When you type mysql -u root -p , you're connecting to the mysql server over a local unix socket.

However the grant you gave, 'bill'@'%' only matches TCP/IP connections curiously enough.

If you want to grant access to the local unix socket, you need to grant privileges to 'bill'@'localhost' , which curiously enough is not the same as 'bill'@'127.0.0.1'

You could also connect using TCP/IP with the mysql command line client, as to match the privileges you already granted, e.g. run mysql -u root -p -h 192.168.1.123 or whichever local IP address your box have.

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I received this once by (accidentally) importing both the .h and .m files into the same class.

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_menu);

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

What CSS selector can be used to select the first div within another div

The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1> before the <div>s. What I would suggest is that you either add a class to the <div>, like <div class="first"> and then style it that way, or use jQuery if you really can't add a class:

$('#content > div:first')

How do you get the length of a list in the JSF expression language?

You can eventually extend the EL language by using the EL Functor, which will allow you to call any Java beans methods, even with parameters...

How to create Java gradle project

I just tried with with Eclipse Neon.1 and Gradle:

------------------------------------------------------------
Gradle 3.2.1
------------------------------------------------------------

Build time:   2016-11-22 15:19:54 UTC
Revision:     83b485b914fd4f335ad0e66af9d14aad458d2cc5

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_112 (Oracle Corporation 25.112-b15)
OS:           Windows 10 10.0 amd64

enter image description here

On windows 10 with Java Version:

C:\FDriveKambiz\repo\gradle-gen-project>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)

And it failed miserably as you can see in Eclipse. But sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project. That is not good enough. I am switching to Intellij for gradle projects:

enter image description here

Log all requests from the python-requests module

For those using python 3+

import requests
import logging
import http.client

http.client.HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

Bootstrap-select - how to fire event on change

Easiest implementation.

<script>
    $( ".selectpicker" ).change(function() {
        alert( "Handler for .change() called." );
    });
</script>

Anybody knows any knowledge base open source?

How about one of the many wikis?

Kenny: I've used FlexWiki & ScrewTurn (abandoned).

someone else with RepPower to edit my post added this.
Wikipedia is powered by MediaWiki.

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

java.math.BigInteger cannot be cast to java.lang.Integer

You can try this:

((BigDecimal) volume).intValue();

I use java.math.BigDecimal convert to int (primitive type).

It is worked for me.

How to bind a List to a ComboBox?

If you are using a ToolStripComboBox there is no DataSource exposed (.NET 4.0):

List<string> someList = new List<string>();
someList.Add("value");
someList.Add("value");
someList.Add("value");

toolStripComboBox1.Items.AddRange(someList.ToArray());

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

pip install access denied on Windows

  1. Open Command Prompt as Administrator.

  2. To Install any Python Package use this command including --user.

pip install --ignore-installed --upgrade --user <packagename>

How to get the GL library/headers?

In Visual Studio :

//OpenGL
#pragma comment(lib, "opengl32")
#pragma comment(lib, "glu32")
#include <gl/gl.h>
#include <gl/glu.h>

Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

UITextView that expands to text using auto layout

I've found it's not entirely uncommon in situations where you may still need isScrollEnabled set to true to allow a reasonable UI interaction. A simple case for this is when you want to allow an auto expanding text view but still limit it's maximum height to something reasonable in a UITableView.

Here's a subclass of UITextView I've come up with that allows auto expansion with auto layout but that you could still constrain to a maximum height and which will manage whether the view is scrollable depending on the height. By default the view will expand indefinitely if you have your constraints setup that way.

import UIKit

class FlexibleTextView: UITextView {
    // limit the height of expansion per intrinsicContentSize
    var maxHeight: CGFloat = 0.0
    private let placeholderTextView: UITextView = {
        let tv = UITextView()

        tv.translatesAutoresizingMaskIntoConstraints = false
        tv.backgroundColor = .clear
        tv.isScrollEnabled = false
        tv.textColor = .disabledTextColor
        tv.isUserInteractionEnabled = false
        return tv
    }()
    var placeholder: String? {
        get {
            return placeholderTextView.text
        }
        set {
            placeholderTextView.text = newValue
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        isScrollEnabled = false
        autoresizingMask = [.flexibleWidth, .flexibleHeight]
        NotificationCenter.default.addObserver(self, selector: #selector(UITextInputDelegate.textDidChange(_:)), name: Notification.Name.UITextViewTextDidChange, object: self)
        placeholderTextView.font = font
        addSubview(placeholderTextView)

        NSLayoutConstraint.activate([
            placeholderTextView.leadingAnchor.constraint(equalTo: leadingAnchor),
            placeholderTextView.trailingAnchor.constraint(equalTo: trailingAnchor),
            placeholderTextView.topAnchor.constraint(equalTo: topAnchor),
            placeholderTextView.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var text: String! {
        didSet {
            invalidateIntrinsicContentSize()
            placeholderTextView.isHidden = !text.isEmpty
        }
    }

    override var font: UIFont? {
        didSet {
            placeholderTextView.font = font
            invalidateIntrinsicContentSize()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            placeholderTextView.contentInset = contentInset
        }
    }

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize

        if size.height == UIViewNoIntrinsicMetric {
            // force layout
            layoutManager.glyphRange(for: textContainer)
            size.height = layoutManager.usedRect(for: textContainer).height + textContainerInset.top + textContainerInset.bottom
        }

        if maxHeight > 0.0 && size.height > maxHeight {
            size.height = maxHeight

            if !isScrollEnabled {
                isScrollEnabled = true
            }
        } else if isScrollEnabled {
            isScrollEnabled = false
        }

        return size
    }

    @objc private func textDidChange(_ note: Notification) {
        // needed incase isScrollEnabled is set to true which stops automatically calling invalidateIntrinsicContentSize()
        invalidateIntrinsicContentSize()
        placeholderTextView.isHidden = !text.isEmpty
    }
}

As a bonus there's support for including placeholder text similar to UILabel.

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

Selecting non-blank cells in Excel with VBA

I know I'm am very late on this, but here some usefull samples:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

 lngLast = cells(rows.count,3).end(xlUp).row

Spring Boot Configure and Use Two DataSources

I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.

The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.

Here is config for the first (Primary) database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstDbEntityManagerFactory",
    transactionManagerRef = "firstDbTransactionManager",
    basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.firstDb")
    fun firstDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Primary
    @Bean(name = ["firstDbEntityManagerFactory"])
    fun firstDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("firstDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(SomeEntity::class.java)
            .persistenceUnit("firstDb")
            // Following is the optional configuration for naming strategy
            .properties(
                singletonMap(
                    "hibernate.naming.physical-strategy",
                    "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
                )
            )
            .build()
    }

    @Primary
    @Bean(name = ["firstDbTransactionManager"])
    fun firstDbTransactionManager(
        @Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(firstDbEntityManagerFactory)
    }
}

And this is config for second database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "secondDbEntityManagerFactory",
    transactionManagerRef = "secondDbTransactionManager",
    basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.secondDb")
    fun secondDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean(name = ["secondDbEntityManagerFactory"])
    fun secondDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("secondDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(EntityFromSecondDb::class.java)
            .persistenceUnit("secondDb")
            .build()
    }

    @Bean(name = ["secondDbTransactionManager"])
    fun secondDbTransactionManager(
        @Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(secondDbEntityManagerFactory)
    }
}

The properties for datasources are like this:

spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=

spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=

Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.

p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.

How to read line by line or a whole text file at once?

Another method that has not been mentioned yet is std::vector.

std::vector<std::string> line;

while(file >> mystr)
{
   line.push_back(mystr);
}

Then you can simply iterate over the vector and modify/extract what you need/

How to avoid .pyc files?

You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.

I don't think there's a more elegant option. PEP 304 appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.

I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.

How to sort an array of objects in Java?

Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)

`int tallest; // the index of tallest book found thus far
 Book temp; // used in the swap
 for(int a = 0; a < booksArray.length - 1; a++) {
   tallest = a; // reset tallest to current index
   // start inner loop at next index
   for(int b = a + 1; b < booksArray.length; b++)
     // check if the book at this index is taller than the
     // tallest found thus far
     if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
       tallest = b;
   // once inner loop is complete, swap the tallest book found with
   // the one at the current index of the outer loop
   temp = booksArray[a];
   booksArray[a] = booksArray[tallest];
   booksArray[tallest] = temp;
 }`

When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!

String split on new line, tab and some number of spaces

>>> for line in s.splitlines():
...     line = line.strip()
...     if not line:continue
...     ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

Git refusing to merge unrelated histories on rebase

I ran this command and issue got resolved.

git pull origin branchName --allow-unrelated-histories

Check out this page for more info.

How to increment a datetime by one day?

You can also import timedelta so the code is cleaner.

from datetime import datetime, timedelta
date = datetime.now() + timedelta(seconds=[delta_value])

Then convert to date to string

date = date.strftime('%Y-%m-%d %H:%M:%S')

Python one liner is

date = (datetime.now() + timedelta(seconds=[delta_value])).strftime('%Y-%m-%d %H:%M:%S')

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

How to generate a random String in Java

Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";

for (int i=0; i<=top; i++) {
  data = (char)(ran.nextInt(25)+97);
  dat = data + dat;
}

System.out.println(dat);

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How does lock work exactly?

The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

Box-Shadow on the left side of the element only

box-shadow: inset 10px 0 0 0 red;

Swift: Reload a View Controller

If you need to update the canvas by redrawing views after some change, you should call setNeedsDisplay.

Thank you @Vincent from an earlier comment.enter image description here

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Passing multiple argument through CommandArgument of Button in Asp.net

Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.

How can I maintain fragment state when added to the back stack?

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
    {
        @Override
        public void onBackStackChanged()
        {
            if (getSupportFragmentManager().getBackStackEntryCount() == 0)
            {
                //setToolbarTitle("Main Activity");
            }
            else
            {
                Log.e("fragment_replace11111", "replace");
            }
        }
    });


YourActivity.java
@Override
public void onBackPressed()
{
 Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.Fragment_content);
  if (fragment instanceof YourFragmentName)
    {
        fragmentReplace(new HomeFragment(),"Home Fragment");
        txt_toolbar_title.setText("Your Fragment");
    }
  else{
     super.onBackPressed();
   }
 }


public void fragmentReplace(Fragment fragment, String fragment_name)
{
    try
    {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.Fragment_content, fragment, fragment_name);
        fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
        fragmentTransaction.addToBackStack(fragment_name);
        fragmentTransaction.commitAllowingStateLoss();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

Thymeleaf using path variables to th:href

The right way according to Thymeleaf documention for adding parameters is:

<a th:href="@{/category/edit/{id}(id=${category.idCategory})}">view</a>

Regexp Java for password validation

Password Requirement :

  • Password should be at least eight (8) characters in length where the system can support it.
  • Passwords must include characters from at least two (2) of these groupings: alpha, numeric, and special characters.

    ^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])|(?=.{8,})(?=.*\d)(?=.*[!@#$%^&])|(?=.{8,})(?=.*[a-zA-Z])(?=.*[!@#$%^&]).*$
    

I tested it and it works

how to implement login auth in node.js

I tried this answer and it didn't work for me. I am also a newbie on web development and took classes where i used mlab but i prefer parse which is why i had to look for the most suitable solution. Here is my own current solution using parse on expressJS.

1)Check if the user is authenticated: I have a middleware function named isLogginIn which I use on every route that needs the user to be authenticated:

 function isLoggedIn(req, res, next) {
 var currentUser = Parse.User.current();
 if (currentUser) {
     next()
 } else {
     res.send("you are not authorised");
 }
}

I use this function in my routes like this:

  app.get('/my_secret_page', isLoggedIn, function (req, res) 
  {
    res.send('if you are viewing this page it means you are logged in');
  });

2) The Login Route:

  // handling login logic
  app.post('/login', function(req, res) {
  Parse.User.enableUnsafeCurrentUser();
  Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
    res.redirect('/books');
  }, function(error) {
    res.render('login', { flash: error.message });
  });
});

3) The logout route:

 // logic route
  app.get("/logout", function(req, res){
   Parse.User.logOut().then(() => {
    var currentUser = Parse.User.current();  // this will now be null
    });
        res.redirect('/login');
   });

This worked very well for me and i made complete reference to the documentation here https://docs.parseplatform.org/js/guide/#users

Thanks to @alessioalex for his answer. I have only updated with the latest practices.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

Solving sslv3 alert handshake failure when trying to use a client certificate

The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.

Once changing this value to DEFAULT, run the following command:

/usr/bin/update-crypto-policies --set DEFAULT

Rerun the curl command and it should work.

Setting TIME_WAIT TCP

A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).

The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).

So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.

That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.

That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.

How do I print the type or class of a variable in Swift?

Many of the answers here do not work with the latest Swift (Xcode 7.1.1 at time of writing).

The current way of getting the information is to create a Mirror and interrogate that. For the classname it is as simple as:

let mirror = Mirror(reflecting: instanceToInspect)
let classname:String = mirror.description

Additional information about the object can also be retrieved from the Mirror. See http://swiftdoc.org/v2.1/type/Mirror/ for details.

How do I run a program with a different working directory from current, from Linux shell?

from the current directory provide the full path to the script directory to execute the command

/root/server/user/home/bin/script.sh

Convert timestamp to date in Oracle SQL

This may not be the correct way to do it. But I have solved the problem using substring function.

Select max(start_ts), min(start_ts)from db where SUBSTR(start_ts, 0,9) ='13-may-2016'

using this I was able to retrieve the max and min timestamp.

When using a Settings.settings file in .NET, where is the config actually stored?

I know it's already answered but couldn't you just synchronize the settings in the settings designer to move back to your default settings?

uncaught syntaxerror unexpected token U JSON

That error is normally seen when the value given to JSON.parse is actually undefined. So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

Download File Using Javascript/jQuery

Most Complete and Working (Tested) Code for Downloading Data For FireFox, Chrome and IE Code is Following. Assume that Data is in texarea field, that has id='textarea_area' and filename is name of file where data will be downloaded.

function download(filename) {
    if (typeof filename==='undefined') filename = ""; // default
    value = document.getElementById('textarea_area').value;

    filetype="text/*";
    extension=filename.substring(filename.lastIndexOf("."));
    for (var i = 0; i < extToMIME.length; i++) {
        if (extToMIME[i][0].localeCompare(extension)==0) {
            filetype=extToMIME[i][1];
            break;
        }
    }


    var pom = document.createElement('a');
    pom.setAttribute('href', 'data: '+filetype+';charset=utf-8,' + '\ufeff' + encodeURIComponent(value)); // Added BOM too
    pom.setAttribute('download', filename);


    if (document.createEvent) {
        if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { // IE
            blobObject = new Blob(['\ufeff'+value]);
            window.navigator.msSaveBlob(blobObject, filename);
        } else { // FF, Chrome
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
    } else if( document.createEventObject ) { // Have No Idea
        var evObj = document.createEventObject();
        pom.fireEvent( 'onclick' , evObj );
    } else { // For Any Case
        pom.click();
    }

}

and then just call

<a href="javascript:download();">Download</a>

For Download Initiating.

Array for setting correct MIME type for download dialog CAN BE following:

// ----------------------- Extensions to MIME --------- //

        // List of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
    var extToMIME = [
        [".323", "text/h323"],
        [".3g2", "video/3gpp2"],
        [".3gp", "video/3gpp"],
        [".3gp2", "video/3gpp2"],
        [".3gpp", "video/3gpp"],
        [".7z", "application/x-7z-compressed"],
        [".aa", "audio/audible"],
        [".AAC", "audio/aac"],
        [".aaf", "application/octet-stream"],
        [".aax", "audio/vnd.audible.aax"],
        [".ac3", "audio/ac3"],
        [".aca", "application/octet-stream"],
        [".accda", "application/msaccess.addin"],
        [".accdb", "application/msaccess"],
        [".accdc", "application/msaccess.cab"],
        [".accde", "application/msaccess"],
        [".accdr", "application/msaccess.runtime"],
        [".accdt", "application/msaccess"],
        [".accdw", "application/msaccess.webapplication"],
        [".accft", "application/msaccess.ftemplate"],
        [".acx", "application/internet-property-stream"],
        [".AddIn", "text/xml"],
        [".ade", "application/msaccess"],
        [".adobebridge", "application/x-bridge-url"],
        [".adp", "application/msaccess"],
        [".ADT", "audio/vnd.dlna.adts"],
        [".ADTS", "audio/aac"],
        [".afm", "application/octet-stream"],
        [".ai", "application/postscript"],
        [".aif", "audio/x-aiff"],
        [".aifc", "audio/aiff"],
        [".aiff", "audio/aiff"],
        [".air", "application/vnd.adobe.air-application-installer-package+zip"],
        [".amc", "application/x-mpeg"],
        [".application", "application/x-ms-application"],
        [".art", "image/x-jg"],
        [".asa", "application/xml"],
        [".asax", "application/xml"],
        [".ascx", "application/xml"],
        [".asd", "application/octet-stream"],
        [".asf", "video/x-ms-asf"],
        [".ashx", "application/xml"],
        [".asi", "application/octet-stream"],
        [".asm", "text/plain"],
        [".asmx", "application/xml"],
        [".aspx", "application/xml"],
        [".asr", "video/x-ms-asf"],
        [".asx", "video/x-ms-asf"],
        [".atom", "application/atom+xml"],
        [".au", "audio/basic"],
        [".avi", "video/x-msvideo"],
        [".axs", "application/olescript"],
        [".bas", "text/plain"],
        [".bcpio", "application/x-bcpio"],
        [".bin", "application/octet-stream"],
        [".bmp", "image/bmp"],
        [".c", "text/plain"],
        [".cab", "application/octet-stream"],
        [".caf", "audio/x-caf"],
        [".calx", "application/vnd.ms-office.calx"],
        [".cat", "application/vnd.ms-pki.seccat"],
        [".cc", "text/plain"],
        [".cd", "text/plain"],
        [".cdda", "audio/aiff"],
        [".cdf", "application/x-cdf"],
        [".cer", "application/x-x509-ca-cert"],
        [".chm", "application/octet-stream"],
        [".class", "application/x-java-applet"],
        [".clp", "application/x-msclip"],
        [".cmx", "image/x-cmx"],
        [".cnf", "text/plain"],
        [".cod", "image/cis-cod"],
        [".config", "application/xml"],
        [".contact", "text/x-ms-contact"],
        [".coverage", "application/xml"],
        [".cpio", "application/x-cpio"],
        [".cpp", "text/plain"],
        [".crd", "application/x-mscardfile"],
        [".crl", "application/pkix-crl"],
        [".crt", "application/x-x509-ca-cert"],
        [".cs", "text/plain"],
        [".csdproj", "text/plain"],
        [".csh", "application/x-csh"],
        [".csproj", "text/plain"],
        [".css", "text/css"],
        [".csv", "text/csv"],
        [".cur", "application/octet-stream"],
        [".cxx", "text/plain"],
        [".dat", "application/octet-stream"],
        [".datasource", "application/xml"],
        [".dbproj", "text/plain"],
        [".dcr", "application/x-director"],
        [".def", "text/plain"],
        [".deploy", "application/octet-stream"],
        [".der", "application/x-x509-ca-cert"],
        [".dgml", "application/xml"],
        [".dib", "image/bmp"],
        [".dif", "video/x-dv"],
        [".dir", "application/x-director"],
        [".disco", "text/xml"],
        [".dll", "application/x-msdownload"],
        [".dll.config", "text/xml"],
        [".dlm", "text/dlm"],
        [".doc", "application/msword"],
        [".docm", "application/vnd.ms-word.document.macroEnabled.12"],
        [".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
        [".dot", "application/msword"],
        [".dotm", "application/vnd.ms-word.template.macroEnabled.12"],
        [".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"],
        [".dsp", "application/octet-stream"],
        [".dsw", "text/plain"],
        [".dtd", "text/xml"],
        [".dtsConfig", "text/xml"],
        [".dv", "video/x-dv"],
        [".dvi", "application/x-dvi"],
        [".dwf", "drawing/x-dwf"],
        [".dwp", "application/octet-stream"],
        [".dxr", "application/x-director"],
        [".eml", "message/rfc822"],
        [".emz", "application/octet-stream"],
        [".eot", "application/octet-stream"],
        [".eps", "application/postscript"],
        [".etl", "application/etl"],
        [".etx", "text/x-setext"],
        [".evy", "application/envoy"],
        [".exe", "application/octet-stream"],
        [".exe.config", "text/xml"],
        [".fdf", "application/vnd.fdf"],
        [".fif", "application/fractals"],
        [".filters", "Application/xml"],
        [".fla", "application/octet-stream"],
        [".flr", "x-world/x-vrml"],
        [".flv", "video/x-flv"],
        [".fsscript", "application/fsharp-script"],
        [".fsx", "application/fsharp-script"],
        [".generictest", "application/xml"],
        [".gif", "image/gif"],
        [".group", "text/x-ms-group"],
        [".gsm", "audio/x-gsm"],
        [".gtar", "application/x-gtar"],
        [".gz", "application/x-gzip"],
        [".h", "text/plain"],
        [".hdf", "application/x-hdf"],
        [".hdml", "text/x-hdml"],
        [".hhc", "application/x-oleobject"],
        [".hhk", "application/octet-stream"],
        [".hhp", "application/octet-stream"],
        [".hlp", "application/winhlp"],
        [".hpp", "text/plain"],
        [".hqx", "application/mac-binhex40"],
        [".hta", "application/hta"],
        [".htc", "text/x-component"],
        [".htm", "text/html"],
        [".html", "text/html"],
        [".htt", "text/webviewhtml"],
        [".hxa", "application/xml"],
        [".hxc", "application/xml"],
        [".hxd", "application/octet-stream"],
        [".hxe", "application/xml"],
        [".hxf", "application/xml"],
        [".hxh", "application/octet-stream"],
        [".hxi", "application/octet-stream"],
        [".hxk", "application/xml"],
        [".hxq", "application/octet-stream"],
        [".hxr", "application/octet-stream"],
        [".hxs", "application/octet-stream"],
        [".hxt", "text/html"],
        [".hxv", "application/xml"],
        [".hxw", "application/octet-stream"],
        [".hxx", "text/plain"],
        [".i", "text/plain"],
        [".ico", "image/x-icon"],
        [".ics", "application/octet-stream"],
        [".idl", "text/plain"],
        [".ief", "image/ief"],
        [".iii", "application/x-iphone"],
        [".inc", "text/plain"],
        [".inf", "application/octet-stream"],
        [".inl", "text/plain"],
        [".ins", "application/x-internet-signup"],
        [".ipa", "application/x-itunes-ipa"],
        [".ipg", "application/x-itunes-ipg"],
        [".ipproj", "text/plain"],
        [".ipsw", "application/x-itunes-ipsw"],
        [".iqy", "text/x-ms-iqy"],
        [".isp", "application/x-internet-signup"],
        [".ite", "application/x-itunes-ite"],
        [".itlp", "application/x-itunes-itlp"],
        [".itms", "application/x-itunes-itms"],
        [".itpc", "application/x-itunes-itpc"],
        [".IVF", "video/x-ivf"],
        [".jar", "application/java-archive"],
        [".java", "application/octet-stream"],
        [".jck", "application/liquidmotion"],
        [".jcz", "application/liquidmotion"],
        [".jfif", "image/pjpeg"],
        [".jnlp", "application/x-java-jnlp-file"],
        [".jpb", "application/octet-stream"],
        [".jpe", "image/jpeg"],
        [".jpeg", "image/jpeg"],
        [".jpg", "image/jpeg"],
        [".js", "application/x-javascript"],
        [".json", "application/json"],
        [".jsx", "text/jscript"],
        [".jsxbin", "text/plain"],
        [".latex", "application/x-latex"],
        [".library-ms", "application/windows-library+xml"],
        [".lit", "application/x-ms-reader"],
        [".loadtest", "application/xml"],
        [".lpk", "application/octet-stream"],
        [".lsf", "video/x-la-asf"],
        [".lst", "text/plain"],
        [".lsx", "video/x-la-asf"],
        [".lzh", "application/octet-stream"],
        [".m13", "application/x-msmediaview"],
        [".m14", "application/x-msmediaview"],
        [".m1v", "video/mpeg"],
        [".m2t", "video/vnd.dlna.mpeg-tts"],
        [".m2ts", "video/vnd.dlna.mpeg-tts"],
        [".m2v", "video/mpeg"],
        [".m3u", "audio/x-mpegurl"],
        [".m3u8", "audio/x-mpegurl"],
        [".m4a", "audio/m4a"],
        [".m4b", "audio/m4b"],
        [".m4p", "audio/m4p"],
        [".m4r", "audio/x-m4r"],
        [".m4v", "video/x-m4v"],
        [".mac", "image/x-macpaint"],
        [".mak", "text/plain"],
        [".man", "application/x-troff-man"],
        [".manifest", "application/x-ms-manifest"],
        [".map", "text/plain"],
        [".master", "application/xml"],
        [".mda", "application/msaccess"],
        [".mdb", "application/x-msaccess"],
        [".mde", "application/msaccess"],
        [".mdp", "application/octet-stream"],
        [".me", "application/x-troff-me"],
        [".mfp", "application/x-shockwave-flash"],
        [".mht", "message/rfc822"],
        [".mhtml", "message/rfc822"],
        [".mid", "audio/mid"],
        [".midi", "audio/mid"],
        [".mix", "application/octet-stream"],
        [".mk", "text/plain"],
        [".mmf", "application/x-smaf"],
        [".mno", "text/xml"],
        [".mny", "application/x-msmoney"],
        [".mod", "video/mpeg"],
        [".mov", "video/quicktime"],
        [".movie", "video/x-sgi-movie"],
        [".mp2", "video/mpeg"],
        [".mp2v", "video/mpeg"],
        [".mp3", "audio/mpeg"],
        [".mp4", "video/mp4"],
        [".mp4v", "video/mp4"],
        [".mpa", "video/mpeg"],
        [".mpe", "video/mpeg"],
        [".mpeg", "video/mpeg"],
        [".mpf", "application/vnd.ms-mediapackage"],
        [".mpg", "video/mpeg"],
        [".mpp", "application/vnd.ms-project"],
        [".mpv2", "video/mpeg"],
        [".mqv", "video/quicktime"],
        [".ms", "application/x-troff-ms"],
        [".msi", "application/octet-stream"],
        [".mso", "application/octet-stream"],
        [".mts", "video/vnd.dlna.mpeg-tts"],
        [".mtx", "application/xml"],
        [".mvb", "application/x-msmediaview"],
        [".mvc", "application/x-miva-compiled"],
        [".mxp", "application/x-mmxp"],
        [".nc", "application/x-netcdf"],
        [".nsc", "video/x-ms-asf"],
        [".nws", "message/rfc822"],
        [".ocx", "application/octet-stream"],
        [".oda", "application/oda"],
        [".odc", "text/x-ms-odc"],
        [".odh", "text/plain"],
        [".odl", "text/plain"],
        [".odp", "application/vnd.oasis.opendocument.presentation"],
        [".ods", "application/oleobject"],
        [".odt", "application/vnd.oasis.opendocument.text"],
        [".one", "application/onenote"],
        [".onea", "application/onenote"],
        [".onepkg", "application/onenote"],
        [".onetmp", "application/onenote"],
        [".onetoc", "application/onenote"],
        [".onetoc2", "application/onenote"],
        [".orderedtest", "application/xml"],
        [".osdx", "application/opensearchdescription+xml"],
        [".p10", "application/pkcs10"],
        [".p12", "application/x-pkcs12"],
        [".p7b", "application/x-pkcs7-certificates"],
        [".p7c", "application/pkcs7-mime"],
        [".p7m", "application/pkcs7-mime"],
        [".p7r", "application/x-pkcs7-certreqresp"],
        [".p7s", "application/pkcs7-signature"],
        [".pbm", "image/x-portable-bitmap"],
        [".pcast", "application/x-podcast"],
        [".pct", "image/pict"],
        [".pcx", "application/octet-stream"],
        [".pcz", "application/octet-stream"],
        [".pdf", "application/pdf"],
        [".pfb", "application/octet-stream"],
        [".pfm", "application/octet-stream"],
        [".pfx", "application/x-pkcs12"],
        [".pgm", "image/x-portable-graymap"],
        [".pic", "image/pict"],
        [".pict", "image/pict"],
        [".pkgdef", "text/plain"],
        [".pkgundef", "text/plain"],
        [".pko", "application/vnd.ms-pki.pko"],
        [".pls", "audio/scpls"],
        [".pma", "application/x-perfmon"],
        [".pmc", "application/x-perfmon"],
        [".pml", "application/x-perfmon"],
        [".pmr", "application/x-perfmon"],
        [".pmw", "application/x-perfmon"],
        [".png", "image/png"],
        [".pnm", "image/x-portable-anymap"],
        [".pnt", "image/x-macpaint"],
        [".pntg", "image/x-macpaint"],
        [".pnz", "image/png"],
        [".pot", "application/vnd.ms-powerpoint"],
        [".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"],
        [".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"],
        [".ppa", "application/vnd.ms-powerpoint"],
        [".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"],
        [".ppm", "image/x-portable-pixmap"],
        [".pps", "application/vnd.ms-powerpoint"],
        [".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"],
        [".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"],
        [".ppt", "application/vnd.ms-powerpoint"],
        [".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"],
        [".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
        [".prf", "application/pics-rules"],
        [".prm", "application/octet-stream"],
        [".prx", "application/octet-stream"],
        [".ps", "application/postscript"],
        [".psc1", "application/PowerShell"],
        [".psd", "application/octet-stream"],
        [".psess", "application/xml"],
        [".psm", "application/octet-stream"],
        [".psp", "application/octet-stream"],
        [".pub", "application/x-mspublisher"],
        [".pwz", "application/vnd.ms-powerpoint"],
        [".qht", "text/x-html-insertion"],
        [".qhtm", "text/x-html-insertion"],
        [".qt", "video/quicktime"],
        [".qti", "image/x-quicktime"],
        [".qtif", "image/x-quicktime"],
        [".qtl", "application/x-quicktimeplayer"],
        [".qxd", "application/octet-stream"],
        [".ra", "audio/x-pn-realaudio"],
        [".ram", "audio/x-pn-realaudio"],
        [".rar", "application/octet-stream"],
        [".ras", "image/x-cmu-raster"],
        [".rat", "application/rat-file"],
        [".rc", "text/plain"],
        [".rc2", "text/plain"],
        [".rct", "text/plain"],
        [".rdlc", "application/xml"],
        [".resx", "application/xml"],
        [".rf", "image/vnd.rn-realflash"],
        [".rgb", "image/x-rgb"],
        [".rgs", "text/plain"],
        [".rm", "application/vnd.rn-realmedia"],
        [".rmi", "audio/mid"],
        [".rmp", "application/vnd.rn-rn_music_package"],
        [".roff", "application/x-troff"],
        [".rpm", "audio/x-pn-realaudio-plugin"],
        [".rqy", "text/x-ms-rqy"],
        [".rtf", "application/rtf"],
        [".rtx", "text/richtext"],
        [".ruleset", "application/xml"],
        [".s", "text/plain"],
        [".safariextz", "application/x-safari-safariextz"],
        [".scd", "application/x-msschedule"],
        [".sct", "text/scriptlet"],
        [".sd2", "audio/x-sd2"],
        [".sdp", "application/sdp"],
        [".sea", "application/octet-stream"],
        [".searchConnector-ms", "application/windows-search-connector+xml"],
        [".setpay", "application/set-payment-initiation"],
        [".setreg", "application/set-registration-initiation"],
        [".settings", "application/xml"],
        [".sgimb", "application/x-sgimb"],
        [".sgml", "text/sgml"],
        [".sh", "application/x-sh"],
        [".shar", "application/x-shar"],
        [".shtml", "text/html"],
        [".sit", "application/x-stuffit"],
        [".sitemap", "application/xml"],
        [".skin", "application/xml"],
        [".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"],
        [".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"],
        [".slk", "application/vnd.ms-excel"],
        [".sln", "text/plain"],
        [".slupkg-ms", "application/x-ms-license"],
        [".smd", "audio/x-smd"],
        [".smi", "application/octet-stream"],
        [".smx", "audio/x-smd"],
        [".smz", "audio/x-smd"],
        [".snd", "audio/basic"],
        [".snippet", "application/xml"],
        [".snp", "application/octet-stream"],
        [".sol", "text/plain"],
        [".sor", "text/plain"],
        [".spc", "application/x-pkcs7-certificates"],
        [".spl", "application/futuresplash"],
        [".src", "application/x-wais-source"],
        [".srf", "text/plain"],
        [".SSISDeploymentManifest", "text/xml"],
        [".ssm", "application/streamingmedia"],
        [".sst", "application/vnd.ms-pki.certstore"],
        [".stl", "application/vnd.ms-pki.stl"],
        [".sv4cpio", "application/x-sv4cpio"],
        [".sv4crc", "application/x-sv4crc"],
        [".svc", "application/xml"],
        [".swf", "application/x-shockwave-flash"],
        [".t", "application/x-troff"],
        [".tar", "application/x-tar"],
        [".tcl", "application/x-tcl"],
        [".testrunconfig", "application/xml"],
        [".testsettings", "application/xml"],
        [".tex", "application/x-tex"],
        [".texi", "application/x-texinfo"],
        [".texinfo", "application/x-texinfo"],
        [".tgz", "application/x-compressed"],
        [".thmx", "application/vnd.ms-officetheme"],
        [".thn", "application/octet-stream"],
        [".tif", "image/tiff"],
        [".tiff", "image/tiff"],
        [".tlh", "text/plain"],
        [".tli", "text/plain"],
        [".toc", "application/octet-stream"],
        [".tr", "application/x-troff"],
        [".trm", "application/x-msterminal"],
        [".trx", "application/xml"],
        [".ts", "video/vnd.dlna.mpeg-tts"],
        [".tsv", "text/tab-separated-values"],
        [".ttf", "application/octet-stream"],
        [".tts", "video/vnd.dlna.mpeg-tts"],
        [".txt", "text/plain"],
        [".u32", "application/octet-stream"],
        [".uls", "text/iuls"],
        [".user", "text/plain"],
        [".ustar", "application/x-ustar"],
        [".vb", "text/plain"],
        [".vbdproj", "text/plain"],
        [".vbk", "video/mpeg"],
        [".vbproj", "text/plain"],
        [".vbs", "text/vbscript"],
        [".vcf", "text/x-vcard"],
        [".vcproj", "Application/xml"],
        [".vcs", "text/plain"],
        [".vcxproj", "Application/xml"],
        [".vddproj", "text/plain"],
        [".vdp", "text/plain"],
        [".vdproj", "text/plain"],
        [".vdx", "application/vnd.ms-visio.viewer"],
        [".vml", "text/xml"],
        [".vscontent", "application/xml"],
        [".vsct", "text/xml"],
        [".vsd", "application/vnd.visio"],
        [".vsi", "application/ms-vsi"],
        [".vsix", "application/vsix"],
        [".vsixlangpack", "text/xml"],
        [".vsixmanifest", "text/xml"],
        [".vsmdi", "application/xml"],
        [".vspscc", "text/plain"],
        [".vss", "application/vnd.visio"],
        [".vsscc", "text/plain"],
        [".vssettings", "text/xml"],
        [".vssscc", "text/plain"],
        [".vst", "application/vnd.visio"],
        [".vstemplate", "text/xml"],
        [".vsto", "application/x-ms-vsto"],
        [".vsw", "application/vnd.visio"],
        [".vsx", "application/vnd.visio"],
        [".vtx", "application/vnd.visio"],
        [".wav", "audio/wav"],
        [".wave", "audio/wav"],
        [".wax", "audio/x-ms-wax"],
        [".wbk", "application/msword"],
        [".wbmp", "image/vnd.wap.wbmp"],
        [".wcm", "application/vnd.ms-works"],
        [".wdb", "application/vnd.ms-works"],
        [".wdp", "image/vnd.ms-photo"],
        [".webarchive", "application/x-safari-webarchive"],
        [".webtest", "application/xml"],
        [".wiq", "application/xml"],
        [".wiz", "application/msword"],
        [".wks", "application/vnd.ms-works"],
        [".WLMP", "application/wlmoviemaker"],
        [".wlpginstall", "application/x-wlpg-detect"],
        [".wlpginstall3", "application/x-wlpg3-detect"],
        [".wm", "video/x-ms-wm"],
        [".wma", "audio/x-ms-wma"],
        [".wmd", "application/x-ms-wmd"],
        [".wmf", "application/x-msmetafile"],
        [".wml", "text/vnd.wap.wml"],
        [".wmlc", "application/vnd.wap.wmlc"],
        [".wmls", "text/vnd.wap.wmlscript"],
        [".wmlsc", "application/vnd.wap.wmlscriptc"],
        [".wmp", "video/x-ms-wmp"],
        [".wmv", "video/x-ms-wmv"],
        [".wmx", "video/x-ms-wmx"],
        [".wmz", "application/x-ms-wmz"],
        [".wpl", "application/vnd.ms-wpl"],
        [".wps", "application/vnd.ms-works"],
        [".wri", "application/x-mswrite"],
        [".wrl", "x-world/x-vrml"],
        [".wrz", "x-world/x-vrml"],
        [".wsc", "text/scriptlet"],
        [".wsdl", "text/xml"],
        [".wvx", "video/x-ms-wvx"],
        [".x", "application/directx"],
        [".xaf", "x-world/x-vrml"],
        [".xaml", "application/xaml+xml"],
        [".xap", "application/x-silverlight-app"],
        [".xbap", "application/x-ms-xbap"],
        [".xbm", "image/x-xbitmap"],
        [".xdr", "text/plain"],
        [".xht", "application/xhtml+xml"],
        [".xhtml", "application/xhtml+xml"],
        [".xla", "application/vnd.ms-excel"],
        [".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"],
        [".xlc", "application/vnd.ms-excel"],
        [".xld", "application/vnd.ms-excel"],
        [".xlk", "application/vnd.ms-excel"],
        [".xll", "application/vnd.ms-excel"],
        [".xlm", "application/vnd.ms-excel"],
        [".xls", "application/vnd.ms-excel"],
        [".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"],
        [".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"],
        [".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
        [".xlt", "application/vnd.ms-excel"],
        [".xltm", "application/vnd.ms-excel.template.macroEnabled.12"],
        [".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"],
        [".xlw", "application/vnd.ms-excel"],
        [".xml", "text/xml"],
        [".xmta", "application/xml"],
        [".xof", "x-world/x-vrml"],
        [".XOML", "text/plain"],
        [".xpm", "image/x-xpixmap"],
        [".xps", "application/vnd.ms-xpsdocument"],
        [".xrm-ms", "text/xml"],
        [".xsc", "application/xml"],
        [".xsd", "text/xml"],
        [".xsf", "text/xml"],
        [".xsl", "text/xml"],
        [".xslt", "text/xml"],
        [".xsn", "application/octet-stream"],
        [".xss", "application/xml"],
        [".xtp", "application/octet-stream"],
        [".xwd", "image/x-xwindowdump"],
        [".z", "application/x-compress"],
        [".zip", "application/x-zip-compressed"]
];

// ----------------------- End of Extensions to MIME --------- //

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Strip first and last character from C string

Another option, again assuming that "edit" means you want to modify in place:

void topntail(char *str) {
    size_t len = strlen(str);
    assert(len >= 2); // or whatever you want to do with short strings
    memmove(str, str+1, len-2);
    str[len-2] = 0;
}

This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

How to use Git for Unity3D source control?

I would rather prefer that you use BitBucket, as it is not public and there is an official tutorial by Unity on Bitbucket.

https://unity3d.com/learn/tutorials/topics/cloud-build/creating-your-first-source-control-repository

hope this helps.

python paramiko ssh

###### Use paramiko to connect to LINUX platform############
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp) # Output 

How can I create a dynamically sized array of structs?

This looks like an academic exercise which unfortunately makes it harder since you can't use C++. Basically you have to manage some of the overhead for the allocation and keep track how much memory has been allocated if you need to resize it later. This is where the C++ standard library shines.

For your example, the following code allocates the memory and later resizes it:

// initial size
int count = 100;
words *testWords = (words*) malloc(count * sizeof(words));
// resize the array
count = 76;
testWords = (words*) realloc(testWords, count* sizeof(words));

Keep in mind, in your example you are just allocating a pointer to a char and you still need to allocate the string itself and more importantly to free it at the end. So this code allocates 100 pointers to char and then resizes it to 76, but does not allocate the strings themselves.

I have a suspicion that you actually want to allocate the number of characters in a string which is very similar to the above, but change word to char.

EDIT: Also keep in mind it makes a lot of sense to create functions to perform common tasks and enforce consistency so you don't copy code everywhere. For example, you might have a) allocate the struct, b) assign values to the struct, and c) free the struct. So you might have:

// Allocate a words struct
words* CreateWords(int size);
// Assign a value
void AssignWord(word* dest, char* str);
// Clear a words structs (and possibly internal storage)
void FreeWords(words* w);

EDIT: As far as resizing the structs, it is identical to resizing the char array. However the difference is if you make the struct array bigger, you should probably initialize the new array items to NULL. Likewise, if you make the struct array smaller, you need to cleanup before removing the items -- that is free items that have been allocated (and only the allocated items) before you resize the struct array. This is the primary reason I suggested creating helper functions to help manage this.

// Resize words (must know original and new size if shrinking
// if you need to free internal storage first)
void ResizeWords(words* w, size_t oldsize, size_t newsize);

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

HTML input type=file, get the image before submitting the form

Here is the complete example for previewing image before it gets upload.

HTML :

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>

JavaScript :

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
        .attr('src', e.target.result)
        .width(150)
        .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

Loading all images using imread from a given folder

import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
    n= cv2.imread(img)
    cv_img.append(n)`

PHP Multidimensional Array Searching (Find key by specific value)

For the next visitor coming along: use the recursive array walk; it visits every "leaf" in the multidimensional array. Here's for inspiration:

function getMDArrayValueByKey($a, $k) {
    $r = [];
    array_walk_recursive ($a, 
                          function ($item, $key) use ($k, &$r) {if ($key == $k) $r[] = $item;}
                          );
    return $r;
}

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

Converting an OpenCV Image to Black and White

Approach 1

While converting a gray scale image to a binary image, we usually use cv2.threshold() and set a threshold value manually. Sometimes to get a decent result we opt for Otsu's binarization.

I have a small hack I came across while reading some blog posts.

  1. Convert your color (RGB) image to gray scale.
  2. Obtain the median of the gray scale image.
  3. Choose a threshold value either 33% above the median

enter image description here

Why 33%?

This is because 33% works for most of the images/data-set.

You can also work out the same approach by replacing median with the mean.

Approach 2

Another approach would be to take an x number of standard deviations (std) from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following:

  • th1 = mean - (x * std)
  • th2 = mean + (x * std)

Note: Before applying threshold it is advisable to enhance the contrast of the gray scale image locally (See CLAHE).

How to sum digits of an integer in java?

without mapping ? the quicker lambda solution

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );

…or same with the slower % operator

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );


…or Unicode compliant

Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );

Eclipse Error: "Failed to connect to remote VM"

I tried several things mentioned here, but the below method worked for me:

Go to Debug Console of Eclipse, where you will find the name of the process which is already existing there. Right click on that process and select "Terminate and Remove", this will terminate the process. Now try initiating the process again and it will work.

Typescript empty object for a typed variable

If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

type User = {
    Username?: string;
    Email?: string;
}

How to write string literals in python without having to escape them?

(Assuming you are not required to input the string from directly within Python code)

to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

This will print the literal text of whatever is in the text file, even if it is;

 '   ''' """  “ \

Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.

Shrinking navigation bar when scrolling down (bootstrap3)

If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/

You can do this so nice like this :

HTML:

<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
    <div class="container-fluid top-header">
        <!--- Rest of code --->
    </div>
</nav>

CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)

nav.navbar {
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;

  background-color: white;
  margin-bottom: 0;
  padding: 25px;
}

.navbar-fixed-top {
  padding: 0;
}

And then add your directive

Directive: (Note you may need to change this.pageYOffset >= 50 from 50 to more or less to fulfill your needs)

angular.module('app')
.directive('scrollNav', function ($window) {
  return function(scope, element, attrs) {
    angular.element($window).bind("scroll", function() {
      if (this.pageYOffset >= 50) {
        scope.scrollDown = true;
      } else {
        scope.scrollDown = false;
      }
      scope.$apply();
    });
  };
});

This will do the job nicely, animated and cool way.

Replace HTML Table with Divs

Please be aware that although tables are discouraged as a primary means of page layout, they still have their place. Tables can and should be used when and where appropriate and until some of the more popular browsers (ahem, IE, ahem) become more standards compliant, tables are sometimes the best route to a solution.

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

Convert list to dictionary using linq and not worrying about duplicates

A Linq-solution using Distinct() and and no grouping is:

var _people = personList
    .Select(item => new { Key = item.Key, FirstAndLastName = item.FirstAndLastName })
    .Distinct()
    .ToDictionary(item => item.Key, item => item.FirstFirstAndLastName, StringComparer.OrdinalIgnoreCase);

I don't know if it is nicer than LukeH's solution but it works as well.

Bash script plugin for Eclipse?

ShellEd is a good plugin for Eclipse.

This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/

Steps:

  1. Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.

  2. Then click Help > Install New Software...

  3. Click Add... in the upper right.
  4. Click Archive...
  5. Navigate to where you saved the zipped archive net.sourceforge.shelled-site-2.0.x.zip and select it.
  6. Click OK. (Don't worry about the optional Name field. Eclipse will name it automatically.)
  7. Select the new Shell Script checkbox.
  8. Click Next.
  9. Click Next again.
  10. Select "I accept the terms of the license agreement."
  11. Click Finish.
  12. Restart Eclipse.

How to pipe list of files returned by find command to cat to view all the files

Sounds like a job for a shell script to me:

for file in 'find -name *.xml'
do
   grep 'hello' file
done

or something like that

Write lines of text to a file in R

I would use the cat() command as in this example:

> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)

You can then view the results from with R with

> file.show("outfile.txt")
hello
world

Angular File Upload

In Angular 7/8/9

Source Link

enter image description here

Using Bootstrap Form

<form>
    <div class="form-group">
        <fieldset class="form-group">

            <label>Upload Logo</label>
            {{imageError}}
            <div class="custom-file fileInputProfileWrap">
                <input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
                <div class="img-space">

                    <ng-container *ngIf="isImageSaved; else elseTemplate">
                        <img [src]="cardImageBase64" />
                    </ng-container>
                    <ng-template #elseTemplate>

                        <img src="./../../assets/placeholder.png" class="img-responsive">
                    </ng-template>

                </div>

            </div>
        </fieldset>
    </div>
    <a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>

In Component Class

fileChangeEvent(fileInput: any) {
    this.imageError = null;
    if (fileInput.target.files && fileInput.target.files[0]) {
        // Size Filter Bytes
        const max_size = 20971520;
        const allowed_types = ['image/png', 'image/jpeg'];
        const max_height = 15200;
        const max_width = 25600;

        if (fileInput.target.files[0].size > max_size) {
            this.imageError =
                'Maximum size allowed is ' + max_size / 1000 + 'Mb';

            return false;
        }

        if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
            this.imageError = 'Only Images are allowed ( JPG | PNG )';
            return false;
        }
        const reader = new FileReader();
        reader.onload = (e: any) => {
            const image = new Image();
            image.src = e.target.result;
            image.onload = rs => {
                const img_height = rs.currentTarget['height'];
                const img_width = rs.currentTarget['width'];

                console.log(img_height, img_width);


                if (img_height > max_height && img_width > max_width) {
                    this.imageError =
                        'Maximum dimentions allowed ' +
                        max_height +
                        '*' +
                        max_width +
                        'px';
                    return false;
                } else {
                    const imgBase64Path = e.target.result;
                    this.cardImageBase64 = imgBase64Path;
                    this.isImageSaved = true;
                    // this.previewImagePath = imgBase64Path;
                }
            };
        };

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

removeImage() {
    this.cardImageBase64 = null;
    this.isImageSaved = false;
}

Javascript Click on Element by Class

class of my button is "input-addon btn btn-default fileinput-exists"

below code helped me

document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();

but I want to click second button, I have two buttons in my screen so I used querySelectorAll

var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
                elem[1].click();

here elem[1] is the second button object that I want to click.

What causes: "Notice: Uninitialized string offset" to appear?

It means one of your arrays isn't actually an array.

By the way, your if check is unnecessary. If $varsCount is 0 the for loop won't execute anyway.

How to get a path to a resource in a Java JAR file

A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.

Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

I suggest to look at Dan Abramov (one of the React core maintainers) answer here:

I think you're making it more complicated than it needs to be.

function Example() {
  const [data, dataSet] = useState<any>(null)

  useEffect(() => {
    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await response.json()
      dataSet(response)
    }

    fetchMyAPI()
  }, [])

  return <div>{JSON.stringify(data)}</div>
}

Longer term we'll discourage this pattern because it encourages race conditions. Such as — anything could happen between your call starts and ends, and you could have gotten new props. Instead, we'll recommend Suspense for data fetching which will look more like

const response = MyAPIResource.read();

and no effects. But in the meantime you can move the async stuff to a separate function and call it.

You can read more about experimental suspense here.


If you want to use functions outside with eslint.

 function OutsideUsageExample() {
  const [data, dataSet] = useState<any>(null)

  const fetchMyAPI = useCallback(async () => {
    let response = await fetch('api/data')
    response = await response.json()
    dataSet(response)
  }, [])

  useEffect(() => {
    fetchMyAPI()
  }, [fetchMyAPI])

  return (
    <div>
      <div>data: {JSON.stringify(data)}</div>
      <div>
        <button onClick={fetchMyAPI}>manual fetch</button>
      </div>
    </div>
  )
}

If you will use useCallback, look at example of how it works useCallback. Sandbox.

import React, { useState, useEffect, useCallback } from "react";

export default function App() {
  const [counter, setCounter] = useState(1);

  // if counter is changed, than fn will be updated with new counter value
  const fn = useCallback(() => {
    setCounter(counter + 1);
  }, [counter]);

  // if counter is changed, than fn will not be updated and counter will be always 1 inside fn
  /*const fnBad = useCallback(() => {
      setCounter(counter + 1);
    }, []);*/

  // if fn or counter is changed, than useEffect will rerun
  useEffect(() => {
    if (!(counter % 2)) return; // this will stop the loop if counter is not even

    fn();
  }, [fn, counter]);

  // this will be infinite loop because fn is always changing with new counter value
  /*useEffect(() => {
    fn();
  }, [fn]);*/

  return (
    <div>
      <div>Counter is {counter}</div>
      <button onClick={fn}>add +1 count</button>
    </div>
  );
}

Python: Best way to add to sys.path relative to the current running script

Using python 3.4+
Barring the use of cx_freeze or using in IDLE.

import sys
from pathlib import Path

sys.path.append(Path(__file__).parent / "lib")

Socket send and receive byte array

There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.

(from that tutorial) This sets up to read from an echo server:

    echoSocket = new Socket("taranis", 7);
    out = new PrintWriter(echoSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(
                                echoSocket.getInputStream()));

taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).

Error handling and closing sockets/streams omitted from the above, but check the tutorial.

mat-form-field must contain a MatFormFieldControl

import {MatInputModule} from '@angular/material/input';



@NgModule({
    imports: [
        MatInputModule
    ],
    exports: [
        MatInputModule
    ]
})

HTML <sup /> tag affecting line height, how to make it consistent?

sup, sub {
  vertical-align: baseline;
  position: relative;
  top: -0.4em;
}
sub { 
  top: 0.4em; 
}

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

PHP 7 simpleXML

Typically on Debian systems you have different PHP configuration for CLI and for PHP running as say an Apache module. Your phpinfo page may very well show simplexml as being enabled via web server, while it is not enabled via CLI.

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

While configure could find my Boost installation, CMake could not.

Locate FindBoost.cmake and look for LIBRARY_HINTS to see what sub-packages it is looking for. In my case it wanted the MPI and graph libraries.

 # Compute component-specific hints.
  set(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "")
  if(${COMPONENT} STREQUAL "mpi" OR ${COMPONENT} STREQUAL "mpi_python" OR
     ${COMPONENT} STREQUAL "graph_parallel")
    foreach(lib ${MPI_CXX_LIBRARIES} ${MPI_C_LIBRARIES})
      if(IS_ABSOLUTE "${lib}")
        get_filename_component(libdir "${lib}" PATH)
        string(REPLACE "\\" "/" libdir "${libdir}")
        list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT ${libdir})
      endif()
    endforeach()
  endif()

apt-cache search ... I installed the dev packages since I was building code, and the dev package drags in all the dependencies. I'm not so sure that a standard Boost install needs Open MPI, but this is OK for now.

sudo apt-get install libboost-mpi-dev libboost-mpi-python-dev
sudo apt-get install libboost-graph-parallel-dev

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

How do I read input character-by-character in Java?

Combining the recommendations from others for specifying a character encoding and buffering the input, here's what I think is a pretty complete answer.

Assuming you have a File object representing the file you want to read:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(
        new FileInputStream(file),
        Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
  char character = (char) c;
  // Do something with your character
}

Finding the max value of an attribute in an array of objects

// Here is very simple way to go:

// Your DataSet.

let numberArray = [
  {
    "x": "8/11/2009",
    "y": 0.026572007
  },
  {
    "x": "8/12/2009",
    "y": 0.025057454
  },
  {
    "x": "8/13/2009",
    "y": 0.024530916
  },
  {
    "x": "8/14/2009",
    "y": 0.031004457
  }
]

// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]

// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457

Reactive forms - disabled attribute

Ultimate way to do this.

ngOnInit() {
  this.interPretationForm.controls.InterpretationType.valueChanges.takeWhile(()=> this.alive).subscribe(val =>{
    console.log(val); // You check code. it will be executed every time value change.
  })
}

Generate random 5 characters string

I always use the same function for this, usually to generate passwords. It's easy to use and useful.

function randPass($length, $strength=8) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength >= 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength >= 2) {
        $vowels .= "AEUY";
    }
    if ($strength >= 4) {
        $consonants .= '23456789';
    }
    if ($strength >= 8) {
        $consonants .= '@#$%';
    }

    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

where does MySQL store database files?

WAMP stores the db data under WAMP\bin\mysql\mysql(version)\data. Where the WAMP folder itself is depends on where you installed it to (on xp, I believe it is directly in the main drive, for example c:\WAMP\...

If you deleted that folder, or if the uninstall deleted that folder, if you did not do a DB backup before the uninstall, you may be out of luck.

If you did do a backup though phpmyadmin, then login, and click the import tab, and browse to the backup file.

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

Pandas read_csv low_memory and dtype options

I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:

  1. the file contained strange characters (fixed using encoding)
  2. the datatype was not specified (fixed using dtype property)
  3. Using the above I still faced an issue which was related with the file_format that could not be defined based on the filename (fixed using try .. except..)
    df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
                     names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
                     dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
    
    try:
        df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
    except:
        df['file_format'] = ''

JavaFX Location is not set error message

This worked for me well :

 public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException {

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/TestDataGenerator.fxml"));
        loader.setClassLoader(getClass().getClassLoader());
        Parent root = loader.load();
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

uppercase first character in a variable with bash

foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

Synchronous Requests in Node.js

The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.

There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?

You'd want to have a counter, and only call the callback when the data is there:

var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    ucomp = split2[1];
    if(--waiting == 0) callback();
});

request( {url: base + v_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    vcomp = split2[1];
    if(--waiting == 0) callback();
});

function callback() {
    // do math here.
}

Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.

Dart/Flutter : Converting timestamp

meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.

EDIT:

From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.

import 'package:timeago/timeago.dart' as timeago;

final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));

// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());

// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());

print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes

to convert epochMS to DateTime, just use...

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

How do I declare a namespace in JavaScript?

JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollute the global namespace. Let's take an example of defining two functions without any namespace,

function func1() {
    console.log("This is a first definition");

}
function func1() {
    console.log("This is a second definition");
}
func1(); // This is a second definition

It always calls the second function definition. In this case, namespace will solve the name collision problem.

How to sum all column values in multi-dimensional array?

You can try this:

$c = array_map(function () {
      return array_sum(func_get_args());
     },$a, $b);

and finally:

print_r($c);

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

What is an abstract class in PHP?

An abstract class is a class that contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as "abstract".

The purpose of this is to provide a kind of template to inherit from and to force the inheriting class to implement the abstract methods.

An abstract class thus is something between a regular class and a pure interface. Also interfaces are a special case of abstract classes where ALL methods are abstract.

See this section of the PHP manual for further reference.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?

Just read your exception stacktrace:

Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

So it seems that you are using the Microsoft.Web.Helpers which in turn depends on System.Web.WebPages.Razor, Version=2.0.0.0.

How do you append rows to a table using jQuery?

Add as first row or last row in a table

To add as first row in table

$(".table tbody").append("<tr><td>New row</td></tr>");

To add as last row in table

$(".table tbody").prepend("<tr><td>New row</td></tr>");

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Get an image extension from an uploaded file in Laravel

If you just want the extension, you can use pathinfo:

$ext = pathinfo($file_path, PATHINFO_EXTENSION);

How to scroll to bottom in a ScrollView on activity startup

This is the best way of doing this.

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
});

JCheckbox - ActionListener and ItemListener?

Both ItemListener as well as ActionListener, in case of JCheckBox have the same behaviour. However, major difference is ItemListener can be triggered by calling the setSelected(true) on the checkbox. As a coding practice do not register both ItemListener as well as ActionListener with the JCheckBox, in order to avoid inconsistency.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;

I also use the newer command:

Connect-SPOService

jQuery .load() call doesn't execute JavaScript in loaded HTML file

You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?

Here is the driver page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery Load of Script</title>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("jquery", "1.3.2");
        </script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#myButton").click(function() {
                    $("#myDiv").load("trackingCode.html");
                });
             });
         </script>
    </head>
    <body>
        <button id="myButton">Click Me</button>
        <div id="myDiv"></div>
    </body>
</html>

Here is the contents of trackingCode.html:

<script type="text/javascript">
    alert("Outside the jQuery ready");
    $(function() {
        alert("Inside the jQuery ready");
    });
 </script>

This works for me in Safari 4.

Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

T-SQL substring - separating first and last name

You could do this if firstname and surname are separated by space:

SELECT SUBSTRING(FirstAndSurnameCol, 0, CHARINDEX(' ', FirstAndSurnameCol)) Firstname,
SUBSTRING(FirstAndSurnameCol, CHARINDEX(' ', FirstAndSurnameCol)+1, LEN(FirstAndSurnameCol)) Surname FROM ...

Chrome extension id - how to find it

As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".

However, you must click the Developer Mode checkbox at top of Extensions page to see them.

How Can I Truncate A String In jQuery?

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

Authentication failed because remote party has closed the transport stream

For VB.NET, you can place the following before your web request:

Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12

This solved my security issue on .NET 3.5.

Set the maximum character length of a UITextField in Swift

Simple solution without using delegate:

TEXT_FIELD.addTarget(self, action: #selector(editingChanged(sender:)), for: .editingChanged)


@objc private func editingChanged(sender: UITextField) {

        if let text = sender.text, text.count >= MAX_LENGHT {
            sender.text = String(text.dropLast(text.count - MAX_LENGHT))
            return
        }
}

ArrayList initialization equivalent to array initialization

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

How should I print types like off_t and size_t?

For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification

As for off_t, it is defined as long in VC\include\sys\types.h.

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

Unsetting array values in a foreach loop

Sorry for the late response, I recently had the same problem with PHP and found out that when working with arrays that do not use $key => $value structure, when using the foreach loop you actual copy the value of the position on the loop variable, in this case $image. Try using this code and it will fix your problem.

for ($i=0; $i < count($images[1]); $i++)
{

    if($images[1][$i] == 'http://i27.tinypic.com/29yk345.gif' ||

    $images[1][$i] == 'http://img3.abload.de/img/10nx2340fhco.gif' ||

    $images[1][$i] == 'http://i42.tinypic.com/9pp2456x.gif')

    {

        unset($images[1][$i]);

    }

}

var_dump($images);die();

How to create a hash or dictionary object in JavaScript

You want to create an Object, not an Array.

Like so,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

Numpy Resize/Rescale Image

For people coming here from Google looking for a fast way to downsample images in numpy arrays for use in Machine Learning applications, here's a super fast method (adapted from here ). This method only works when the input dimensions are a multiple of the output dimensions.

The following examples downsample from 128x128 to 64x64 (this can be easily changed).

Channels last ordering

# large image is shape (128, 128, 3)
# small image is shape (64, 64, 3)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((output_size, bin_size, 
                                   output_size, bin_size, 3)).max(3).max(1)

Channels first ordering

# large image is shape (3, 128, 128)
# small image is shape (3, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((3, output_size, bin_size, 
                                      output_size, bin_size)).max(4).max(2)

For grayscale images just change the 3 to a 1 like this:

Channels first ordering

# large image is shape (1, 128, 128)
# small image is shape (1, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((1, output_size, bin_size,
                                      output_size, bin_size)).max(4).max(2)

This method uses the equivalent of max pooling. It's the fastest way to do this that I've found.

PHP form send email to multiple recipients

If these all answers are not working then You can simply use multiple mail function for multiple recipient.

$email_to1 = "[email protected]";
$email_to2 = "[email protected]";

mail($email_to1, $email_subject, $email_message, $headers);  
mail($email_to2, $email_subject, $email_message, $headers);  

How to create multidimensional array

Hope the following code suits your requirement

var row= 20;
var column= 10;
var f = new Array();

for (i=0;i<row;i++) {
 f[i]=new Array();
 for (j=0;j<column;j++) {
  f[i][j]=0;
 }
}

Java - Convert String to valid URI object

I ended up using the httpclient-4.3.6:

import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
    URIBuilder uri = new URIBuilder();
    uri.setScheme("http")
    .setHost("www.example.com")
    .setPath("/somepage.php")
    .setParameter("username", "Hello Günter")
    .setParameter("p1", "parameter 1");
    System.out.println(uri.toString());
}

Output will be:

http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

How can I increment a char?

I came from PHP, where you can increment char (A to B, Z to AA, AA to AB etc.) using ++ operator. I made a simple function which does the same in Python. You can also change list of chars to whatever (lowercase, uppercase, etc.) is your need.

# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    # Unique and sort
    chlist = ''.join(sorted(set(str(chlist))))
    chlen = len(chlist)
    if not chlen:
        return ''
    text = str(text)
    # Replace all chars but chlist
    text = re.sub('[^' + chlist + ']', '', text)
    if not len(text):
        return chlist[0]
    # Increment
    inc = ''
    over = False
    for i in range(1, len(text)+1):
        lchar = text[-i]
        pos = chlist.find(lchar) + 1
        if pos < chlen:
            inc = chlist[pos] + inc
            over = False
            break
        else:
            inc = chlist[0] + inc
            over = True
    if over:
        inc += chlist[0]
    result = text[0:-len(inc)] + inc
    return result

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

Destroy or remove a view in Backbone.js

According to current Backbone documentation....

view.remove()

Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

Convert hex string to int in Python

Or ast.literal_eval (this is safe, unlike eval):

ast.literal_eval("0xffff")

Demo:

>>> import ast
>>> ast.literal_eval("0xffff")
65535
>>> 

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Date minus 1 year?

Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php

So, for reference, you can also use a \DateInterval to modify a \Datetime object:

$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));

echo $date->format('Y-m-d');

Which returns:

2008-01-01

For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php

Conditionally formatting cells if their value equals any value of another column

Another simpler solution is to use this formula in the conditional formatting (apply to column A):

=COUNTIF(B:B,A1)

Regards!

String.replaceAll single backslashes with double backslashes

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex:

string.replaceAll("\\\\", "\\\\\\\\");

But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace() should suffice:

string.replace("\\", "\\\\");

Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript() instead to cover more characters.

Clear and refresh jQuery Chosen dropdown list

In my case, I need to update selected value at each change because when I submit form, it always gets wrong values and I used multiple chosen drop downs. Rather than updating single entries, change selector to update all drop downs. This might help someone

 $(".chosen-select").chosen().change(function () {
    var item = $(this).val();
    $('.chosen-select').trigger('chosen:updated');
});

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Check your android:authorities attribute under <provider tag


Check if your package name is correct or not

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

For people who are looking to insert a row between two rows in an existing excel with XSSF (Apache POI), there is already a method "copyRows" implemented in the XSSFSheet.

import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class App2 throws Exception{
    public static void main(String[] args){
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("input.xlsx"));
        XSSFSheet sheet = workbook.getSheet("Sheet1");
        sheet.copyRows(0, 2, 3, new CellCopyPolicy());
        FileOutputStream out = new FileOutputStream("output.xlsx");
        workbook.write(out);
        out.close();
    }
}

What is the naming convention in Python for variable and function names?

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

py2exe - generate single executable file

PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)

I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.

SQL Error with Order By in Subquery

Besides the fact that order by doesn't seem to make sense in your query.... To use order by in a sub select you will need to use TOP 2147483647.

SELECT (
  SELECT TOP 2147483647
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

My understanding is that "TOP 100 PERCENT" doesn't gurantee ordering anymore starting with SQL 2005:

In SQL Server 2005, the ORDER BY clause in a view definition is used only to determine the rows that are returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when the view is queried, unless ORDER BY is also specified in the query itself.

See SQL Server 2005 breaking changes

Hope this helps, Patrick

How can I implement custom Action Bar with custom buttons in Android?

1 You can use a drawable

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_item1"
        android:icon="@drawable/my_item_drawable"
        android:title="@string/menu_item1"
        android:showAsAction="ifRoom" />
</menu>

2 Create a style for the action bar and use a custom background:

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <!-- other activity and action bar styles here -->
    </style>
    <!-- style for the action bar backgrounds -->
    <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/background</item>
        <item name="android:backgroundStacked">@drawable/background</item>
        <item name="android:backgroundSplit">@drawable/split_background</item>
    </style>
</resources>

3 Style again android:actionBarDivider

The android documentation is very usefull for that.

How to choose between Hudson and Jenkins?

As chmullig wrote, use Jenkins. Some additional points:

...and a little background info:

The creator of Hudson, Kohsuke Kawaguchi, started the project on his free time, even if he was working for Sun Microsystems and later paid by them to develop it further. As @erickson noted at another SO question,

[Hudson/Jenkins] is the product of a single genius intellect—Kohsuke Kawaguchi. Because of that, it's consistent, coherent, and rock solid.

After the acquisition by Oracle, Kohsuke didn't hang around for long (due to lack of monitors...? ;-]), and went to work for CloudBees. What started in late 2010 as conflict over tools between the dev community and Oracle and ended in the rename/fork/split is well documented in the links chmullig provided. To me, that whole conundrum speaks, perhaps more than anything else, to Oracle's utter inability or unwillingness to sponsor an open-source project in a way that keeps all parties (Oracle, developers, users) happy. It's not in their DNA or something, as we've seen in other cases too.

Given all of the above, I would personally follow Kohsuke and other core developers in this matter, and go with Jenkins.

Is it possible to insert multiple rows at a time in an SQLite database?

As the other posters have said, SQLite does not support this syntax. I don't know if compound INSERTs are part of the SQL standard, but in my experience they're not implemented in many products.

As an aside, you should be aware that INSERT performance in SQLite is improved considerably if you wrap multiple INSERTs in an explicit transaction.

Why is my Git Submodule HEAD detached from master?

Adding a branch option in .gitmodule is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.

From git submodule --help, HEAD detached is the default behavior of git submodule update --remote.

First, there's no need to specify a branch to be tracked. origin/master is the default branch to be tracked.

--remote

Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (branch.<name>.remote), defaulting to origin. The remote branch used defaults to master.

Why

So why is HEAD detached after update? This is caused by the default module update behavior: checkout.

--checkout

Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override submodule.$name.update when set to a value other than checkout.

To explain this weird update behavior, we need to understand how do submodules work?

Quote from Starting with Submodules in book Pro Git

Although sbmodule DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.

How

If you want the submodule merged with remote branch automatically, use --merge or --rebase.

--merge

This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.

--rebase

Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.

All you need to do is,

git submodule update --remote --merge
# or
git submodule update --remote --rebase

Recommended alias:

git config alias.supdate 'submodule update --remote --merge'

# do submodule update with
git supdate

There's also an option to make --merge or --rebase as the default behavior of git submodule update, by setting submodule.$name.update to merge or rebase.

Here's an example about how to config the default update behavior of submodule update in .gitmodule.

[submodule "bash/plugins/dircolors-solarized"]
    path = bash/plugins/dircolors-solarized
    url = https://github.com/seebi/dircolors-solarized.git
    update = merge # <-- this is what you need to add

Or configure it in command line,

# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge

References

How can I declare a two dimensional string array?

When you are trying to create a multi-dimensional array all you need to do is add a comma to the declaration like so:

string[,] tablero = new string[3,3].