Programs & Examples On #Initializer

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

static constructors in C++? I need to initialize private static objects

I guess Simple solution to this will be:

    //X.h
    #pragma once
    class X
    {
    public:
            X(void);
            ~X(void);
    private:
            static bool IsInit;
            static bool Init();
    };

    //X.cpp
    #include "X.h"
    #include <iostream>

    X::X(void)
    {
    }


    X::~X(void)
    {
    }

    bool X::IsInit(Init());
    bool X::Init()
    {
            std::cout<< "ddddd";
            return true;
    }

    // main.cpp
    #include "X.h"
    int main ()
    {
            return 0;
    }

Static class initializer in PHP

Sounds like you'd be better served by a singleton rather than a bunch of static methods

class Singleton
{
  /**
   * 
   * @var Singleton
   */
  private static $instance;

  private function __construct()
  {
    // Your "heavy" initialization stuff here
  }

  public static function getInstance()
  {
    if ( is_null( self::$instance ) )
    {
      self::$instance = new self();
    }
    return self::$instance;
  }

  public function someMethod1()
  {
    // whatever
  }

  public function someMethod2()
  {
    // whatever
  }
}

And then, in usage

// As opposed to this
Singleton::someMethod1();

// You'd do this
Singleton::getInstance()->someMethod1();

C++: constructor initializer for arrays

This seems to work, but I'm not convinced it's right:

#include <iostream>

struct Foo { int x; Foo(int x): x(x) { } };

struct Baz { 
     Foo foo[3];

    static int bar[3];
     // Hmm...
     Baz() : foo(bar) {}
};

int Baz::bar[3] = {4, 5, 6};

int main() {
    Baz z;
    std::cout << z.foo[1].x << "\n";
}

Output:

$ make arrayinit -B CXXFLAGS=-pedantic && ./arrayinit
g++ -pedantic    arrayinit.cpp   -o arrayinit
5

Caveat emptor.

Edit: nope, Comeau rejects it.

Another edit: This is kind of cheating, it just pushes the member-by-member array initialization to a different place. So it still requires Foo to have a default constructor, but if you don't have std::vector then you can implement for yourself the absolute bare minimum you need:

#include <iostream>

struct Foo { 
    int x; 
    Foo(int x): x(x) { }; 
    Foo(){}
};

// very stripped-down replacement for vector
struct Three { 
    Foo data[3]; 
    Three(int d0, int d1, int d2) {
        data[0] = d0;
        data[1] = d1;
        data[2] = d2;
    }
    Foo &operator[](int idx) { return data[idx]; }
    const Foo &operator[](int idx) const { return data[idx]; }
};

struct Baz { 
    Three foo;

    static Three bar;
    // construct foo using the copy ctor of Three with bar as parameter.
    Baz() : foo(bar) {}
    // or get rid of "bar" entirely and do this
    Baz(bool) : foo(4,5,6) {}
};

Three Baz::bar(4,5,6);

int main() {
    Baz z;
    std::cout << z.foo[1].x << "\n";
}

z.foo isn't actually an array, but it looks about as much like one as a vector does. Adding begin() and end() functions to Three is trivial.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

Converting String Array to an Integer Array

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

How to detect if numpy is installed

The traditional method for checking for packages in Python is "it's better to beg forgiveness than ask permission", or rather, "it's better to catch an exception than test a condition."

try:
    import numpy
    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

What is the meaning of prepended double colon "::"?

"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.

A child container failed during start java.util.concurrent.ExecutionException

I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.

1.Class

@WebServlet("/display")
public class MyFirst extends HttpServlet {

2.Class

@WebServlet("/display")
public class MySecond extends HttpServlet {

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

How to get CRON to call in the correct PATHs

Adding a PATH definition into the user crontab with correct values will help... I've filled mine with this line on top (after comments, and before cron jobs):

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

And it's enough to get all my scripts working... Include any custom path there if you need to.

How to handle the new window in Selenium WebDriver using Java?

                string BaseWindow = driver.CurrentWindowHandle;
                ReadOnlyCollection<string> handles = driver.WindowHandles;
                foreach (string handle in handles)
                {
                    if (handle != BaseWindow)
                    {
                        string title = driver.SwitchTo().Window(handle).Title;
                        Thread.Sleep(3000);
                        driver.SwitchTo().Window(handle).Title.Equals(title);
                        Thread.Sleep(3000);
                    }
                }

rmagick gem install "Can't find Magick-config"

Things change...maybe this will help someone else:

sudo apt-get install libmagick9-dev used to work. But with a later version of imagemagick I needed:

sudo apt-get install graphicsmagick-libmagick-dev-compat libmagickcore-dev libmagickwand-dev

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

How to get a List<string> collection of values from app.config in WPF?

You can create your own custom config section in the app.config file. There are quite a few tutorials around to get you started. Ultimately, you could have something like this:

<configSections>
    <section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
  </configSections>

<backupDirectories>
   <directory location="C:\test1" />
   <directory location="C:\test2" />
   <directory location="C:\test3" />
</backupDirectories>

To complement Richard's answer, this is the C# you could use with his sample configuration:

using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace TestReadMultipler2343
{
    public class BackupDirectoriesSection : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            List<directory> myConfigObject = new List<directory>();

            foreach (XmlNode childNode in section.ChildNodes)
            {
                foreach (XmlAttribute attrib in childNode.Attributes)
                {
                    myConfigObject.Add(new directory() { location = attrib.Value });
                }
            }
            return myConfigObject;
        }
    }

    public class directory
    {
        public string location { get; set; }
    }
}

Then you can access the backupDirectories configuration section as follows:

List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;

Round button with text and icon in flutter

You can do something like,

RaisedButton.icon( elevation: 4.0,
                    icon: Image.asset('images/image_upload.png' ,width: 20,height: 20,) ,
                      color: Theme.of(context).primaryColor,
                    onPressed: getImage,
                    label: Text("Add Team Image",style: TextStyle(
                        color: Colors.white, fontSize: 16.0))
                  ),

Trigger 404 in Spring-MVC controller?

If your controller method is for something like file handling then ResponseEntity is very handy:

@Controller
public class SomeController {
    @RequestMapping.....
    public ResponseEntity handleCall() {
        if (isFound()) {
            return new ResponseEntity(...);
        }
        else {
            return new ResponseEntity(404);
        }
    }
}

How do I compile with -Xlint:unchecked?

other way to compile using -Xlint:unchecked through command line

javac abc.java -Xlint:unchecked

it will show the unchecked and unsafe warnings.

Setting the default Java character encoding

I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding. It's always best to explicitly specify the desired encoding (i.e. "UTF-8") in your code. That way, you know it will work even across different systems and JVM configurations.

'ssh' is not recognized as an internal or external command

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

A valid provisioning profile for this executable was not found... (again)

I have spent about a week solving this problem. Most of the answers are sort of magic (no logical purposes for these algorithms) and they were not useful for me. I found this error in Xcode console:

ERROR ITMS-90174: "Missing Provisioning Profile - iOS Apps must contain a provisioning profile in a file named embedded.mobileprovision."

And found this answer solving this issue. The case is to switch Xcode Build system to the Legacy one.

I was deploying my Ionic app.

CSS white space at bottom of page despite having both min-height and height tag

The problem is how 100% height is being calculated. Two ways to deal with this.

Add 20px to the body padding-bottom

body {
    padding-bottom: 20px;
}

or add a transparent border to body

body {
    border: 1px solid transparent;
}

Both worked for me in firebug

In defense of this answer

Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.

Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.

Thirtydot's answer is completely legit. The p around the script is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.

But why? Shouldn't the p tag's height, padding and margin be calculated into the height of the body?

And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.

The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.

In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.

Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.

My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.

phantomjs not waiting for "full" page load

Do Mouse move while page is loading should work.

 page.sendEvent('click',200, 660);

do { phantom.page.sendEvent('mousemove'); } while (page.loading);

UPDATE

When submitting the form, nothing was returned, so the program stopped. The program did not wait for the page to load as it took a few seconds for the redirect to begin.

telling it to move the mouse until the URL changes to the home page gave the browser as much time as it needed to change. then telling it to wait for the page to finish loading allowed the page to full load before the content was grabbed.

page.evaluate(function () {
document.getElementsByClassName('btn btn-primary btn-block')[0].click();
});
do { phantom.page.sendEvent('mousemove'); } while (page.evaluate(function()
{
return document.location != "https://www.bestwaywholesale.co.uk/";
}));
do { phantom.page.sendEvent('mousemove'); } while (page.loading);

Implementing two interfaces in a class with same method. Which interface method is overridden?

There is nothing to identify. Interfaces only proscribe a method name and signature. If both interfaces have a method of exactly the same name and signature, the implementing class can implement both interface methods with a single concrete method.

However, if the semantic contracts of the two interface method are contradicting, you've pretty much lost; you cannot implement both interfaces in a single class then.

What are .a and .so files?

Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.

The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.

This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

Hope this helps.

How do I edit an incorrect commit message in git ( that I've pushed )?

At our shop, I introduced the convention of adding recognizably named annotated tags to commits with incorrect messages, and using the annotation as the replacement.

Even though this doesn't help folks who run casual "git log" commands, it does provide us with a way to fix incorrect bug tracker references in the comments, and all my build and release tools understand the convention.

This is obviously not a generic answer, but it might be something folks can adopt within specific communities. I'm sure if this is used on a larger scale, some sort of porcelain support for it may crop up, eventually...

How to install Guest addition in Mac OS as guest and Windows machine as host

Before you start, close VirtualBox! After those manipulations start VB as Administrator!


  1. Run CMD as Administrator
  2. Use lines below one by one:
  • cd "C:\Program Files\Oracle\Virtualbox"
  • VBoxManage setextradata “macOS_Catalina” VBoxInternal2/EfiGraphicsResolution 1920x1080

Screen Resolutions: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900

Description:

  • macOS_Catalina - insert your VB machine name.

  • 1920x1080 - put here your Screen Resolution.

Cheers!

How to get StackPanel's children to fill maximum space downward?

It sounds like you want a StackPanel where the final element uses up all the remaining space. But why not use a DockPanel? Decorate the other elements in the DockPanel with DockPanel.Dock="Top", and then your help control can fill the remaining space.

XAML:

<DockPanel Width="200" Height="200" Background="PowderBlue">
    <TextBlock DockPanel.Dock="Top">Something</TextBlock>
    <TextBlock DockPanel.Dock="Top">Something else</TextBlock>
    <DockPanel
        HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" 
        Height="Auto" 
        Margin="10">

      <GroupBox 
        DockPanel.Dock="Right" 
        Header="Help" 
        Width="100" 
        Background="Beige" 
        VerticalAlignment="Stretch" 
        VerticalContentAlignment="Stretch" 
        Height="Auto">
        <TextBlock Text="This is the help that is available on the news screen." 
                   TextWrapping="Wrap" />
     </GroupBox>

      <StackPanel DockPanel.Dock="Left" Margin="10" 
           Width="Auto" HorizontalAlignment="Stretch">
          <TextBlock Text="Here is the news that should wrap around." 
                     TextWrapping="Wrap"/>
      </StackPanel>
    </DockPanel>
</DockPanel>

If you are on a platform without DockPanel available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:

<Grid Width="200" Height="200" Background="PowderBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
        <TextBlock>Something</TextBlock>
        <TextBlock>Something else</TextBlock>
    </StackPanel>
    <Grid Height="Auto" Grid.Row="1" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Width="100"
            Height="Auto"
            Grid.Column="1"
            Background="Beige"
            Header="Help">
            <TextBlock Text="This is the help that is available on the news screen." 
              TextWrapping="Wrap"/>
        </GroupBox>
        <StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
            <TextBlock Text="Here is the news that should wrap around." 
              TextWrapping="Wrap"/>
        </StackPanel>
    </Grid>
</Grid>

How to clear react-native cache?

For React Native Init approach (without expo) use:

npm start -- --reset-cache

Retrieving the output of subprocess.call()

I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:

import shlex
from subprocess import Popen, PIPE

def get_exitcode_stdout_stderr(cmd):
    """
    Execute the external command and get its exitcode, stdout and stderr.
    """
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode
    #
    return exitcode, out, err

cmd = "..."  # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)

I also have a blog post on it here.

Edit: the solution was updated to a newer one that doesn't need to write to temp. files.

How to have click event ONLY fire on parent DIV, not children?

I had the same problem and came up with this solution (based on the other answers)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }

How to test whether a service is running from the command line

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end

How to ALTER multiple columns at once in SQL Server

This is not possible. You will need to do this one by one. You could:

  1. Create a Temporary Table with your modified columns in
  2. Copy the data across
  3. Drop your original table (Double check before!)
  4. Rename your Temporary Table to your original name

Setting up Gradle for api 26 (Android)

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:recyclerview-v7:26.0.1'
    compile 'com.android.support:cardview-v7:26.0.1'

Array definition in XML?

Once I've seen such an interesting construction:

<Ids xmlns:id="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <id:int>1787</id:int>
</Ids>

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In newer versions of Git for Windows, Bash is started with --login which causes Bash to not read .bashrc directly. Instead it reads .bash_profile.

If this file does not exist, create it with the following content:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

This will cause Bash to read the .bashrc file. From my understanding of this issue, Git for Windows should do this automatically. However, I just installed version 2.5.1, and it did not.

How to select an item from a dropdown list using Selenium WebDriver with java?

public class checkBoxSel {

    public static void main(String[] args) {

         WebDriver driver = new FirefoxDriver();
         EventFiringWebDriver dr = null ;


         dr = new EventFiringWebDriver(driver);
         dr.get("http://www.google.co.in/");

         dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

         dr.findElement(By.linkText("Gmail")).click() ;

         Select sel = new Select(driver.findElement(By.tagName("select")));
         sel.selectByValue("fil");

    }

}

I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.

Is Safari on iOS 6 caching $.ajax results?

While adding cache-buster parameters to make the request look different seems like a solid solution, I would advise against it, as it would hurt any application that relies on actual caching taking place. Making the APIs output the correct headers is the best possible solution, even if that's slightly more difficult than adding cache busters to the callers.

Android Closing Activity Programmatically

finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.

SQL ROWNUM how to return rows between a specific range

You can also do using CTE with clause.

WITH maps AS (Select ROW_NUMBER() OVER (ORDER BY Id) AS rownum,* 
from maps006 )

SELECT rownum, * FROM maps  WHERE rownum >49 and rownum <101  

What is the difference between the dot (.) operator and -> in C++?

The simplest difference between the two is that "->" dereferences a pointer before it goes to look at that objects fields, function etc. whereas "." doesn't dereference first. Use "->" when you have a pointer to an object, and use "." when you're working with the actual instance of an object.

Another equivalent way of wrinting this might be to use the dereferencing "*" on the pointer first and then just use the ".". We skip middleman by using "->".

There are other differences, but the other answers have covered this extensively.

If you have a background in Java this might confuse you, since, in Java, everything is pointers. This means that there's no reason to have symbol that doesn't dereference your pointer first. In c++ however you gotta be a little more careful with remembering what is and what isn't a pointer, and it might be a good idea to label them with the prefix "p_" or simply "p".

Adb Devices can't find my phone

I have a ZTE Crescent phone (Orange San Francisco II).

When I connect the phone to the USB a disk shows up in OS X named 'ZTE_USB_Driver'.

Running adb devices displays no connected devices. But after I eject the 'ZTE_USB_Driver' disk from OS X, and run adb devices again the phone shows up as connected.

How to set up tmux so that it starts up with specified windows opened?

have a look @ https://github.com/remiprev/teamocil

you can specify your structure using YAML

windows:
  - name: sample-window
    splits:
      - cmd: vim
      - cmd:
        - ipython
        width: 50
      - cmd:
        height: 25

Simple calculations for working with lat/lon and km distance?

The approximate conversions are:

  • Latitude: 1 deg = 110.574 km
  • Longitude: 1 deg = 111.320*cos(latitude) km

This doesn't fully correct for the Earth's polar flattening - for that you'd probably want a more complicated formula using the WGS84 reference ellipsoid (the model used for GPS). But the error is probably negligible for your purposes.

Source: http://en.wikipedia.org/wiki/Latitude

Caution: Be aware that latlong coordinates are expressed in degrees, while the cos function in most (all?) languages typically accepts radians, therefore a degree to radians conversion is needed.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?

In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.

How to get a complete list of object's methods and attributes?

This is how I do it, useful for simple custom objects to which you keep adding attributes:

Given an object created with obj = type("Obj",(object,),{}), or by simply:

class Obj: pass
obj = Obj()

Add some attributes:

obj.name = 'gary'
obj.age = 32

then, to obtain a dictionary with only the custom attributes:

{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}

# {'name': 'gary', 'age': 32}

"Strict Standards: Only variables should be passed by reference" error

This should be OK

   $value = explode(".", $value);
   $extension = strtolower(array_pop($value));   //Line 32
   // the file name is before the last "."
   $fileName = array_shift($value);  //Line 34

How to check if div element is empty

You can use the is function

if( $('#cartContent').is(':empty') ) { }

or use the length

if( $('#cartContent:empty').length ) { }

Find out where MySQL is installed on Mac OS X

To check MySQL version of MAMP , use the following command in Terminal:

/Applications/MAMP/Library/bin/mysql --version

Assume you have started MAMP .

Example output:

./mysql  Ver 14.14 Distrib 5.1.44, for apple-darwin8.11.1 (i386) using  EditLine wrapper

UPDATE: Moreover, if you want to find where does mysql installed in system, use the following command:

type -a mysql

type -a is an equivalent of tclsh built-in command where in OS X bash shell. If MySQL is found, it will show :

mysql is /usr/bin/mysql

If not found, it will show:

-bash: type: mysql: not found

By default , MySQL is not installed in Mac OS X.

Sidenote: For XAMPP, the command should be:

/Applications/XAMPP/xamppfiles/bin/mysql --version

How To Show And Hide Input Fields Based On Radio Button Selection

You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.

I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.

$('#yesCheck').click(function() {
    $('#ifYes').slideDown();
});
$('#noCheck').click(function() {
    $('#ifYes').slideUp();
});

It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.

How do I change the JAVA_HOME for ant?

JAVA_HOME should point at where the JDK is installed not not a JRE.

So, if you type ls $JAVA_HOME what do you see? if you do ls $JAVA_HOME/bin/ do you see javac?

If the first doesn't work then you don't have JAVA_HOME pointing at the right directory. If the second doesn't work then you need to point JAVA_HOME at a JDK instead of a JRE.

Why is nginx responding to any domain name?

The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.

So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.

This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.

# Default server
server {
    return 404;
}

server {
    server_name domain_1;
    [...]
}

server {
    server_name domain_2;
    [...]
}

etc

** EDIT **

It seems some users are a bit confused by this example and think it is limited to a single conf file etc.

Please note that the above is a simple example for the OP to develop as required.

I personally use separate vhost conf files with this as so (CentOS/RHEL):

http {
    [...]
    # Default server
    server {
        return 404;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf.d/ will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.

The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.

In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.

In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.

However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.

This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.

I resolve this by creating a default server for Port 8080 to redirect such requests.

http {
    [...]
    # Default server block for undefined domains
    server {
        listen 80;
        return 404;
    }
    # Default server block to redirect Port 8080 for all domains
    server {
        listen my.external.ip.addr:8080;
        return 301 http://$host$request_uri;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.

I actually have four of such server blocks and this is a simplified use case.

Passing a varchar full of comma delimited values to a SQL Server IN function

The simplest way i found was to use FIND_IN_SET

FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)

Add new value to an existing array in JavaScript

jQuery is an abstraction of JavaScript. Think of jQuery as a sub-set of JavaScript, aimed at working with the DOM. That being said; there are functions for adding item(s) to a collection. I would use basic JavaScript in your case though:

var array;

array[0] = "value1";
array[1] = "value2";
array[2] = "value3";

... Or:

var array = ["value1", "value2", "value3"];

... Or:

var array = [];

array.push("value1");
array.push("value2");
array.push("value3");

Convert a row of a data frame to vector

If you don't want to change to numeric you can try this.

> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6

Resize image proportionally with MaxHeight and MaxWidth constraints

Working Solution :

For Resize image with size lower then 100Kb

WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;

Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;

do
{
    ScaleTransform st = new ScaleTransform();
    st.ScaleX = 0.3;
    st.ScaleY = 0.3;
    i = new WriteableBitmap(img, st);
    img.Source = i;
} while (i.Pixels.Length / 1024 > 100);

More Reference at http://net4attack.blogspot.com/

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Another way of doing it is by using the read.table() argument colClasses to specify the column type by making colClasses=c(*column class types*). If there are 6 columns whose members you want as numeric, you need to repeat the character string "numeric" six times separated by commas, importing the data frame, and as.matrix() the data frame. P.S. looks like you have headers, so I put header=T.

as.matrix(read.table(SFI.matrix,header=T,
colClasses=c("numeric","numeric","numeric","numeric","numeric","numeric"),
sep=","))

mat-form-field must contain a MatFormFieldControl

You have missed matInput directive in your input tag.

What’s the best way to reload / refresh an iframe?

If all of the above doesn't work for you:

window.location.reload();

This for some reason refreshed my iframe instead of the whole script. Maybe because it is placed in the frame itself, while all those getElemntById solutions work when you try to refresh a frame from another frame?

Or I don't understand this fully and talk gibberish, anyways this worked for me like a charm :)

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

What is a race condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:

if (x == 5) // The "Check"
{
   y = x * 2; // The "Act"

   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
   // y will not be equal to 10.
}

The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.

In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:

// Obtain lock for x
if (x == 5)
{
   y = x * 2; // Now, nothing can change x until the lock is released. 
              // Therefore y = 10
}
// release lock for x

Error in finding last used cell in Excel with VBA

One important note to keep in mind when using the solution ...

LastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

... is to ensure that your LastRow variable is of Long type:

Dim LastRow as Long

Otherwise you will end up getting OVERFLOW errors in certain situations in .XLSX workbooks

This is my encapsulated function that I drop in to various code uses.

Private Function FindLastRow(ws As Worksheet) As Long
    ' --------------------------------------------------------------------------------
    ' Find the last used Row on a Worksheet
    ' --------------------------------------------------------------------------------
    If WorksheetFunction.CountA(ws.Cells) > 0 Then
        ' Search for any entry, by searching backwards by Rows.
        FindLastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
End Function

git stash changes apply to new branch?

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

git stash branch branchName

It will make:

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

Android: Creating a Circular TextView?

Try out below drawable file. Create file named "circle" in your res/drawable folder and copy below code:

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

    <solid android:color="#FFFFFF" />

    <stroke
        android:width="1dp"
        android:color="#4a6176" />

    <padding
        android:left="10dp"
        android:right="10dp"
        android:top="10dp"
        android:bottom="10dp"
         />

    <corners android:radius="10dp" />

</shape>

Apply it in your TextView as below:

<TextView
        android:id="@+id/tvSummary1"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:text="Hello World" 
        android:gravity="left|center_vertical"
        android:background="@drawable/round_bg">

    </TextView>

enter image description here

Show all tables inside a MySQL database using PHP?

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!


How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

What is 0x10 in decimal?

The simple version is 0x is a prefix denoting a hexadecimal number, source.

So the value you're computing is after the prefix, in this case 10.

But that is not the number 10. The most significant bit 1 denotes the hex value while 0 denotes the units.

So the simple math you would do is

0x10

1 * 16 + 0 = 16

Note - you use 16 because hex is base 16.

Another example:

0xF7

15 * 16 + 7 = 247

You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.

Create a dictionary with list comprehension

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran's answer.

What's the difference between .bashrc, .bash_profile, and .environment?

That's simple. It's explained in man bash:

/bin/bash
       The bash executable
/etc/profile
       The systemwide initialization file, executed for login shells
~/.bash_profile
       The personal initialization file, executed for login shells
~/.bashrc
       The individual per-interactive-shell startup file
~/.bash_logout
       The individual login shell cleanup file, executed when a login shell exits
~/.inputrc
       Individual readline initialization file

Login shells are the ones that are read one you login (so, they are not executed when merely starting up xterm, for example). There are other ways to login. For example using an X display manager. Those have other ways to read and export environment variables at login time.

Also read the INVOCATION chapter in the manual. It says "The following paragraphs describe how bash executes its startup files.", i think that's a spot-on :) It explains what an "interactive" shell is too.

Bash does not know about .environment. I suspect that's a file of your distribution, to set environment variables independent of the shell that you drive.

How to determine if Javascript array contains an object with an attribute that equals a given value?

To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var  objectsFound = [];

for(let objectNumber in productList){
    var currentId = productList[objectNumber].id;   
    if (theDatabaseList.some(obj => obj.id === currentId)) {
        // Do what you need to do with the matching value here
        objectsFound.push(currentId);
    }
}
console.log(objectsFound);

An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var objectsFound = [];

for(var i = 0; i < Object.keys(productList).length; i++){
        for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
        if(productList[i].id === theDatabaseList[j].id){
            objectsFound.push(productList[i].id);
        }       
    }
}
console.log(objectsFound);

To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } 
];

for(var ojectNumbers in vendors){
    if(vendors[ojectNumbers].Name === 'Magenic'){
        console.log('object contains Magenic');
    }
}

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

How can I check if a background image is loaded?

I have a jQuery plugin called waitForImages that can detect when background images have downloaded.

$('body')
  .css('background-image','url(http://picture.de/image.png)')
  .waitForImages(function() {
    alert('Background image done loading');
    // This *does* work
  }, $.noop, true);

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

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

In JavaScript it has no special significance (no more than a or Q anyway). It is just an uninformative variable name.

In jQuery the variable is assigned a copy of the jQuery function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".

Format ints into string of hex

Yet another option is binascii.hexlify:

a = [0,1,2,3,127,200,255]
print binascii.hexlify(bytes(bytearray(a)))

prints

000102037fc8ff

This is also the fastest version for large strings on my machine.

In Python 2.7 or above, you could improve this even more by using

binascii.hexlify(memoryview(bytearray(a)))

saving the copy created by the bytes call.

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

Git pushing to remote branch

With modern Git versions, the command to use would be:

git push -u origin <branch_name_test>

This will automatically set the branch name to track from remote and push in one go.

How can I convert a PFX certificate file for use with Apache on a linux server?

SSLSHopper has some pretty thorough articles about moving between different servers.

http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html

Just pick the relevant link at bottom of this page.

Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

How do I make an editable DIV look like a text field?

You could go for an inner box shadow:

div[contenteditable=true] {
  box-shadow: inset 0px 1px 4px #666;
}

I updated the jsfiddle from Jarish: http://jsfiddle.net/ZevvE/2/

How to replace ${} placeholders in a text file?

Update

Here is a solution from yottatsa on a similar question that only does replacement for variables like $VAR or ${VAR}, and is a brief one-liner

i=32 word=foo envsubst < template.txt

Of course if i and word are in your environment, then it is just

envsubst < template.txt

On my Mac it looks like it was installed as part of gettext and from MacGPG2

Old Answer

Here is an improvement to the solution from mogsie on a similar question, my solution does not require you to escale double quotes, mogsie's does, but his is a one liner!

eval "cat <<EOF
$(<template.txt)
EOF
" 2> /dev/null

The power on these two solutions is that you only get a few types of shell expansions that don't occur normally $((...)), `...`, and $(...), though backslash is an escape character here, but you don't have to worry that the parsing has a bug, and it does multiple lines just fine.

SELECT only rows that contain only alphanumeric characters in MySQL

Try this code:

SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$'

This makes sure that all characters match.

Jquery click event not working after append method

TRY THIS

As of jQuery version 1.7+, the on() method is the new replacement for the bind(), live() and delegate() methods.

SO ADD THIS,

$(document).on("click", "a.new_participant_form" , function() {
      console.log('clicked');
});

Or for more information CHECK HERE

Redirect from an HTML page

Place the following code between the <HEAD> and </HEAD> tags of your HTML code:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://example.com/index.html">

The above HTML redirect code will redirect your visitors to another web page instantly. The content="0; may be changed to the number of seconds you want the browser to wait before redirecting.

How to use multiprocessing queue in Python?

in "from queue import Queue" there is no module called queue, instead multiprocessing should be used. Therefore, it should look like "from multiprocessing import Queue"

Check if an object exists

Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count()

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

num_results = len(user_object)

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

Why aren't programs written in Assembly more often?

Assembly is not portable between different microprocessors.

In C++, what is a virtual base class?

A virtual base class is a class that cannot be instantiated : you cannot create direct object out of it.

I think you are confusing two very different things. Virtual inheritance is not the same thing as an abstract class. Virtual inheritance modifies the behaviour of function calls; sometimes it resolves function calls that otherwise would be ambiguous, sometimes it defers function call handling to a class other than that one would expect in a non-virtual inheritance.

Using SQL LOADER in Oracle to import CSV file

Try this

load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)

In command prompt:

sqlldr system@databasename/password control='control file location'

How to convert SQL Server's timestamp column to datetime format

Works fine, except this message:

Implicit conversion from data type varchar to timestamp is not allowed. Use the CONVERT function to run this query

So yes, TIMESTAMP (RowVersion) is NOT a DATE :)

To be honest, I fidddled around quite some time myself to find a way to convert it to a date.

Best way is to convert it to INT and compare. That's what this type is meant to be.

If you want a date - just add a Datetime column and live happily ever after :)

cheers mac

Close popup window

You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :

window.open

then

window.close

will work. Or else not.

Call Class Method From Another Class

class CurrentValue:

    def __init__(self, value):
        self.value = value

    def set_val(self, k):
        self.value = k

    def get_val(self):
        return self.value


class AddValue:

    def av(self, ocv):
        print('Before:', ocv.get_val())
        num = int(input('Enter number to add : '))
        nnum = num + ocv.get_val()
        ocv.set_val(nnum)
        print('After add :', ocv.get_val())


cvo = CurrentValue(5)

avo = AddValue()

avo.av(cvo)

We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.

I am sorry for any inconvenience. This will not happen again.

Before: 5

Enter number to add : 14

After add : 19

Rounding a number to the nearest 5 or 10 or X

In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.

The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.

Django: OperationalError No Such Table

If you get to the bottom of this list and find this answer, I am almost sure it will solve all your issues :) In my case, I had dropped a database table and I was not getting anywhere with makemigrations and migrate

So I got a very detailed answer on how to reset everything on this link

SQL Server after update trigger

First off, your trigger as you already see is going to update every record in the table. There is no filtering done to accomplish jus the rows changed.

Secondly, you're assuming that only one row changes in the batch which is incorrect as multiple rows could change.

The way to do this properly is to use the virtual inserted and deleted tables: http://msdn.microsoft.com/en-us/library/ms191300.aspx

In nodeJs is there a way to loop through an array without using array size?

Use Iterators...

var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
    console.log('all done')
})
function processArray(iter, cb) {
    var curr = iter.next()
    if(curr.done)
        return cb()
    console.log(curr.value)
    processArray(iter, cb)
}

More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

How do you share constants in NodeJS modules?

Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;.

Send PHP variable to javascript function

Your JavaScript would have to be defined within a PHP-parsed file.

For example, in index.php you could place

<?php
$time = time();
?>
<script>
    document.write(<?php echo $time; ?>);
</script>

Call a function from another file?

First save the file in .py format (for example, my_example.py). And if that file have functions,

def xyz():

        --------

        --------

def abc():

        --------

        --------

In the calling function you just have to type the below lines.

file_name: my_example2.py

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

import my_example.py


a = my_example.xyz()

b = my_example.abc()

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

Do I need to close() both FileReader and BufferedReader?

You Don't need to close the wrapped reader/writer.

If you've taken a look at the docs (Reader.close(),Writer.close()), You'll see that in Reader.close() it says:

Closes the stream and releases any system resources associated with it.

Which just says that it "releases any system resources associated with it". Even though it doesn't confirm.. it gives you a nudge to start looking deeper. and if you go to Writer.close() it only states that it closes itself.

In such cases, we refer to OpenJDK to take a look at the source code.

At BufferedWriter Line 265 you'll see out.close(). So it's not closing itself.. It's something else. If you search the class for occurences of "out" you'll notice that in the constructor at Line 87 that out is the writer the class wraps where it calls another constructor and then assigning out parameter to it's own out variable..

So.. What about others? You can see similar code at BufferedReader Line 514, BufferedInputStream Line 468 and InputStreamReader Line 199. Others i don't know but this should be enough to assume that they do.

Difference between window.location.href=window.location.href and window.location.reload()

As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:

if (!window.location.hash) {
    window.location.href = window.location.href;
} else {
    window.location.reload();
}

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

I need an unordered list without any bullets

You can hide them using ::marker pseudo-element.

  1. Transparent ::marker

ul li::marker {
  color: transparent;
}

_x000D_
_x000D_
ul li::marker {
  color: transparent;
}

ul {
  padding-inline-start: 10px; /* Just to reset the browser initial padding */
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> I want to remove them. </li>
  <li> Hey! ::marker to the rescue </li>
</ul>
_x000D_
_x000D_
_x000D_

  1. ::marker empty content

ul li::marker {
  content: "";
}

_x000D_
_x000D_
ul li::marker {
   content: "";
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> I want to remove them </li>
  <li> Hey! ::marker to the rescue </li>
</ul>
_x000D_
_x000D_
_x000D_

It is better when you need to remove bullets from a specific list item.

ul li:nth-child(n)::marker { /* Replace n with the list item's position*/
   content: "";
}

_x000D_
_x000D_
ul li:not(:nth-child(2))::marker {
   content: "";
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> But I can live with it using ::marker </li>
  <li> Not again though </li>
</ul>
_x000D_
_x000D_
_x000D_

How to prevent long words from breaking my div?

I had to do the following because, if the properties were not declared in the correct order, it would randomly break words at the wrong place and without adding a hyphen.

    -moz-white-space: pre-wrap;
white-space: pre-wrap;        
    hyphens: auto;
    -ms-word-break: break-all;
    -ms-word-wrap: break-all;
    -webkit-word-break: break-word;
    -webkit-word-wrap: break-word;
word-break: break-word;
word-wrap: break-word;
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    -ms-hyphens: auto;
hyphens: auto;

Originally posted by Enigmo: https://stackoverflow.com/a/14191114

A method to reverse effect of java String.split()?

There's no method in the JDK for this that I'm aware of. Apache Commons Lang has various overloaded join() methods in the StringUtils class that do what you want.

jquery to change style attribute of a div class

Just try $('.handle').css('left', '300px');

Initialization of all elements of an array to one default value in C++?

Using the syntax that you used,

int array[100] = {-1};

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

Python function as a function argument?

Here's another way using *args (and also optionally), **kwargs:

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')

Output

hello dude
world

Note that function, *args, **kwargs have to be in that order and have to be the last arguments to the function calling the function.

Random color generator

function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}

http://jsfiddle.net/XmqDz/1/

Send a SMS via intent

I have developed this functionality from one Blog. There are 2 ways you can send SMS.

  1. Open native SMS composer
  2. write your message and send from your Android application

This is the code of 1st method.

Main.xml

<?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout  
        android:id="@+id/relativeLayout1"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        xmlns:android="http://schemas.android.com/apk/res/android">  

            <Button  
                android:id="@+id/btnSendSMS"  
               android:layout_height="wrap_content"  
               android:layout_width="wrap_content"  
               android:text="Send SMS"  
               android:layout_centerInParent="true"  
               android:onClick="sendSMS">  
           </Button>  
   </RelativeLayout>

Activity

public class SendSMSActivity extends Activity {  
     /** Called when the activity is first created. */  
     @Override  
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.main);  
      }  

     public void sendSMS(View v)  
     {  
         String number = "12346556";  // The number on which you want to send SMS  
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));  
     }  
    /* or 
     public void sendSMS(View v) 
      { 
     Uri uri = Uri.parse("smsto:12346556"); 
         Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
         it.putExtra("sms_body", "Here you can set the SMS text to be sent"); 
         startActivity(it); 
      } */  
 }

NOTE:- In this method, you don’t require SEND_SMS permission inside the AndroidManifest.xml file.

For 2nd method refer to this BLOG. You will find a good explanation from here.

Hope this will help you...

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

'setInterval' vs 'setTimeout'

setTimeout():

It is a function that execute a JavaScript statement AFTER x interval.

setTimeout(function () {
    something();
}, 1000); // Execute something() 1 second later.

setInterval():

It is a function that execute a JavaScript statement EVERY x interval.

setInterval(function () {
    somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.

The interval unit is in millisecond for both functions.

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

How to access pandas groupby dataframe by key

Rather than

gb.get_group('foo')

I prefer using gb.groups

df.loc[gb.groups['foo']]

Because in this way you can choose multiple columns as well. for example:

df.loc[gb.groups['foo'],('A','B')]

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

Using CSS to affect div style inside iframe

The quick answer is: No, sorry.

It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

"Cloning" row or column vectors

Let:

>>> n = 1000
>>> x = np.arange(n)
>>> reps = 10000

Zero-cost allocations

A view does not take any additional memory. Thus, these declarations are instantaneous:

# New axis
x[np.newaxis, ...]

# Broadcast to specific shape
np.broadcast_to(x, (reps, n))

Forced allocation

If you want force the contents to reside in memory:

>>> %timeit np.array(np.broadcast_to(x, (reps, n)))
10.2 ms ± 62.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit np.repeat(x[np.newaxis, :], reps, axis=0)
9.88 ms ± 52.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit np.tile(x, (reps, 1))
9.97 ms ± 77.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

All three methods are roughly the same speed.

Computation

>>> a = np.arange(reps * n).reshape(reps, n)
>>> x_tiled = np.tile(x, (reps, 1))

>>> %timeit np.broadcast_to(x, (reps, n)) * a
17.1 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit x[np.newaxis, :] * a
17.5 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit x_tiled * a
17.6 ms ± 240 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

All three methods are roughly the same speed.


Conclusion

If you want to replicate before a computation, consider using one of the "zero-cost allocation" methods. You won't suffer the performance penalty of "forced allocation".

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

AppCompatActivity was only added in version 22.1.0 of the support library. Before that it was called ActionBarActivity.

You should use the same version for all of your support libraries. At the time of writing the latest version is 23.1.1 (you can find out the latest here https://developer.android.com/tools/support-library/index.html#revisions) so the dependencies section of your gradle file should look like this.

implementation "com.android.support:support-v4:23.1.1"
implementation "com.android.support:appcompat-v7:23.1.1"
implementation "com.android.support:support-annotations:23.1.1"

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

How to change the blue highlight color of a UITableViewCell?

You can change the highlight color in several ways.

  1. Change the selectionStyle property of your cell. If you change it to UITableViewCellSelectionStyleGray, it will be gray.

  2. Change the selectedBackgroundView property. Actually what creates the blue gradient is a view. You can create a view and draw what ever you like, and use the view as the background of your table view cells.

adding child nodes in treeview

I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.

It's actually really easy to reference the correct node to receive the new child node.

private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
   //show dialogbox to let user name the new node
   frmDialogInput f = new frmDialogInput();
   f.ShowDialog();

    //find the node that was selected
    TreeNode myNode = TreeView1.SelectedNode;
    //create the new node to add
    TreeNode newNode = new TreeNode(f.EnteredText);
    //add the new child to the selected node
    myNode.Nodes.Add(newNode);
}

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

How can I reduce the waiting (ttfb) time

TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.

You need to look into what queries are being run and how the website connects to the server.

This article might help understand TTFB, but otherwise you need to dig deeper into your application.

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

jquery change button color onclick

$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

Use class, Demo:- http://jsfiddle.net/BX6Df/

   $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/

$('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});


.red
{
    background-color:red;
}

Updated answer for your comment.

http://jsfiddle.net/H2Xhw/

$('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

How to convert a byte array to its numeric value (Java)?

Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:

    long content = 212000607777l;
    byte[] numberByte = Longs.toByteArray(content);
    logger.info(Longs.fromByteArray(numberByte));

foreach with index

It depends on the class you are using.

Dictionary<(Of <(TKey, TValue>)>) Class For Example Support This

The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values.

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.

foreach (KeyValuePair kvp in myDictionary) {...}

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

Invalid default value for 'create_date' timestamp field

If you generated the script from the MySQL workbench.

The following line is generated

SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

Remove TRADITIONAL from the SQL_MODE, and then the script should work fine

Else, you could set the SQL_MODE as Allow Invalid Dates

SET SQL_MODE='ALLOW_INVALID_DATES';

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

Get a CSS value with JavaScript

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hyphen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
            return (function(value) {
                var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}

Main reference stackoverflow

Is it wrong to place the <script> tag after the </body> tag?

As Andy said the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:

void HTMLParser::processCloseTag(Token* t)
{
    // Support for really broken html.
    // we never close the body tag, since some stupid web pages close it before 
    // the actual end of the doc.
    // let's rely on the end() call to close things.
    if (t->tagName == htmlTag || t->tagName == bodyTag 
                              || t->tagName == commentAtom)
        return;
    ...

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

Using regular expression in css?

You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:

#sections div[id^='s'] {
    color: red;  
}

That says select any div elements inside the #sections div that have an ID starting with the letter 's'.

See fiddle here.

W3 CSS selector docs here.

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Global javascript variable inside document.ready

JavaScript has Function-Level variable scope which means you will have to declare your variable outside $(document).ready() function.

Or alternatively to make your variable to have global scope, simply dont use var keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.

$(document).ready(function() {
   intro = null; // it is in global scope now

To learn more about it, check out:

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Just use Date constructor to compare with string input:

_x000D_
_x000D_
function isDate(str) {_x000D_
  return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_

Edited: Responding to one of the comments

Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal

_x000D_
_x000D_
function pad(n) {_x000D_
  return (10 > n ? ('0' + n) : (n));_x000D_
}_x000D_
_x000D_
function isDate(str) {_x000D_
  if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {_x000D_
    return false;_x000D_
  }_x000D_
  var dt = new Date(str.replace(/\-/g, '/'));_x000D_
  return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_

use localStorage across subdomains

Set to cookie in the main domain -

document.cookie = "key=value;domain=.mydomain.com"

and then take the data from any main domain or sub domain and set it on the localStorage

How to add a "sleep" or "wait" to my Lua Script?

wxLua has three sleep functions:

local wx = require 'wx'
wx.wxSleep(12)   -- sleeps for 12 seconds
wx.wxMilliSleep(1200)   -- sleeps for 1200 milliseconds
wx.wxMicroSleep(1200)   -- sleeps for 1200 microseconds (if the system supports such resolution)

What is the default access modifier in Java?

Default access modifier is package-private - visible only from the same package

How can I change the value of the elements in a vector?

You can access the values in a vector just as you access any other array.

for (int i = 0; i < v.size(); i++)
{         
  v[i] -= 1;         
} 

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

Unix ls command: show full path when using options

You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.

ls -lart `find . -type f -name "*" `

Is there a Python equivalent to Ruby's string interpolation?

You can also have this

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Best practice to run Linux service as a different user

After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

  1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

    daemon --user=my_user my_cmd &>/dev/null &
    

    This is implemented by wrapping the process invocation with runuser - more on this later.

  2. Jonathan Leffler is right: there is setuid in Python:

    import os
    os.setuid(501) # UID of my_user is 501
    

    I still don't think you can setuid from inside a JVM, however.

  3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

    [my_user@my_host]$ id
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    [my_user@my_host]$ su my_user -c "id"
    Password: # don't want to be prompted!
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    

To workaround that behaviour of su and runuser, I've changed my init script to something like:

if [[ "$USER" == "my_user" ]]
then
    daemon my_cmd &>/dev/null &
else
    daemon --user=my_user my_cmd &>/dev/null &
fi

Thanks all for your help!

Clear the cache in JavaScript

I've solved this issue by using ETag

Etags are similar to fingerprints, and if the resource at a given URL changes, a new Etag value must be generated. A comparison of them can determine whether two representations of a resource are the same.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

Delayed function calls

private static volatile List<System.Threading.Timer> _timers = new List<System.Threading.Timer>();
        private static object lockobj = new object();
        public static void SetTimeout(Action action, int delayInMilliseconds)
        {
            System.Threading.Timer timer = null;
            var cb = new System.Threading.TimerCallback((state) =>
            {
                lock (lockobj)
                    _timers.Remove(timer);
                timer.Dispose();
                action()
            });
            lock (lockobj)
                _timers.Add(timer = new System.Threading.Timer(cb, null, delayInMilliseconds, System.Threading.Timeout.Infinite));
}

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

Generating statistics from Git repository

If your project is on GitHub, you now (April 2013) have Pulse (see "Get up to speed with Pulse"):

It is more limited, and won't display all the stats you might need, but is readily available for any GitHub project.

Pulse is a great way to discover recent activity on projects.
Pulse will show you who has been actively committing and what has changed in a project's default branch:

Pulse

You can find the link to the left of the nav bar.

Link

Note that there isn't (yet) an API to extract that information.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

How do I enable php to work with postgresql?

You need to install the pgsql module for php. In debian/ubuntu is something like this:

sudo apt-get install php5-pgsql

Or if the package is installed, you need to enable de module in php.ini

extension=php_pgsql.dll (windows)
extension=php_pgsql.so (linux)

Greatings.

Implementing a simple file download servlet

The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.

You can easily achieve it through:

HttpServletResponse.sendRedirect()

How to reverse a singly linked list using only two pointers?

You need a track pointer which will track the list.

You need two pointers :

first pointer to pick first node. second pointer to pick second node.

Processing :

Move Track Pointer

Point second node to first node

Move First pointer one step, by assigning second pointer to one

Move Second pointer one step, By assigning Track pointer to second

Node* reverselist( )
{
   Node *first = NULL;  // To keep first node
   Node *second = head; // To keep second node
   Node *track =  head; // Track the list

    while(track!=NULL)
    {
      track = track->next; // track point to next node;
      second->next = first; // second node point to first
      first = second; // move first node to next
      second = track; // move second node to next
    }

    track = first;

    return track;

}

Send response to all clients except sender

From the @LearnRPG answer but with 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 io.emit('message', 'this is a test');

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

To answer @Crashalot comment, socketid comes from:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

Why does ++[[]][+[]]+[+[]] return the string "10"?

++[[]][+[]] => 1 // [+[]] = [0], ++0 = 1
[+[]] => [0]

Then we have a string concatenation

1+[0].toString() = 10

Import Maven dependencies in IntelliJ IDEA

What helped me:

Navigage: Settings | Build, Execution, Deployment | Maven

Specify "Maven home directory" - the place you installed the maven

How do you show animated GIFs on a Windows Form (c#)

It's not too hard.

  1. Drop a picturebox onto your form.
  2. Add the .gif file as the image in the picturebox
  3. Show the picturebox when you are loading.

Things to take into consideration:

  • Disabling the picturebox will prevent the gif from being animated.

Animated gifs:

If you are looking for animated gifs you can generate them:

AjaxLoad - Ajax Loading gif generator

Another way of doing it:

Another way that I have found that works quite well is the async dialog control that I found on the code project

Given final block not properly padded

This can also be a issue when you enter wrong password for your sign key.

Sending GET request with Authentication headers using restTemplate

You can use postForObject with an HttpEntity. It would look like this:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject(url, entity, String.class);

In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange or execute methods directly. The get shorthands don't support header modification.

The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.

Multi-select dropdown list in ASP.NET

Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:

(1) Multi-select; (2) Auto-complete; (3) Validation.

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

  • It only accepts a single character from user input and returns its ASCII Code.
  • The data type should be int. because it returns an integer value as ASCII.
  • ex -> int value = Console.Read();

Console.ReadLine()

  • It read all the characters from user input. (and finish when press enter).
  • It returns a String so data type should be String.
  • ex -> string value = Console.ReadLine();

Console.ReadKey()

  • It read that which key is pressed by the user and returns its name. it does not require to press enter key before entering.
  • It is a Struct Data type which is ConsoleKeyInfo.
  • ex -> ConsoleKeyInfo key = Console.ReadKey();

How do you use youtube-dl to download live streams (that are live)?

Some websites with m3u streaming cannot be downloaded in a single youtube-dl step, you can try something like this :

$ URL=https://www.arte.tv/fr/videos/078132-001-A/cosmos-une-odyssee-a-travers-l-univers/
$ youtube-dl -F $URL | grep m3u
HLS_XQ_2     m3u8       1280x720   VA-STA, Allemand 2200k 
HLS_XQ_1     m3u8       1280x720   VF-STF, Français 2200k 
$ CHOSEN_FORMAT=HLS_XQ_1
$ youtube-dl -F "$(youtube-dl -gf $CHOSEN_FORMAT)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[info] Available formats for master:
format code  extension  resolution note
61           mp4        audio only   61k , mp4a.40.2
419          mp4        384x216     419k , avc1.66.30, mp4a.40.2
923          mp4        640x360     923k , avc1.77.30, mp4a.40.2
1737         mp4        720x406    1737k , avc1.77.30, mp4a.40.2
2521         mp4        1280x720   2521k , avc1.77.30, mp4a.40.2 (best)
$ youtube-dl --hls-prefer-native -f 1737 "$(youtube-dl -gf $CHOSEN_FORMAT $URL)" -o "$(youtube-dl -f $CHOSEN_FORMAT --get-filename $URL)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 257
[download] Destination: Cosmos_une_odyssee_a_travers_l_univers__HLS_XQ_1__078132-001-A.mp4
[download]   0.9% of ~731.27MiB at 624.95KiB/s ETA 13:13
....

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

If you have an html form containing one or more fields with "required" attributes, Chrome (on last versions) will validate these fields before submitting the form and, if they are not filled, some tooltips will be shown to the users to help them getting the form submitted (I.e. "please fill out this field").

To avoid this browser built-in validation in forms you can use "novalidate" attribute on your form tag. This form won't be validated by browser:

<form id="form-id" novalidate>

    <input id="input-id" type="text" required>

    <input id="submit-button" type="submit">

</form>

Remove Identity from a column in a table

Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.

Lets suppose you have a table with two columns

ID Identity (1,1) | Name Varchar

and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4

DBCC CHECKIDENT([YourTable], RESEED, 3)

Make the Insert

INSERT  INTO [YourTable]
        ( Name )
VALUES  ( 'Client' )

And get your seed back to the highest ID, lets suppose is 15

DBCC CHECKIDENT([YourTable], RESEED, 15)

Done!

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Failure [INSTALL_FAILED_OLDER_SDK]

basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion specified in your app.

FROM

apply plugin: 'com.android.application'

android {

compileSdkVersion 'L' //Avoid String change to 20 without quotes
buildToolsVersion "20.0.0"

defaultConfig {
    applicationId "com.vahe_muradyan.notes"
    minSdkVersion 8
    targetSdkVersion 'L' //Set your correct Target which is 17 for Android 4.2.2
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:19.+' // Avoid Generalization 
// can lead to dependencies issues remove +

}

TO

apply plugin: 'com.android.application'

android {
compileSdkVersion 20 
buildToolsVersion "20.0.0"

defaultConfig {
    applicationId "com.vahe_muradyan.notes"
    minSdkVersion 8
    targetSdkVersion 17
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 
'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:19.0.0'
}

This is common error from eclipse to now Android Studio 0.8-.8.6

Things to avoid in Android Studio (As for now)

  • Avoid Strings instead set API level/Number
  • Avoid generalizing dependencies + be specific

Pass variables to AngularJS controller, best practice?

You could create a basket service. And generally in JS you use objects instead of lots of parameters.

Here's an example: http://jsfiddle.net/2MbZY/

var app = angular.module('myApp', []);

app.factory('basket', function() {
    var items = [];
    var myBasketService = {};

    myBasketService.addItem = function(item) {
        items.push(item);
    };
    myBasketService.removeItem = function(item) {
        var index = items.indexOf(item);
        items.splice(index, 1);
    };
    myBasketService.items = function() {
        return items;
    };

    return myBasketService;
});

function MyCtrl($scope, basket) {
    $scope.newItem = {};
    $scope.basket = basket;    
}

Disable the postback on an <ASP:LinkButton>

In C#, you'd do something like this:

MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

PHP function use variable from outside

Alternatively, you can bring variables in from the outside scope by using closures with the use keyword.

$myVar = "foo";
$myFunction = function($arg1, $arg2) use ($myVar)
{
 return $arg1 . $myVar . $arg2;
};

How to make rpm auto install dependencies

Create a (local) repository and use yum to have it resolve the dependencies for you.

The CentOS wiki has a nice page providing a how-to on this. CentOS wiki HowTos/CreateLocalRepos.


Summarized and further minimized (not ideal, but quickest):

  1. Create a directory for you local repository, e.g. /home/user/repo.
  2. Move the RPMs into that directory.
  3. Fix some ownership and filesystem permissions:

    # chown -R root.root /home/user/repo
    
  4. Install the createrepo package if not installed yet, and run

    # createrepo /home/user/repo
    # chmod -R o-w+r /home/user/repo
    
  5. Create a repository configuration file, e.g. /etc/yum.repos.d/myrepo.repo containing

    [local]
    name=My Awesome Repo
    baseurl=file:///home/user/repo
    enabled=1
    gpgcheck=0
    
  6. Install your package using

    # yum install packagename
    

How to get the nvidia driver version from the command line?

On any linux system with the NVIDIA driver installed and loaded into the kernel, you can execute:

cat /proc/driver/nvidia/version

to get the version of the currently loaded NVIDIA kernel module, for example:

$ cat /proc/driver/nvidia/version 
NVRM version: NVIDIA UNIX x86_64 Kernel Module  304.54  Sat Sep 29 00:05:49 PDT 2012
GCC version:  gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 

Bootstrap modal appearing under background

An other way to approach this is to remove the z-index from the .modal-backdrop in bootstrap.css. This will cause the backdrop to be on the same level as the rest of your body (it will still fade) and your modal to be on top.

.modal-backdrop looks like this

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #000000;
}

How to declare a local variable in Razor?

you can put everything in a block and easily write any code that you wish in that block just exactly the below code :

@{
        bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
        if (isUserConnected)
        { // meaning that the viewing user has not been saved
            <div>
                <div> click to join us </div>
                <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
            </div>
        }
    }

it helps you to have at first a cleaner code and also you can prevent your page from loading many times different blocks of codes

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

jQuery Toggle Text?

In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:

$.fn.extend({
  toggleText: function (a, b){
    if (this.text() == a){ this.text(b); }
    else { this.text(a) }
  }
);

You could use it this way:

$(document).on('click', '.toggle-details', function(e){
  e.preventDefault();
  //other things happening
  $(this).toggleText("Show Details", "Hide Details");
});

Android Intent Cannot resolve constructor

Same Error was coming with my code in Activity but not in Fragment. Showing constructor error for different line like new Intent( From.this, To.class) and new ArrayList<> etc.

Fixed using closing Android Studio and moving the repository to other location and opening the the project once again. Fixed the problem.

Seems like Android Studio building problem.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

As I can't add a comment, just thought I'd post this for completion. tufy's answer is correct, it's to do with parenthesis (brackets) in the path to the application being run.

There is an existing networking bug where the networking layer is unable to parse program locations that contain parenthesis in the path to the executable which is attempting to connect to Oracle.

Filed with Oracle, Bug 3807408 refers.

Source

What are the parameters for the number Pipe - Angular 2

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits