Programs & Examples On #Tray

PackagesNotFoundError: The following packages are not available from current channels:

Have you tried:

pip install <package>

or

conda install -c conda-forge <package>

Error: fix the version conflict (google-services plugin)

Initially, the firebase database was pointing to 11.8.0 .after changing all the related jars to 11.0.4 this issue is resolved at changes the SDK level.

compile 'com.google.firebase:firebase-database:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I find this at google: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

It mentiones that we need to

  1. Update Gradle version to gradle-4.1-all ( changegradle-wrapper.properties by distributionUrl=\https\://services.gradle.org/distributions/gradle-4.1-all.zip
  2. Add google() to repositories repositories { google() } and dependencies { classpath 'com.android.tools.build:gradle:3.0.0-beta7' }

You may require to have Android Studio 3

Error:Cause: unable to find valid certification path to requested target

change dependencies from compile to Implementation in build.gradle file

Homebrew refusing to link OpenSSL

Note: this no longer works due to https://github.com/Homebrew/brew/pull/612

I had the same problem today. I uninstalled (unbrewed??) openssl 1.0.2 and installed 1.0.1 also with homebrew. Dotnet new/restore/run then worked fine.

Install openssl 101:
brew install homebrew/versions/openssl101
Linking:
brew link --force homebrew/versions/openssl101

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Do you have the line

apply plugin: 'com.google.gms.google-services' 

line at the bottom of your app's build.gradle file?

I saw some errors when it was on the top and as it's written here, it should be at the bottom.

No notification sound when sending notification from firebase in android

In the notification payload of the notification there is a sound key.

From the official documentation its use is:

Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.

Eg:

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",

    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon",
      "sound" : "mySound"
    }
  }

If you want to use default sound of the device, you should use: "sound": "default".

See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

Could not find method android() for arguments

My issue was inside of my app.gradle. I ran into this issue when I moved

apply plugin: "com.android.application"

from the top line to below a line with

apply from:

I switched the plugin back to the top and violá

My exact error was

Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.

The top of my app.gradle now looks like this

project.ext.envConfigFiles = [
        debug: ".env",
        release: ".env",
        anothercustombuild: ".env",
]


apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

After updating to Android 3.4, I started to get the error, tried all the above solutions.

Root cause of the problem was, updating Android Studio enabled the Instant Run.

Hence, one of the solutions you can try is Disabling Instant Run, if its enabled for you, fixed my problem.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

In my case, I just had to do

  1. Click Build
  2. Click Make Project

It all then went fine. I still have no clue what happened.

Error: stray '\240' in program

Your Program has invalid/invisible characters in it. You most likely would have picked up these invisible characters when you copy and past code from another website or sometimes a document. Copying the code from the site into another text document and then copying and pasting into your code editor may work, but depending on how long your code is you should just go with typing it out word for word.

Adding external library in Android studio

If the library you need is on GitHub then adding it to Android Studio is easy with JitPack.

Step 1. Add the jitpack repository to build.gradle:

allprojects { 
  repositories {
    jcenter()
    maven { url "https://jitpack.io" }
  }
}

Step 2. Add the GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.Username:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used much like Maven Central. The nice thing is that the maintainers don't have to upload the library. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore for this to work there needs to be a working build file in the git repository.

There is also a guide on how to publish an Android library.

What's the right way to pass form element state to sibling/parent elements?

So, if I'm understanding you correctly, your first solution is suggesting that you're keeping state in your root component? I can't speak for the creators of React, but generally, I find this to be a proper solution.

Maintaining state is one of the reasons (at least I think) that React was created. If you've ever implemented your own state pattern client side for dealing with a dynamic UI that has a lot of interdependent moving pieces, then you'll love React, because it alleviates a lot of this state management pain.

By keeping state further up in the hierarchy, and updating it through eventing, your data flow is still pretty much unidirectional, you're just responding to events in the Root component, you're not really getting the data there via two way binding, you're telling the Root component that "hey, something happened down here, check out the values" or you're passing the state of some data in the child component up in order to update the state. You changed the state in C1, and you want C2 to be aware of it, so, by updating the state in the Root component and re-rendering, C2's props are now in sync since the state was updated in the Root component and passed along.

class Example extends React.Component {
  constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }
  render () {
    return (
      <div>
        <C1 onUpdate={this.onUpdate.bind(this)}/>
        <C2 data={this.state.data}/>
      </div>
    )
  }
  onUpdate (data) { this.setState({ data }) }
}

class C1 extends React.Component {
    render () {
      return (
        <div>
          <input type='text' ref='myInput'/>
          <input type='button' onClick={this.update.bind(this)} value='Update C2'/>
        </div>
      )
    }
    update () {
      this.props.onUpdate(this.refs.myInput.getDOMNode().value)
    }
})

class C2 extends React.Component {
    render () {
      return <div>{this.props.data}</div>
    }
})

ReactDOM.renderComponent(<Example/>, document.body)

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mint 18 Cinnamon

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout.

How to move all HTML element children to another parent using JavaScript?

Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
    setParent(a.childNodes[0], b);
}

Here is the Demo

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

I noticed this commit comment in AOSP, the solution will be to exclude some files using DSL. Probably when 0.7.1 is released.

commit e7669b24c1f23ba457fdee614ef7161b33feee69
Author: Xavier Ducrohet <--->
Date:   Thu Dec 19 10:21:04 2013 -0800

    Add DSL to exclude some files from packaging.

    This only applies to files coming from jar dependencies.
    The DSL is:

    android {
      packagingOptions {
        exclude 'META-INF/LICENSE.txt'
      }
    }

Playing mp3 song on python

So Far, pydub worked best for me. Modules like playsound will also do the job, But It has only one single feature. pydub has many features like slicing the song(file), Adjusting the volume etc...

It is as simple as slicing the lists in python.

So, When it comes to just playing, It is as shown as below.

from pydub import AudioSegment
from pydub.playback import play

path_to_file = r"Music/Harry Potter Theme Song.mp3"
song = AudioSegment.from_mp3(path_to_file)
play(song)

Compilation error: stray ‘\302’ in program etc

You have invalid chars in your source. If you don't have any valid non ascii chars in your source, maybe in a double quoted string literal, you can simply convert your file back to ascii with:

tr -cd '\11\12\15\40-\176' < old.c > new.c

Edit: method with iconv will stop at wrong chars which makes no sense. The above command line is working with the example file. Good luck :-)

Composer Warning: openssl extension is missing. How to enable in WAMP

I was facing the same issue. I renamed my php folder from php7_winxxxx to just php and it worked fine. It looked like composer was checking the location to the php_openssl module in c:/php/ext.

You may also need to add c:/php to the PATH in environment variable

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

PHP cURL not working - WAMP on Windows 7 64 bit

I think cURL doesn't work with WAMP 2.2e. I tried all your solutions, but it still did not work. I got the previous version, (2.2d) and it works.

So just download the previous version :D

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

  1. Like you installed older version of PHP do the same with Apache. I picked version 2.0.63 and then I was able to run WAMP Server with PHP 5.2.9 with no problems.

  2. I also read that it's problem with 64-bit version of WAMP.

minimize app to system tray

I'd go with

private void Form1_Resize(object sender, EventArgs e)
{
     if (FormWindowState.Minimized == this.WindowState)
     {
          notifyIcon1.Visible = true;
          notifyIcon1.ShowBalloonTip(500);
          this.Hide();    
     }
     else if (FormWindowState.Normal == this.WindowState)
     {
          notifyIcon1.Visible = false;
     }
}

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
     this.Show();
     this.WindowState = FormWindowState.Normal;
}

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

How can I get a web site's favicon?

Using jquery

var favicon = $("link[rel='shortcut icon']").attr("href") ||
              $("link[rel='icon']").attr("href") || "";

WPF Application that only has a tray icon

You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.

I have code on GitHub which uses System.Windows.Forms NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs

Here are the summary bits:

Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.

At class-level:

private System.Windows.Forms.NotifyIcon notifyIcon = null;

During OnInitialize():

notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];

During OnLoaded():

notifyIcon.Visible = true;

And for interaction (shown as notifyIcon.Click and DoubleClick above):

void notifyIcon_Click(object sender, EventArgs e)
{
    ShowQuickLaunchMenu();
}

From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.

It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.

Hope that helps.

It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.

How can I make a .NET Windows Forms application that only runs in the System Tray?

Simply add

this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;

to your form object. You will see only an icon at system tray.

How to detect the physical connected state of a network cable/connector?

You can use ethtool:

$ sudo ethtool eth0
Settings for eth0:
    Supported ports: [ TP ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Advertised auto-negotiation: Yes
    Speed: 1000Mb/s
    Duplex: Full
    Port: Twisted Pair
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: umbg
    Wake-on: g
    Current message level: 0x00000007 (7)
    Link detected: yes

To only get the Link status you can use grep:

$ sudo ethtool eth0 | grep Link
    Link detected: yes

How to make a window always stay on top in .Net?

What is the other application you are trying to suppress the visibility of? Have you investigated other ways of achieving your desired effect? Please do so before subjecting your users to such rogue behaviour as you are describing: what you are trying to do sound rather like what certain naughty sites do with browser windows...

At least try to adhere to the rule of Least Surprise. Users expect to be able to determine the z-order of most applications themselves. You don't know what is most important to them, so if you change anything, you should focus on pushing the other application behind everything rather than promoting your own.

This is of course trickier, since Windows doesn't have a particularly sophisticated window manager. Two approaches suggest themselves:

  1. enumerating top-level windows and checking which process they belong to, dropping their z-order if so. (I'm not sure if there are framework methods for these WinAPI functions.)
  2. Fiddling with child process permissions to prevent it from accessing the desktop... but I wouldn't try this until the othe approach failed, as the child process might end up in a zombie state while requiring user interaction.

How do you determine what technology a website is built on?

You could use http://builtwith.com to figure out which server and programming language was used. For example it told me that SO uses IIS7, google analytics, html4 and utf8.

If you want to know the framework...well that will probably not be possible just from looking at the site. Why don't you write them an email? ;)

What is the difference between `new Object()` and object literal notation?

Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

Here is an example of creating an object using constructor function (see code explanation at the bottom):

function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

Person.prototype.fullname = function() {
    console.log(this.firstname + ' ' + this.lastname);
}

var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');

zubaer.fullname();
john.fullname();

Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

var zubaer = {
    firstname: 'Zubaer',
    lastname: 'Ahammed',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

var john= {
    firstname: 'John',
    lastname: 'Doe',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

zubaer.fullname();
john.fullname();

At last, if you now ask why should I use constructor function approach instead of object literal approach:

*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

I hope this makes sense.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

How to grep for contents after pattern?

This will print everything after each match, on that same line only:

perl -lne 'print $1 if /^potato:\s*(.*)/' file.txt

This will do the same, except it will also print all subsequent lines:

perl -lne 'if ($found){print} elsif (/^potato:\s*(.*)/){print $1; $found++}' file.txt

These command-line options are used:

  • -n loop around each line of the input file
  • -l removes newlines before processing, and adds them back in afterwards
  • -e execute the perl code

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

I tried all the solutions but it still wasn't sufficient. After some more digging I eventually found I had also to set the 'file_priv' flag, and restart mysql.

To resume :

Grant the privileges :

> GRANT ALL PRIVILEGES
  ON my_database.* 
  to 'my_user'@'localhost';

> GRANT FILE ON *.* TO my_user;

> FLUSH PRIVILEGES; 

Set the flag :

> UPDATE mysql.user SET File_priv = 'Y' WHERE user='my_user' AND host='localhost';

Finally restart the mysql server:

$ sudo service mysql restart

After that, I could write into the secure_file_priv directory. For me it was /var/lib/mysql-files/, but you can check it with the following command :

> SHOW VARIABLES LIKE "secure_file_priv";

How to replace a character by a newline in Vim

\r can do the work here for you.

Execute script after specific delay using JavaScript

To add on the earlier comments, I would like to say the following :

The setTimeout() function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.

There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date() function and adding the time interval you need.

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

How to inject window into a service?

I know the question is how to inject the window object into a component but you're doing this just to get to localStorage it seems. If you realy just want localStorage, why not use a service that exposes just that, like h5webstorage. Then you component will describe its real dependencies which makes your code more readable.

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

i do nothing, just add this tag in web.config, its working this issue come up one of the following points

  1. Use Web Api in the same project using MVC or asp.net forms

  2. Use RouteConfig and WebApiConfig in Global.asax as GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes);

  3. Use RouteConfig for 2 purposes, asp.net forms using with friendlyurl and mvc routing for MVC routing

we just use this tag in web.config, it will work.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
   .........................
</modules>
</system.webServer>

Error to run Android Studio

For me, running Fedora 22 with Gnome 16.2, this solution helped me. In short, you should install the java-1.8.0-openjdk-devel, the development files of the JDK.

Open the Terminal and search for the latest version of the JDK development package:

$ dnf search jdk-devel
Last metadata expiration check performed 12:44:51 ago on Mon Aug  3 22:20:24 2015.
============================ N/S Matched: jdk-devel ============================
java-1.8.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.8.0-openjdk-devel-debug.x86_64 : OpenJDK Development Environment with
                                      : full debug on
$ sudo dnf install java-1.8.0-openjdk-devel

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

How to delete a line from a text file in C#?

Remove a block of code from multiple files

To expand on @Markus Olsson's answer, I needed to remove a block of code from multiple files. I had problems with Swedish characters in a core project, so I needed to install System.Text.CodePagesEncodingProvider nuget package and use System.Text.Encoding.GetEncoding(1252) instead of System.Text.Encoding.UTF8.

    public static void Main(string[] args)
    {
        try
        {
            var dir = @"C:\Test";
            //Get all html and htm files
            var files = DirSearch(dir);
            foreach (var file in files)
            {
                RmCode(file);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            throw;
        }

    }

    private static void RmCode(string file)
    {
        string tempFile = Path.GetTempFileName();

        using (var sr = new StreamReader(file, Encoding.UTF8))
        using (var sw = new StreamWriter(new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8))
        {
            string line;

            var startOfBadCode = "<div>";
            var endOfBadCode = "</div>";
            var deleteLine = false;

            while ((line = sr.ReadLine()) != null)
            {
                if (line.Contains(startOfBadCode))
                {
                    deleteLine = true;
                }
                if (!deleteLine)
                {
                    sw.WriteLine(line);
                }

                if (line.Contains(endOfBadCode))
                {
                    deleteLine = false;
                }
            }
        }

        File.Delete(file);
        File.Move(tempFile, file);
    }

    private static List<String> DirSearch(string sDir)
    {
        List<String> files = new List<String>();
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                files.AddRange(DirSearch(d));
            }
        }
        catch (System.Exception excpt)
        {
            Console.WriteLine(excpt.Message);
        }

        return files.Where(s => s.EndsWith(".htm") || s.EndsWith(".html")).ToList();
    }

Using Docker-Compose, how to execute multiple commands

I recommend using sh as opposed to bash because it is more readily available on most Unix based images (alpine, etc).

Here is an example docker-compose.yml:

version: '3'

services:
  app:
    build:
      context: .
    command: >
      sh -c "python manage.py wait_for_db &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"

This will call the following commands in order:

  • python manage.py wait_for_db - wait for the DB to be ready
  • python manage.py migrate - run any migrations
  • python manage.py runserver 0.0.0.0:8000 - start my development server

How do I install an R package from source?

Download the source package, open Terminal.app, navigate to the directory where you currently have the file, and then execute:

R CMD INSTALL RJSONIO_0.2-3.tar.gz

Do note that this will only succeed when either: a) the package does not need compilation or b) the needed system tools for compilation are present. See: https://cran.r-project.org/bin/macosx/tools/

Remove all the elements that occur in one list from another

use Set Comprehensions {x for x in l2} or set(l2) to get set, then use List Comprehensions to get list

l2set = set(l2)
l3 = [x for x in l1 if x not in l2set]

benchmark test code:

import time

l1 = list(range(1000*10 * 3))
l2 = list(range(1000*10 * 2))

l2set = {x for x in l2}

tic = time.time()
l3 = [x for x in l1 if x not in l2set]
toc = time.time()
diffset = toc-tic
print(diffset)

tic = time.time()
l3 = [x for x in l1 if x not in l2]
toc = time.time()
difflist = toc-tic
print(difflist)

print("speedup %fx"%(difflist/diffset))

benchmark test result:

0.0015058517456054688
3.968189239501953
speedup 2635.179227x    

Best way to serialize/unserialize objects in JavaScript?

I tried to do this with Date with native JSON...

function stringify (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) {
      if (this[k] instanceof Date) {
        return ['$date', +this[k]]
      }
      return v
    }
  )
}

function clone<T> (obj: T): T {
  return JSON.parse(
    stringify(obj),
    (_, v) => (Array.isArray(v) && v[0] === '$date') ? new Date(v[1]) : v
  )
}

What does this say? It says

  • There needs to be a unique identifier, better than $date, if you want it more secure.
class Klass {
  static fromRepr (repr: string): Klass {
    return new Klass(...)
  }

  static guid = '__Klass__'

  __repr__ (): string {
    return '...'
  }
}

This is a serializable Klass, with

function serialize (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) { return this[k] instanceof Klass ? [Klass.guid, this[k].__repr__()] : v }
  )
}

function deserialize (repr: string) {
  return JSON.parse(
    repr,
    (_, v) => (Array.isArray(v) && v[0] === Klass.guid) ? Klass.fromRepr(v[1]) : v
  )
}

I tried to do it with Mongo-style Object ({ $date }) as well, but it failed in JSON.parse. Supplying k doesn't matter anymore...

BTW, if you don't care about libraries, you can use yaml.dump / yaml.load from js-yaml. Just make sure you do it the dangerous way.

Uploading Images to Server android

Main activity class to take pick and upload

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

How do I open the "front camera" on the Android platform?

All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:

This class was deprecated in API level 21. We recommend using the new android.hardware.camera2 API for new applications.

In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to

String[] getCameraIdList()

and then use obtained CameraId to open the camera:

void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)

99% of the frontal cameras have id = "1", and the back camera id = "0" according to this:

Non-removable cameras use integers starting at 0 for their identifiers, while removable cameras have a unique identifier for each individual device, even if they are the same model.

However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.

I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".

Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html

Explicit Examples: https://github.com/googlesamples/android-Camera2Basic


For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:

cam = Camera.open(1);

If you trust OpenCV to do the camera part:

Inside

    <org.opencv.android.JavaCameraView
    ../>

use the following for the frontal camera:

        opencv:camera_id="1"

Android global variable

There are a few different ways you can achieve what you are asking for.

1.) Extend the application class and instantiate your controller and model objects there.

public class FavoriteColorsApplication extends Application {

    private static FavoriteColorsApplication application;
    private FavoriteColorsService service;

    public FavoriteColorsApplication getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        application.initialize();
    }

    private void initialize() {
        service = new FavoriteColorsService();
    }

    public FavoriteColorsService getService() {
        return service;
    }

}

Then you can call the your singleton from your custom Application object at any time:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();

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

    service = ((FavoriteColorsApplication) getApplication()).getService();
    favoriteColors = service.findAllColors();

    ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
    adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
            favoriteColors);
    lv.setAdapter(adapter);
}

2.) You can have your controller just create a singleton instance of itself:

public class Controller {
    private static final String TAG = "Controller";
    private static sController sController;
    private Dao mDao;

    private Controller() {
        mDao = new Dao();    
    }

    public static Controller create() {
        if (sController == null) {
            sController = new Controller();
        }
        return sController;
    }
}

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

I hope I gave enough detail in regards to how you can do what you are hoping for.

How to get Toolbar from fragment?

From your Fragment: ( get Toolbar from fragment?)

// get toolbar
((MainAcivity)this.getActivity()).getToolbar();  // getToolbar will be method in Activity that returns Toolbar!!  don't use getSupportActionBar for getting toolbar!!
// get action bar
this.getActivity().getSupportActionBar();

this is very helpful when you are using spinner in Toolbar and call the spinner or custom views in Toolbar from a fragment!

From your Activity:

// get toolbar
this.getToolbar();
// get Action Bar
this.getSupportActionBar();

How to extract duration time from ffmpeg output?

You could try this:

/*
* Determine video duration with ffmpeg
* ffmpeg should be installed on your server.
*/
function mbmGetFLVDuration($file){

  //$time = 00:00:00.000 format
  $time =  exec("ffmpeg -i ".$file." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");

  $duration = explode(":",$time);
  $duration_in_seconds = $duration[0]*3600 + $duration[1]*60+ round($duration[2]);

  return $duration_in_seconds;

}

$duration = mbmGetFLVDuration('/home/username/webdir/video/file.mov');
echo $duration;

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

This is an old question, yet I had the same problem when moving from JDK 1.8.0_144 to jdk 1.8.0_191

We found a hint in the changelog:

Changelog

we added the following additional system property, which helped in our case to solve this issue:

-Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

You would have to use the JavascriptExecutor class:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");

In Python, how do I convert all of the items in a list to floats?

I have solve this problem in my program using:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)

html select option SELECTED

foreach($array as $value=>$name)
{
    if($value == $_GET['sel'])
    {
         echo "<option selected='selected' value='".$value."'>".$name."</option>";
    }
    else
    {
         echo "<option value='".$value."'>".$name."</option>";
    }
}

How do I obtain the frequencies of each value in an FFT?

Your kth FFT result's frequency is 2*pi*k/N.

How to view method information in Android Studio?

Macbook: ?J or fnF1 does the same.
Also, use the one from the editor definition as explained above.

How to replace local branch with remote branch entirely in Git?

If you want to update branch that is not currently checked out you can do:

git fetch -f origin rbranch:lbranch

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

How do I measure execution time of a command on the Windows command line?

@echo off & setlocal

set start=%time%

REM Do stuff to be timed here.
REM Alternatively, uncomment the line below to be able to
REM pass in the command to be timed when running this script.
REM cmd /c %*

set end=%time%

REM Calculate time taken in seconds, to the hundredth of a second.
REM Assumes start time and end time will be on the same day.

set options="tokens=1-4 delims=:."

for /f %options% %%a in ("%start%") do (
    set /a start_s="(100%%a %% 100)*3600 + (100%%b %% 100)*60 + (100%%c %% 100)"
    set /a start_hs=100%%d %% 100
)

for /f %options% %%a in ("%end%") do (
    set /a end_s="(100%%a %% 100)*3600 + (100%%b %% 100)*60 + (100%%c %% 100)"
    set /a end_hs=100%%d %% 100
)

set /a s=%end_s%-%start_s%
set /a hs=%end_hs%-%start_hs%

if %hs% lss 0 (
    set /a s=%s%-1
    set /a hs=100%hs%
)
if 1%hs% lss 100 set hs=0%hs%

echo.
echo  Time taken: %s%.%hs% secs
echo.

How to copy files between two nodes using ansible

In 2021 you should install wrapper:

ansible-galaxy collection install ansible.posix

And use

- name: Synchronize two directories on one remote host.
  ansible.posix.synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
  delegate_to: "{{ inventory_hostname }}"

Read more:

https://docs.ansible.com/ansible/latest/collections/ansible/posix/synchronize_module.html

Checked on:

ansible --version                          
ansible 2.10.5
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/daniel/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  executable location = /sbin/ansible
  python version = 3.9.1 (default, Dec 13 2020, 11:55:53) [GCC 10.2.0]

How to make a GridLayout fit screen size

Grid Layout

       <GridLayout
        android:layout_width="match_parent"
        android:layout_weight="3"
        android:columnCount="2"
        android:padding="10dp"
        android:rowCount="3"
        android:background="@drawable/background_down"
        android:layout_height="0dp">


        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/user" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>

        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/addusers" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/newspaper" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Report"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>



        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="5dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/settings" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Settings"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

    </GridLayout>

Full tutorials can be found here .

[Android Grid Layout With CardView and OnItemClickListener][2]

PHP, Get tomorrows date from date

$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);

Where 86400 is the # of seconds in a day.

Get int value from enum in C#

will give you the a list with all the integer values of the enum :

List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();

Why do we need to install gulp globally and locally?

I'm not sure if our problem was directly related with installing gulp only locally. But we had to install a bunch of dependencies ourself. This lead to a "huge" package.json and we are not sure if it is really a great idea to install gulp only locally. We had to do so because of our build environment. But I wouldn't recommend installing gulp not globally if it isn't absolutely necessary. We faced similar problems as described in the following blog-post

None of these problems arise for any of our developers on their local machines because they all installed gulp globally. On the build system we had the described problems. If someone is interested I could dive deeper into this issue. But right now I just wanted to mention that it isn't an easy path to install gulp only locally.

How to download Visual Studio 2017 Community Edition for offline installation?

No, there should be an .exe file (vs_Community_xxxxx.exe) directly in you f:\vs2017c directory !

Just start from the this directory, not from a longer path. the packages downloaded are partly having very long path names, it fails if you start from a longer path.

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

Understanding dict.copy() - shallow or deep?

Contents are shallow copied.

So if the original dict contains a list or another dictionary, modifying one them in the original or its shallow copy will modify them (the list or the dict) in the other.

How to copy a row from one SQL Server table to another

INSERT INTO DestTable
SELECT * FROM SourceTable
WHERE ... 

works in SQL Server

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

I logged in using my username instead of email and it started working.

Difference between HashSet and HashMap?

Basically in HashMap, user has to provide both Key and Value, whereas in HashSet you provide only Value, the Key is derived automatically from Value by using hash function. So after having both Key and Value, HashSet can be stored as HashMap internally.

Operation must use an updatable query. (Error 3073) Microsoft Access

I had a similar problem where the following queries wouldn't work;

update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = (select LGA.LGA_NAME from tbl_Prop_LGA as LGA where LGA.LGA_CODE = LVD.LGCode)
where LVD.LGAName is null;

update tbl_LOT_VALUATION_DETAILS inner join tbl_prop_LGA on tbl_LOT_VALUATION_DETAILS.LGCode = tbl_prop_LGA.LGA_CODE 
set tbl_LOT_VALUATION_DETAILS.LGAName = [tbl_Prop_LGA].[LGA_NAME]
where tbl_LOT_VALUATION_DETAILS.LGAName is null;

However using DLookup resolved the problem;

update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = dlookup("LGA_NAME", "tbl_Prop_LGA", "LGA_CODE="+LVD.LGCode)
where LVD.LGAName is null;

This solution was originally proposed at https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query

Is try-catch like error handling possible in ASP Classic?

the statement On Error Resume Next should be placed on top of what we want to validate.

  On Error Resume Next
  'Your code logic is here

Then end with statement like:

  If Err.Number <> 0 then

  'Your error message goes here'

  End if

How to write to a JSON file in the correct format

To make this work on Ubuntu Linux:

  1. I installed the Ubuntu package ruby-json:

    apt-get install ruby-json
    
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO

  3. $HOME/.bashrc included:

    ${HOME}/rubybin:${PATH}
    

(On this occasion I also typed the above on the bash command line.)

Then it worked when I entered on the command line:

jsonDemo

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

iPhone 5 CSS media query

for me, the query that did the job was:

only screen and (device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)

JavaScript query string

tl;dr solution on a single(ish) line of code using vanilla javascript

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {
    queryDict[item.split("=")[0]] = item.split("=")[1]
})

For querystring ?a=1&b=2&c=3&d&eit returns:

> queryDict
a: "1"
b: "2"
c: "3"
d: undefined
e: undefined

multi-valued keys and encoded characters?

See the original answer at How can I get query string values in JavaScript?

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This answer, but with storyboard support.

class SwipeNavigationController: UINavigationController {

    // MARK: - Lifecycle

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setup()
    }

    private func setup() {
        delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }

    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }

    // MARK: - Overrides

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true

        super.pushViewController(viewController, animated: animated)
    }

    // MARK: - Private Properties

    fileprivate var duringPushAnimation = false
}

jQuery-UI datepicker default date

Try passing in a Date object instead. I can't see why it doesn't work in the format you have entered:

<script type="text/javascript">
$(function() {               
    $("#birthdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1920:2010',
        dateFormat : 'dd-mm-yy',
        defaultDate: new Date(1985, 00, 01)
    });
});
</script>

http://api.jqueryui.com/datepicker/#option-defaultDate

Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Step-by-step:

1) Open the page with old NDK versions:

https://developer.android.com/ndk/downloads/older_releases

enter image description here

2) Agree the Terms:

enter image description here

3) Download the older version of NDK (for example 16b):

enter image description here

4) Open your toolchains directory.

5) Transfer files that you need from toolchains folder of downloaded zip-file to your toolchains folder:

enter image description here

6) Rebuild the Project:

enter image description here


UPD 30 Sep 2018:
I used Android NDK Revision r16b for fix this error in my own case. So I present the example with this version.
But it's better to use the Android NDK, Revision r17c (June 2018). It is the last one, supporting mips (reasonable reccomendation from Weekend's comment).

How do I reverse an int array in Java?

Just for the sake of it. People often do only need a 'view' on an array or list in reversed order instead of a completely do not need a reversed array when working with streams and collections but a 'reversed' view on the original array/collection. , it is best to create a toolkit that has a reverse view on a list / array.

So create your Iterator implementation that takes an array or list and provide the input.

/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
  private int index;
  private final List<T> list;
  public ReverseIterator(List<T> list) {
     this.list = list;
     this.index = list.size() - 1;
  }
  public boolean hasNext() {
    return index >= 0 ? true : false;
  }
  public T next() {
    if(index >= 0) 
      return list.get(index--);
    else 
      throw new NoSuchElementException();
  }
}

An implementation for the array situation is quite similar. Of cause an iterator can be source for a stream or a collection as well.

So not always it is best to create a new array just to provide a reverse view when all you want to do is iterating over the array / list or feed it into a stream or a new collection / array.

How to colorize diff on the command line?

I use grc (Generic Colouriser), which allows you to colour the output of a number of commands including diff.

It is a python script which can be wrapped around any command. So instead of invoking diff file1 file2, you would invoke grc diff file1 file2 to see colourised output. I have aliased diff to grc diff to make it easier.

Figure out size of UILabel based on String in Swift

@IBOutlet weak var constraintTxtV: NSLayoutConstraint!
func TextViewDynamicallyIncreaseSize() {
    let contentSize = self.txtVDetails.sizeThatFits(self.txtVDetails.bounds.size)
    let higntcons = contentSize.height
    constraintTxtV.constant = higntcons
}

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

ActiveRecord OR query

Rails 5 comes with an or method. (link to documentation)

This method accepts an ActiveRecord::Relation object. eg:

User.where(first_name: 'James').or(User.where(last_name: 'Scott'))

Current date and time - Default in MVC razor

Isn't this what default constructors are for?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Static linking vs dynamic linking

Another issue not yet discussed is fixing bugs in the library.

With static linking, you not only have to rebuild the library, but will have to relink and redestribute the executable. If the library is just used in one executable, this may not be an issue. But the more executables that need to be relinked and redistributed, the bigger the pain is.

With dynamic linking, you just rebuild and redistribute the dynamic library and you are done.

How do I get client IP address in ASP.NET CORE?

In my case, I have DotNet Core 2.2 Web App running on DigitalOcean with docker and nginx as reverse proxy. With this code in Startup.cs I can get the client IP

app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All,
            RequireHeaderSymmetry = false,
            ForwardLimit = null,
            KnownNetworks = { new IPNetwork(IPAddress.Parse("::ffff:172.17.0.1"), 104) }
        });

::ffff:172.17.0.1 was the ip that I was getting before using

Request.HttpContext.Connection.RemoteIpAddress.ToString();

Node.js: How to send headers with form data using request module?

I've finally managed to do it. Answer in code snippet below:

var querystring = require('querystring');
var request = require('request');

var form = {
    username: 'usr',
    password: 'pwd',
    opaque: 'opaque',
    logintype: '1'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'http://myUrl',
    body: formData,
    method: 'POST'
  }, function (err, res, body) {
    //it works!
  });

Determining complexity for recursive functions (Big O notation)

We can prove it mathematically which is something I was missing in the above answers.

It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:

  1. T(n) = T(n-1) + 1 It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1) and we now add + 1 because it's the time it takes for the general operations to be completed (except T(n-1)). Now, we are going to find T(n-1) as follow: T(n-1) = T(n-1-1) + 1. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ... instead of T(n-1) inside the method T(n) = ... which will give us: T(n) = T(n-1-1) + 1 + 1 which is T(n) = T(n-2) + 2 or in other words we need to find our missing k: T(n) = T(n-k) + k. The next step is to take n-k and claim that n-k = 1 because at the end of the recursion it will take exactly O(1) when n<=0. From this simple equation we now know that k = n - 1. Let's place k in our final method: T(n) = T(n-k) + k which will give us: T(n) = 1 + n - 1 which is exactly n or O(n).
  2. Is the same as 1. You can test it your self and see that you get O(n).
  3. T(n) = T(n/5) + 1 as before, the time for this method to finish equals to the time the same method but with n/5 which is why it is bounded to T(n/5). Let's find T(n/5) like in 1: T(n/5) = T(n/5/5) + 1 which is T(n/5) = T(n/5^2) + 1. Let's place T(n/5) inside T(n) for the final calculation: T(n) = T(n/5^k) + k. Again as before, n/5^k = 1 which is n = 5^k which is exactly as asking what in power of 5, will give us n, the answer is log5n = k (log of base 5). Let's place our findings in T(n) = T(n/5^k) + k as follow: T(n) = 1 + logn which is O(logn)
  4. T(n) = 2T(n-1) + 1 what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1 which is T(n-1) = 2T(n-2) + 1. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1 which is T(n) = 2^2T(n-2) + 2 that gives us T(n) = 2^kT(n-k) + k. Let's find k by claiming that n-k = 1 which is k = n - 1. Let's place k as follow: T(n) = 2^(n-1) + n - 1 which is roughly O(2^n)
  5. T(n) = T(n-5) + n + 1 It's almost the same as 4 but now we add n because we have one for loop. Let's find T(n-5) = T(n-5-5) + n + 1 which is T(n-5) = T(n - 2*5) + n + 1. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1) which is T(n) = T(n-2*5) + 2n + 2) and for the k: T(n) = T(n-k*5) + kn + k) again: n-5k = 1 which is n = 5k + 1 that is roughly n = k. This will give us: T(n) = T(0) + n^2 + n which is roughly O(n^2).

I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

How can I get the behavior of GNU's readlink -f on a Mac?

  1. Install homebrew
  2. Run "brew install coreutils"
  3. Run "greadlink -f path"

greadlink is the gnu readlink that implements -f. You can use macports or others as well, I prefer homebrew.

Deleting an object in java?

You can remove the reference using null.

Let's say You have class A:

A a = new A();
a=null;

last statement will remove the reference of the object a and that object will be "garbage collected" by JVM. It is one of the easiest ways to do this.

How to set env variable in Jupyter notebook

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. (Use %env by itself to print out current environmental variables.)

See: http://ipython.readthedocs.io/en/stable/interactive/magics.html

How can I start PostgreSQL server on Mac OS X?

This worked for me every time, inspired by Craig Ringer:

brew install proctools
sudo pkill -u postgres

proctools includes pkill. If you don't have Homebrew: https://brew.sh/

Does Spring Data JPA have any way to count entites using method name resolving?

Working example

@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
    List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
    long countByTenantName(String tenantName);
}

Calling from DAO layer

@Override
public long countByTenantName(String tenantName) {
    return repository.countByTenantName(tenantName);
}

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

How to install Visual C++ Build tools?

I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.

enter image description here

I hope it helps save others time!

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Save a file in json format using Notepad++

You can do using a simple notepad and save as FILENAME.json

That's all.

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

Check if a class `active` exist on element with jquery

If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

SwiftUI

in SwiftUI, there is a View called Divider that is perfectly matched for this. You can add it below any view by embedding them into a simple VStack:

VStack {
    Text("This could be any View")
    Divider()
}

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I agree with above answer. But here is another way of CSS compression.

You can concat your CSS by using YUI compressor:

module.exports = function(grunt) {
  var exec = require('child_process').exec;
   grunt.registerTask('cssmin', function() {
    var cmd = 'java -jar -Xss2048k '
      + __dirname + '/../yuicompressor-2.4.7.jar --type css '
      + grunt.template.process('/css/style.css') + ' -o '
      + grunt.template.process('/css/style.min.css')
    exec(cmd, function(err, stdout, stderr) {
      if(err) throw err;
    });
  });
}; 

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

How can I check if character in a string is a letter? (Python)

data = "abcdefg hi j 12345"

digits_count = 0
letters_count = 0
others_count = 0

for i in userinput:

    if i.isdigit():
        digits_count += 1 
    elif i.isalpha():
        letters_count += 1
    else:
        others_count += 1

print("Result:")        
print("Letters=", letters_count)
print("Digits=", digits_count)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');
    }

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    /* Process $content here */

    // Close curl handle
    curl_close($ch);
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);

}

* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

how to download file in react js

tldr; fetch the file from the url, store it as a local Blob, inject a link element into the DOM, and click it to download the Blob

I had a PDF file that was stored in S3 behind a Cloudfront URL. I wanted the user to be able to click a button and immediately initiate a download without popping open a new tab with a PDF preview. Generally, if a file is hosted at a URL that has a different domain that the site the user is currently on, immediate downloads are blocked by many browsers for user security reasons. If you use this solution, do not initiate the file download unless a user clicks on a button to intentionally download.

In order to get by this, I needed to fetch the file from the URL getting around any CORS policies to save a local Blob that would then be the source of the downloaded file. In the code below, make sure you swap in your own fileURL, Content-Type, and FileName.

fetch('https://cors-anywhere.herokuapp.com/' + fileURL, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/pdf',
    },
  })
  .then((response) => response.blob())
  .then((blob) => {
    // Create blob link to download
    const url = window.URL.createObjectURL(
      new Blob([blob]),
    );
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute(
      'download',
      `FileName.pdf`,
    );

    // Append to html link element page
    document.body.appendChild(link);

    // Start download
    link.click();

    // Clean up and remove the link
    link.parentNode.removeChild(link);
  });

This solution references solutions to getting a blob from a URL and using a CORS proxy.

Update As of January 31st, 2021, the cors-anywhere demo hosted on Heroku servers will only allow limited use for testing purposes and cannot be used for production applications. You will have to host your own cors-anywhere server by following cors-anywhere or cors-server.

Substring a string from the end of the string

You can do:

string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);

How to scroll table's "tbody" independent of "thead"?

try this.

table 
{
    background-color: #aaa;
}

tbody 
{
    background-color: #ddd;
    height: 100px;
    overflow-y: scroll;
    position: absolute;
}

td 
{
    padding: 3px 10px;
    color: green;
    width: 100px;
}

How to get javax.comm API?

you can find Java Communications API 2.0 in below link

http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Free c# QR-Code generator

Generate QR Code Image in ASP.NET Using Google Chart API

Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.

var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
                WebResponse response = default(WebResponse);
                Stream remoteStream = default(Stream);
                StreamReader readStream = default(StreamReader);
                WebRequest request = WebRequest.Create(url);
                response = request.GetResponse();
                remoteStream = response.GetResponseStream();
                readStream = new StreamReader(remoteStream);
                System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
                img.Save("D:/QRCode/" + txtCode.Text + ".png");
                response.Close();
                remoteStream.Close();
                readStream.Close();
                txtCode.Text = string.Empty;
                txtWidth.Text = string.Empty;
                txtHeight.Text = string.Empty;
                lblMsg.Text = "The QR Code generated successfully";

Click here for complete source code to download

Demo of application for free QR Code generator using C#

enter image description here

Custom exception type

An alternative to the answer of asselin for use with ES2015 classes

class InvalidArgumentException extends Error {
    constructor(message) {
        super();
        Error.captureStackTrace(this, this.constructor);
        this.name = "InvalidArgumentException";
        this.message = message;
    }
}

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

How can I determine the status of a job?

;WITH CTE_JobStatus
AS (
    SELECT DISTINCT NAME AS [JobName]
        ,s.step_id
        ,s.step_name
        ,CASE 
            WHEN [Enabled] = 1
                THEN 'Enabled'
            ELSE 'Disabled'
            END [JobStatus]
        ,CASE 
            WHEN SJH.run_status = 0
                THEN 'Failed'
            WHEN SJH.run_status = 1
                THEN 'Succeeded'
            WHEN SJH.run_status = 2
                THEN 'Retry'
            WHEN SJH.run_status = 3
                THEN 'Cancelled'
            WHEN SJH.run_status = 4
                THEN 'In Progress'
            ELSE 'Unknown'
            END [JobOutcome]
        ,CONVERT(VARCHAR(8), sjh.run_date) [RunDate]
        ,CONVERT(VARCHAR(8), STUFF(STUFF(CONVERT(TIMESTAMP, RIGHT('000000' + CONVERT(VARCHAR(6), sjh.run_time), 6)), 3, 0, ':'), 6, 0, ':')) RunTime
        ,RANK() OVER (
            PARTITION BY s.step_name ORDER BY sjh.run_date DESC
                ,sjh.run_time DESC
            ) AS rn
        ,SJH.run_status
    FROM msdb..SYSJobs sj
    INNER JOIN msdb..SYSJobHistory sjh ON sj.job_id = sjh.job_id
    INNER JOIN msdb.dbo.sysjobsteps s ON sjh.job_id = s.job_id
        AND sjh.step_id = s.step_id
    WHERE (sj.NAME LIKE 'JOB NAME')
        AND sjh.run_date = CONVERT(CHAR, getdate(), 112)
    )
SELECT *
FROM CTE_JobStatus
WHERE rn = 1
    AND run_status NOT IN (1,4)

What does the PHP error message "Notice: Use of undefined constant" mean?

You missed putting single quotes around your array keys:

$_POST[email]

should be:

$_POST['email']

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

What is this Javascript "require"?

So what is this "require?"

require() is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.

Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include, Python's import, and so on.

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.

  • In browser JavaScript, scripts are added via the <script> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.

  • In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports or module.exports. For a module to access another module's exports or module.exports, it must use require().

In your code, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable.

Why does it work in node but not in a webpage?

require(), module.exports and exports are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.

Also, before I got it to work in node, I had to do npm install pg. What's that about?

NPM is a package repository service that hosts published JavaScript modules. npm install is a command that lets you download packages from their repository.

Where did it put it, and how does Javascript find it?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory.

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

How to get ASCII value of string in C#

If you want the charcode for each character in the string, you could do something like this:

char[] chars = "9quali52ty3".ToCharArray();

Configuring Git over SSH to login once

I had to clone a git repo from a server that did not allow login vie ssh key but only with a user/password. I found no way to configure the Git Plugin to use a simple user/password combination so i added the the following shell command as pre-build step on a linux build machine which depends on the tool expect (apt-get install expect):

THIS IS NOT A GOOD WAY OF SOLVING THIS PROBLEM AS YOUR PASSWORD IS SHOWN AS CLEAR TEXT IN THE CONFIGURATION AND LOGS OF THE JENKINS JOB! ONLY USE IT IF THERE IS NO WAY TO CONFIGURE RSA-KEY AUTHENTIFICATION OR OTHER CONFIGURATION POSSIBILITES!

rm -rf $WORKSPACE &&
expect -c 'set timeout -1; spawn git clone USER@MYHOST:/MYPATH/MYREPO.git $WORKSPACE; expect "password:" {send "MYPASSWORD\r"}; expect eof'

How to send a "multipart/form-data" with requests in python?

You need to use the files parameter to send a multipart form POST request even when you do not need to upload any files.

From the original requests source:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    ...
    :param files: (optional) Dictionary of ``'name': file-like-objects``
        (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
        3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
        where ``'content-type'`` is a string
        defining the content type of the given file
        and ``custom_headers`` a dict-like object 
        containing additional headers to add for the file.

The relevant part is: file-tuple can be a2-tuple, 3-tupleor a4-tuple.

Based on the above, the simplest multipart form request that includes both files to upload and form fields will look like this:

multipart_form_data = {
    'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),
    'action': (None, 'store'),
    'path': (None, '/path1')
}

response = requests.post('https://httpbin.org/post', files=multipart_form_data)

print(response.content)

Note the None as the first argument in the tuple for plain text fields — this is a placeholder for the filename field which is only used for file uploads, but for text fields passing None as the first parameter is required in order for the data to be submitted.

Multiple fields with the same name

If you need to post multiple fields with the same name then instead of a dictionary you can define your payload as a list (or a tuple) of tuples:

multipart_form_data = (
    ('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
    ('action', (None, 'store')),
    ('path', (None, '/path1')),
    ('path', (None, '/path2')),
    ('path', (None, '/path3')),
)

Streaming requests API

If the above API is not pythonic enough for you, then consider using requests toolbelt (pip install requests_toolbelt) which is an extension of the core requests module that provides support for file upload streaming as well as the MultipartEncoder which can be used instead of files, and which also lets you define the payload as a dictionary, tuple or list.

MultipartEncoder can be used both for multipart requests with or without actual upload fields. It must be assigned to the data parameter.

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

multipart_data = MultipartEncoder(
    fields={
            # a file upload field
            'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
            # plain text fields
            'field0': 'value0', 
            'field1': 'value1',
           }
    )

response = requests.post('http://httpbin.org/post', data=multipart_data,
                  headers={'Content-Type': multipart_data.content_type})

If you need to send multiple fields with the same name, or if the order of form fields is important, then a tuple or a list can be used instead of a dictionary:

multipart_data = MultipartEncoder(
    fields=(
            ('action', 'ingest'), 
            ('item', 'spam'),
            ('item', 'sausage'),
            ('item', 'eggs'),
           )
    )

How to get all registered routes in Express?

Just use this npm package, it will give the web-output as well as terminal output in nice formatted table view.

enter image description here

https://www.npmjs.com/package/express-routes-catalogue

How to create checkbox inside dropdown?

You can always use multiple or multiple = "true" option with a select tag, but there is one jquery plugin which makes it more beautiful. It is called chosen and can be found here.

This fiddle-example might help you to get started

Thank you.

PHP Call to undefined function

This was a developer mistake - a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long - problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the "undefined function". That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

How to get previous page url using jquery

    $(document).ready(function() {
               var referrer =  document.referrer;

               if(referrer.equals("Setting.jsp")){                     
                   function goBack() {  
                        window.history.go();                            
                    }
               }  
                   if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){                     
                        window.history.forward();
                        function noBack() {
                        window.history.forward(); 
                    }
                   }
    }); 

using this you can avoid load previous page load

Bootstrap 4, how to make a col have a height of 100%?

Use bootstrap class vh-100 for exp:

<div class="vh-100">

Moment js get first and last day of current month

Assuming you are using a Date range Picker to retrieve the dates. You could do something like to to get what you want.

$('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function (start, end) {
      alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}

How to get a single value from FormGroup

Dot notation will break the type checking, switch to bracket notation. You might also try using the get() method. It also keeps AOT compilation in tact I've read.

this.form.get('controlName').value // safer
this.form.controlName.value // triggers type checking and breaks AOT

Watching variables contents in Eclipse IDE

You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents

Closure in Java 7

Yes,Closure (Lambda Expressions) is the new feature with the upcoming Java SE 8 release. You can get more info about this from the below link: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Foreign key referencing a 2 columns primary key in SQL Server

I had the same problem and I think I have the solution.

If your field Application in table Library has a foreign key that references a field in another table (named Application I would bet), then your field Application in table Library has to have a foreign key to table Application too.

After that you can do your composed foreign key.

Excuse my poor english, and sorry if I'm wrong.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

These are class stereotypes used in analysis.

  • boundary classes are ones at the boundary of the system - the classes that you or other systems interact with

  • entity classes classes are your typical business entities like "person" and "bank account"

  • control classes implement some business logic or other

Parenthesis/Brackets Matching using Stack algorithm

//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))-> 
//Split string to substring {[()]}, next [], next [], next{}

public class testbrackets {
    static String stringfirst;
    static String stringsecond;
    static int open = 0;
    public static void main(String[] args) {
        splitstring("(()){}()");
    }
static void splitstring(String str){

    int len = str.length();
    for(int i=0;i<=len-1;i++){
        stringfirst="";
        stringsecond="";
        System.out.println("loop starttttttt");
        char a = str.charAt(i);
    if(a=='{'||a=='['||a=='(')
    {
        open = open+1;
        continue;
    }
    if(a=='}'||a==']'||a==')'){
        if(open==0){
            System.out.println(open+"started with closing brace");
            return;
        }
        String stringfirst=str.substring(i-open, i);
        System.out.println("stringfirst"+stringfirst);
        String stringsecond=str.substring(i, i+open);
        System.out.println("stringsecond"+stringsecond);
        replace(stringfirst, stringsecond);

        }
    i=(i+open)-1;
    open=0;
    System.out.println(i);
    }
    }
    static void replace(String stringfirst, String stringsecond){
        stringfirst = stringfirst.replace('{', '}');
        stringfirst = stringfirst.replace('(', ')');
        stringfirst = stringfirst.replace('[', ']');
        StringBuilder stringfirst1 = new StringBuilder(stringfirst);
        stringfirst = stringfirst1.reverse().toString();
    System.out.println("stringfirst"+stringfirst);
    System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
    System.out.println("pass");
}
    else{
        System.out.println("fail");
        System.exit(0);
        }
    }
}

How to remove elements from a generic list while iterating over it?

Reverse iteration should be the first thing to come to mind when you want to remove elements from a Collection while iterating over it.

Luckily, there is a more elegant solution than writing a for loop which involves needless typing and can be error prone.

ICollection<int> test = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

foreach (int myInt in test.Reverse<int>())
{
    if (myInt % 2 == 0)
    {
        test.Remove(myInt);
    }
}

How to prevent XSS with HTML/PHP?

Basically you need to use the function htmlspecialchars() whenever you want to output something to the browser that came from the user input.

The correct way to use this function is something like this:

echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

Google Code University also has these very educational videos on Web Security:

Difference between String replace() and replaceAll()

String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular expression with the given replacement.

Laravel redirect back to original destination after login

Laravel 5.2

If you are using a another Middleware like Admin middleware you can set a session for url.intended by using this following:

Basically we need to set manually \Session::put('url.intended', \URL::full()); for redirect.

Example

  if (\Auth::guard($guard)->guest()) {
      if ($request->ajax() || $request->wantsJson()) {
         return response('Unauthorized.', 401);
      } else {
        \Session::put('url.intended', \URL::full());
        return redirect('login');
      }
  }

On login attempt

Make sure on login attempt use return \Redirect::intended('default_path');

How to fix "ImportError: No module named ..." error in Python?

Python does not add the current directory to sys.path, but rather the directory that the script is in. Add /home/bodacydo/work/project to either sys.path or $PYTHONPATH.

How to pass the -D System properties while testing on Eclipse?

run configuration -> arguments -> vm arguments

(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)

C#: Printing all properties of an object

The ObjectDumper class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.

EDIT: I just realized, that the code for ObjectDumper is actually on your machine. Go to:

C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip

This will unzip to a folder called LinqSamples. In there, there's a project called ObjectDumper. Use that.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

This answer covers a lot of ground, so it’s divided into three parts:

  • How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems
  • How to avoid the CORS preflight
  • How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems

If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin header, you can still get things to work—by making the request through a CORS proxy.

You can easily run your own proxy using code from https://github.com/Rob--W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master

After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/.

Now, prefix your request URL with the URL for your proxy:

https://cryptic-headland-94862.herokuapp.com/https://example.com

Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:

  1. Forwards the request to https://example.com.
  2. Receives the response from https://example.com.
  3. Adds the Access-Control-Allow-Origin header to the response.
  4. Passes that response, with that added header, back to the requesting frontend code.

The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.


How to avoid the CORS preflight

The code in the question triggers a CORS preflight—since it sends an Authorization header.

https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Even without that, the Content-Type: application/json header would also trigger a preflight.

What “preflight” means: before the browser tries the POST in the code in the question, it’ll first send an OPTIONS request to the server — to determine if the server is opting-in to receiving a cross-origin POST that has Authorization and Content-Type: application/json headers.

It works pretty well with a small curl script - I get my data.

To properly test with curl, you must emulate the preflight OPTIONS request the browser sends:

curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" \
    -H 'Access-Control-Request-Method: POST' \
    -H 'Access-Control-Request-Headers: Content-Type, Authorization' \
    "https://the.sign_in.url"

…with https://the.sign_in.url replaced by whatever your actual sign_in URL is.

The response the browser needs to see from that OPTIONS request must have headers like this:

Access-Control-Allow-Origin:  http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization

If the OPTIONS response doesn’t include those headers, then the browser will stop right there and never even attempt to send the POST request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.

The server in the question is responding to the OPTIONS request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for OPTIONS requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.

So you’re never going to be able to make POST requests directly to that server from your frontend JavaScript code if the server responds to that OPTIONS request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.

The way to avoid triggering a preflight for the case in the question would be:

  • if the server didn’t require an Authorization request header but instead, e.g., relied on authentication data embedded in the body of the POST request or as a query param
  • if the server didn’t require the POST body to have a Content-Type: application/json media type but instead accepted the POST body as application/x-www-form-urlencoded with a parameter named json (or whatever) whose value is the JSON data

How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

I am getting another error message:

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

For a request that includes credentials, browsers won’t let your frontend JavaScript code access the response if the value of the Access-Control-Allow-Origin response header is *. Instead the value in that case must exactly match your frontend code’s origin, http://127.0.0.1:3000.

See Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.

If you control the server you’re sending the request to, then a common way to deal with this case is to configure the server to take the value of the Origin request header, and echo/reflect that back into the value of the Access-Control-Allow-Origin response header; e.g., with nginx:

add_header Access-Control-Allow-Origin $http_origin

But that’s just an example; other (web) server systems provide similar ways to echo origin values.


I am using Chrome. I also tried using that Chrome CORS Plugin

That Chrome CORS plugin apparently just simplemindedly injects an Access-Control-Allow-Origin: * header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake Access-Control-Allow-Origin response header to the actual origin of your frontend JavaScript code, http://127.0.0.1:3000.

So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using curl -H as above.


As far as the frontend JavaScript code for the fetch(…) request in the question:

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Remove those lines. The Access-Control-Allow-* headers are response headers. You never want to send them in a request. The only effect that’ll have is to trigger a browser to do a preflight.

Android: remove left margin from actionbar's custom layout

Kotlin

    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM;
    supportActionBar?.setCustomView(R.layout.actionbar);

    val parent = supportActionBar?.customView?.parent as Toolbar
    parent?.setPadding(0, 0, 0, 0)//for tab otherwise give space in tab
    parent?.setContentInsetsAbsolute(0, 0)

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

Your x and y values ??are not running so first of all youre begin to write this point

 import numpy as np
 import pandas as pd
 import matplotlib as plt

 dataframe=pd.read_csv(".\datasets\Position_Salaries.csv")

 x=dataframe.iloc[:,1:2].values 
 y=dataframe.iloc[:,2].values    
 x1=dataframe.iloc[:,:-1].values 

point of value have publish

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

How to replace � in a string

Character issues like this are difficult to diagnose because information is easily lost through misinterpretation of characters via application bugs, misconfiguration, cut'n'paste, etc.

As I (and apparently others) see it, you've pasted three characters:

codepoint   glyph   escaped    windows-1252    info
=======================================================================
U+00ef      ï       \u00ef     ef,             LATIN_1_SUPPLEMENT, LOWERCASE_LETTER
U+00bf      ¿       \u00bf     bf,             LATIN_1_SUPPLEMENT, OTHER_PUNCTUATION
U+00bd      ½       \u00bd     bd,             LATIN_1_SUPPLEMENT, OTHER_NUMBER

To identify the character, download and run the program from this page. Paste your character into the text field and select the glyph mode; paste the report into your question. It'll help people identify the problematic character.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

How to remove responsive features in Twitter Bootstrap 3?

I needed to completely remove the Bootstrap responsive feature, i ended up overriding the behavior with the following snippet:

.container {
    width: 960px !important;
}

@media (min-width: 1px) {
  .container {
    max-width: 940px;
  }
  .col-lg-1,
  .col-lg-2,
[...]

Full snippet: https://gist.github.com/ivanminutillo/8557293

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

How to send POST request in JSON using HTTPClient in Android?

Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.

Http http = HttpFactory.create(context);
http.get("http://example.com/users")
    .handler(new ResponseHandler<User[]>() {
        @Override
        public void success(User[] users, HttpResponse response) {
        }
    }).execute();

Recover from git reset --hard?

If you had a IDE open with the same code, try doing a ctrl+z on each individual file that you have made changes to. It helped me recover my uncommited changes after doing git reset --hard.

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

How do I set up HttpContent for my HttpClient PostAsync second parameter?

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});

Can Mysql Split a column?

Usually substring_index does what you want:

mysql> select substring_index("[email protected]","@",-1);
+-----------------------------------------+
| substring_index("[email protected]","@",-1) |
+-----------------------------------------+
| gmail.com                               |
+-----------------------------------------+
1 row in set (0.00 sec)

How to use sed/grep to extract text between two words?

The accepted answer does not remove text that could be before Here or after String. This will:

sed -e 's/.*Here\(.*\)String.*/\1/'

The main difference is the addition of .* immediately before Here and after String.

How to define an empty object in PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

adding comment in .properties files

Writing the properties file with multiple comments is not supported. Why ?

PropertyFile.java

public class PropertyFile extends Task {

    /* ========================================================================
     *
     * Instance variables.
     */

    // Use this to prepend a message to the properties file
    private String              comment;

    private Properties          properties;

The ant property file task is backed by a java.util.Properties class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties class to save into the file.

The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment> elements.

Truncate all tables in a MySQL database in one command?

We can write a bash script like below

truncate_tables_in_mysql() {
    type mysql >/dev/null 2>&1 && echo "MySQL present." || sudo apt-get install -y mysql-client
    
    tables=$(mysql -h 127.0.0.1 -P $MYSQL_PORT -u $MYSQL_USER  -p$MYSQL_PASSWORD -e "USE $BACKEND_DATABASE;    
SHOW TABLES;")
    tables_list=($tables)
    
    query_string="USE $BACKEND_DATABASE; SET FOREIGN_KEY_CHECKS = 0;"
    for table in "${tables_list[@]:1}"
    do
        query_string="$query_string TRUNCATE TABLE \`$table\`; "
    done
    query_string="$query_string SET FOREIGN_KEY_CHECKS = 1;"
    
    mysql -h 127.0.0.1 -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e "$query_string"
}

You can replace env variables with your MySQL details. Using one command you can truncate all the tables in a DB.

How to pass data to all views in Laravel 5?

The documentation is here https://laravel.com/docs/5.4/views#view-composers but i will break it down 1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content

How to get char from string by index?

This should further clarify the points:

a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
    print str1[a]
else:
    print('Index overflow')

Input 3 Output m

Input -3 Output p

Create HTTP post request and receive response using C# console application

For this you can simply use the "HttpWebRequest" and "HttpWebResponse" classes in .net.

Below is a sample console app I wrote to demonstrate how easy this is.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "www.somewhere.com";       
            string fileName = @"C:\output.file";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 5000;

            try
            {
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] bytes = ReadFully(response.GetResponseStream());

                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (WebException)
            {
                Console.WriteLine("Error Occured");
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

Enjoy!

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

To easily understand the problem, imagine we wrote this code:

static void Main(string[] args)
{
    string[] test = new string[3];
    test[0]= "hello1";
    test[1]= "hello2";
    test[2]= "hello3";

    for (int i = 0; i <= 3; i++)
    {
        Console.WriteLine(test[i].ToString());
    }
}

Result will be:

hello1
hello2
hello3

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.

Linking a UNC / Network drive on an html page

Setup IIS on the network server and change the path to http://server/path/to/file.txt

EDIT: Make sure you enable directory browsing in IIS

NSArray + remove item from array

Made a category like mxcl, but this is slightly faster.

My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

- (NSArray *)prefix_arrayByRemovingObject:(id)object 
{
    if (!object) {
        return self;
    }

    NSUInteger indexOfObject = [self indexOfObject:object];
    NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
    NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
    NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];

    return newArray;
}

Calculate median in c#

Math.NET is an opensource library that offers a method for calculating the Median. The nuget package is called MathNet.Numerics.

The usage is pretty simple:

using MathNet.Numerics.Statistics;

IEnumerable<double> data;
double median = data.Median();

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

How do you install Boost on MacOS?

Fink appears to have a full set of Boost packages...

With fink installed and running just do

fink install boost1.35.nopython

at the terminal and accept the dependencies it insists on. Or use

fink list boost

to get a list of different packages that are availible.

I can't find my git.exe file in my Github folder

As of version 2.10.1, here is the path -

C:\Users\usersam\AppData\Local\Programs\Git\cmd\git.exe

How to remove indentation from an unordered list item?

Live demo: https://jsfiddle.net/h8uxmoj4/

ol, ul {
  padding-left: 0;
}

li {
  list-style: none;
  padding-left: 1.25rem;
  position: relative;
}

li::before {
  left: 0;
  position: absolute;
}

ol {
  counter-reset: counter;
}

ol li::before {
  content: counter(counter) ".";
  counter-increment: counter;
}

ul li::before {
  content: "?";
}

Since the original question is unclear about its requirements, I attempted to solve this problem within the guidelines set by other answers. In particular:

  • Align list bullets with outside paragraph text
  • Align multiple lines within the same list item

I also wanted a solution that didn't rely on browsers agreeing on how much padding to use. I've added an ordered list for completeness.

Set object property using reflection

You can try this out when you want to mass-assign properties of an Object from another Object using Property names:

public static void Assign(this object destination, object source)
    {
        if (destination is IEnumerable && source is IEnumerable)
        {
            var dest_enumerator = (destination as IEnumerable).GetEnumerator();
            var src_enumerator = (source as IEnumerable).GetEnumerator();
            while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
                dest_enumerator.Current.Assign(src_enumerator.Current);
        }
        else
        {
            var destProperties = destination.GetType().GetProperties();
            foreach (var sourceProperty in source.GetType().GetProperties())
            {
                foreach (var destProperty in destProperties)
                {
                    if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        destProperty.SetValue(destination,     sourceProperty.GetValue(source, new object[] { }), new object[] { });
                        break;
            }
        }
    }
}

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

How to get input field value using PHP

function get_input_tags($html)
{
    $post_data = array();

    // a new dom object
    $dom = new DomDocument; 

    //load the html into the object
    $dom->loadHTML($html); 
    //discard white space
    $dom->preserveWhiteSpace = false; 

    //all input tags as a list
    $input_tags = $dom->getElementsByTagName('input'); 

    //get all rows from the table
    for ($i = 0; $i < $input_tags->length; $i++) 
    {
        if( is_object($input_tags->item($i)) )
        {
            $name = $value = '';
            $name_o = $input_tags->item($i)->attributes->getNamedItem('name');
            if(is_object($name_o))
            {
                $name = $name_o->value;

                $value_o = $input_tags->item($i)->attributes->getNamedItem('value');
                if(is_object($value_o))
                {
                    $value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
                }

                $post_data[$name] = $value;
            }
        }
    }

    return $post_data; 
}

error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");

print_r(get_input_tags($html));

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

align divs to the bottom of their container

You can cheat! Say your div is 20px high, place the div at the top of the next container and set

position: absolute;
top: -20px;

It may not be semantically clean but does scale with responsive designs

How can I check if a file exists in Perl?

You can use: if(-e $base_path)

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

here is your answer

String userName = "xxxx";
    String password = "xxxx";
    String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";

    try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            connection = DriverManager.getConnection(url, userName, password); 

  } catch (Exception e)
  {
     e.printStackTrace();
  }

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

Truncating long strings with CSS: feasible yet?

Another solution to the problem could be the following set of CSS rules:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.

My two cents. Hats off to the original technique by Justin Maxwell

How do I initialize the base (super) class?

How do I initialize the base (super) class?

class SuperClass(object):
    def __init__(self, x):
        self.x = x

class SubClass(SuperClass):
    def __init__(self, y):
        self.y = y

Use a super object to ensure you get the next method (as a bound method) in the method resolution order. In Python 2, you need to pass the class name and self to super to lookup the bound __init__ method:

 class SubClass(SuperClass):
      def __init__(self, y):
          super(SubClass, self).__init__('x')
          self.y = y

In Python 3, there's a little magic that makes the arguments to super unnecessary - and as a side benefit it works a little faster:

 class SubClass(SuperClass):
      def __init__(self, y):
          super().__init__('x')
          self.y = y

Hardcoding the parent like this below prevents you from using cooperative multiple inheritance:

 class SubClass(SuperClass):
      def __init__(self, y):
          SuperClass.__init__(self, 'x') # don't do this
          self.y = y

Note that __init__ may only return None - it is intended to modify the object in-place.

Something __new__

There's another way to initialize instances - and it's the only way for subclasses of immutable types in Python. So it's required if you want to subclass str or tuple or another immutable object.

You might think it's a classmethod because it gets an implicit class argument. But it's actually a staticmethod. So you need to call __new__ with cls explicitly.

We usually return the instance from __new__, so if you do, you also need to call your base's __new__ via super as well in your base class. So if you use both methods:

class SuperClass(object):
    def __new__(cls, x):
        return super(SuperClass, cls).__new__(cls)
    def __init__(self, x):
        self.x = x

class SubClass(object):
    def __new__(cls, y):
        return super(SubClass, cls).__new__(cls)

    def __init__(self, y):
        self.y = y
        super(SubClass, self).__init__('x')

Python 3 sidesteps a little of the weirdness of the super calls caused by __new__ being a static method, but you still need to pass cls to the non-bound __new__ method:

class SuperClass(object):
    def __new__(cls, x):
        return super().__new__(cls)
    def __init__(self, x):
        self.x = x

class SubClass(object):
    def __new__(cls, y):
        return super().__new__(cls)
    def __init__(self, y):
        self.y = y
        super().__init__('x')

When should an IllegalArgumentException be thrown?

Any API should check the validity of the every parameter of any public method before executing it:

void setPercentage(int pct, AnObject object) {
    if( pct < 0 || pct > 100) {
        throw new IllegalArgumentException("pct has an invalid value");
    }
    if (object == null) {
        throw new IllegalArgumentException("object is null");
    }
}

They represent 99.9% of the times errors in the application because it is asking for impossible operations so in the end they are bugs that should crash the application (so it is a non recoverable error).

In this case and following the approach of fail fast you should let the application finish to avoid corrupting the application state.

OrderBy pipe issue

I've created an OrderBy pipe that does just what you need. It supports being able to sort on multiple columns of an enumerable of objects as well.

<li *ngFor="#todo in todos | orderBy : ['completed']">{{todo.name}} {{todo.completed}}</li>

This pipe does allow for adding more items to the array after rendering the page, and will sort the array with the updates dynamically.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

Current time formatting with Javascript

There are many great libraries out there, for those interested

There really shouldn't be a need these days to invent your own formatting specifiers.

Is there a "previous sibling" selector?

Don't think there's a similar answer here so try this. Assuming HTML of:

<ul>
  <li>before</li>
  <li class="target">target</li>
  <li>after</li>
  <li>after</li>
</ul>

Add a style to all the children, then undo the style to the target, and sibling children of your target.

ul > li { color: red; }
ul > li.target, ul > li.target ~ li { color: inherit; }

What's the simplest way to list conflicted files in Git?

Utility git wizard https://github.com/makelinux/git-wizard counts separately unresolved conflicted changes (collisions) and unmerged files. Conflicts must be resolved manually or with mergetool. Resolved unmerged changes can me added and committed usually with git rebase --continue.

Ansible - Save registered variable to file

Thanks to tmoschou for adding this comment to an outdated accepted answer:

As of Ansible 2.10, The documentation for ansible.builtin.copy says: 

If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.

For more details see this and an explanation


Original answer:

You can use the copy module, with the parameter content=.

I gave the exact same answer here: Write variable to a file in Ansible

In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action notation:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

CSS, Images, JS not loading in IIS

Add this to your web.config

<location path="Images">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

How to search file text for a pattern and replace it with a given value

There isn't really a way to edit files in-place. What you usually do when you can get away with it (i.e. if the files are not too big) is, you read the file into memory (File.read), perform your substitutions on the read string (String#gsub) and then write the changed string back to the file (File.open, File#write).

If the files are big enough for that to be unfeasible, what you need to do, is read the file in chunks (if the pattern you want to replace won't span multiple lines then one chunk usually means one line - you can use File.foreach to read a file line by line), and for each chunk perform the substitution on it and append it to a temporary file. When you're done iterating over the source file, you close it and use FileUtils.mv to overwrite it with the temporary file.

How to change the DataTable Column Name?

try this

"columns": [
{data: "id", name: "aaa", sortable: false},
{data: "userid", name: "userid", sortable: false},
{data: "group_id", name: "group_id", sortable: false},
{data: "group_name", name: "group_name", sortable: false},
{data: "group_member", name: "group_member"},
{data: "group_fee", name: "group_fee"},
{data: "dynamic_type", name: "dynamic_type"},
{data: "dynamic_id", name: "dynamic_id"},
{data: "content", name: "content", sortable: false},
{data: "images", name: "images", sortable: false},
{data: "money", name: "money"},
{data: "is_audit", name: "is_audit", sortable: false},
{data: "audited_at", name: "audited_at", sortable: false}

]

enter image description here

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

Send form data using ajax

you can use serialize method of jquery to get form values. Try like this

<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form) " >
</form>

function f( form ){
    var formData = $(form).serialize();
    att=form.attr("action") ;
    $.post(att, formData).done(function(data){
        alert(data);
    });
    return true;
}

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

What's the difference between a word and byte?

In this context, a word is the unit that a machine uses when working with memory. For example, on a 32 bit machine, the word is 32 bits long and on a 64 bit is 64 bits long. The word size determines the address space.

In programming (C/C++), the word is typically represented by the int_ptr type, which has the same length as a pointer, this way abstracting these details.

Some APIs might confuse you though, such as Win32 API, because it has types such as WORD (16 bits) and DWORD (32 bits). The reason is that the API was initially targeting 16 bit machines, then was ported to 32 bit machines, then to 64 bit machines. To store a pointer, you can use INT_PTR. More details here and here.

What is the difference between const int*, const int * const, and int const *?

It's simple but tricky. Please note that we can swap the const qualifier with any data type (int, char, float, etc.).

Let's see the below examples.


const int *p ==> *p is read-only [p is a pointer to a constant integer]

int const *p ==> *p is read-only [p is a pointer to a constant integer]


int *p const ==> Wrong Statement. Compiler throws a syntax error.

int *const p ==> p is read-only [p is a constant pointer to an integer]. As pointer p here is read-only, the declaration and definition should be in same place.


const int *p const ==> Wrong Statement. Compiler throws a syntax error.

const int const *p ==> *p is read-only

const int *const p1 ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.


int const *p const ==> Wrong Statement. Compiler throws a syntax error.

int const int *p ==> Wrong Statement. Compiler throws a syntax error.

int const const *p ==> *p is read-only and is equivalent to int const *p

int const *const p ==> *p and p are read-only [p is a constant pointer to a constant integer]. As pointer p here is read-only, the declaration and definition should be in same place.

how to set default main class in java?

Assuming your my.jar has a class1 and class2 with a main defined in each, you can just call java like this:

java my.jar class1

java my.jar class2

If you need to specify other options to java just make sure they are before the my.jar

java -classpath my.jar class1

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

How do I measure a time interval in C?

On Linux you can use clock_gettime():

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp

// ... do stuff ... //

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);   // get final time-stamp

double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
              (double)(end.tv_nsec - start.tv_nsec);
                                                 // subtract time-stamps and
                                                 // multiply to get elapsed
                                                 // time in ns

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

What is the difference between single and double quotes in SQL?

I use this mnemonic:

  • Single quotes are for strings (one thing)
  • Double quotes are for tables names and column names (two things)

This is not 100% correct according to the specs, but this mnemonic helps me (human being).

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You are facing a double-encoding issue.

¦ and &#8226; are absolutely equivalent to each other. Both refer to the Unicode character 'BULLET' (U+2022) and can exist side-by-side in HTML source code.

However, if that source-code is HTML-encoded again at some point, it will contain ¦ and &amp;#8226;. The former is rendered unchanged, the latter will come out as "&#8226;" on the screen.

This is correct behavior under these circumstances. You need to find the point where the superfluous second HTML-encoding occurs and get rid of it.

UITableview: How to Disable Selection for Some Rows but Not Others

Starting in iOS 6, you can use

-tableView:shouldHighlightRowAtIndexPath:

If you return NO, it disables both the selection highlighting and the storyboard triggered segues connected to that cell.

The method is called when a touch comes down on a row. Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.

UITableViewDelegate Protocol Reference

What's the difference between session.persist() and session.save() in Hibernate?

Here is the difference:

  1. save:

    1. will return the id/identifier when the object is saved to the database.
    2. will also save when the object is tried to do the same by opening a new session after it is detached.
  2. Persist:

    1. will return void when the object is saved to the database.
    2. will throw PersistentObjectException when tried to save the detached object through a new session.

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

Commenting out a set of lines in a shell script

This Perl one-liner comments out lines 1 to 3 of the file orig.sh inclusive (where the first line is numbered 0), and writes the commented version to cmt.sh.

perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

Obviously you can change the boundary numbers as required.

If you want to edit the file in place, it's even shorter:

perl -in -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh

Demo

$ cat orig.sh 
a
b
c
d
e
f

$ perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

$ cat cmt.sh 
a
#b
#c
#d
e
f

Java: int[] array vs int array[]

From JLS http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#10.2

Here are examples of declarations of array variables that do not create arrays:

int[ ] ai;          // array of int
short[ ][ ] as;         // array of array of short
Object[ ]   ao,     // array of Object
        otherAo;    // array of Object
Collection<?>[ ] ca;        // array of Collection of unknown type
short       s,      // scalar short 
        aas[ ][ ];  // array of array of short

Here are some examples of declarations of array variables that create array objects:

Exception ae[ ] = new Exception[3]; 
Object aao[ ][ ] = new Exception[2][3];
int[ ] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[ ] = { 'n', 'o', 't', ' ', 'a', ' ',
                 'S', 't', 'r', 'i', 'n', 'g' }; 
String[ ] aas = { "array", "of", "String", };

The [ ] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[ ] rowvector, colvector, matrix[ ];

This declaration is equivalent to:

byte rowvector[ ], colvector[ ], matrix[ ][ ];

Firefox "ssl_error_no_cypher_overlap" error

I've had the same problem; to solve was enough to enable all the SSL schemas in "about:config". I was finding them by filtering with ssl. First I anabled all options for afret disabling the unnecessary ones.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.