Programs & Examples On #Ios32

For issues relating to using iOS, version 3.2.

How to add google-play-services.jar project dependency so my project will run and present map

What i have done is that import a new project into eclipse workspace, and that path of that was be

android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib

and add as library in your project.. that it .. simple!! you might require to add support library in your project.

What is the difference between a static method and a non-static method?

- First we must know that the diff bet static and non static methods 
is differ from static and non static variables : 

- this code explain static method - non static method and what is the diff 

    public class MyClass {
        static {
            System.out.println("this is static routine ... ");

        }
          public static void foo(){
            System.out.println("this is static method ");
        }

        public void blabla(){

         System.out.println("this is non static method ");
        }

        public static void main(String[] args) {

           /* ***************************************************************************  
            * 1- in static method you can implement the method inside its class like :  *       
            * you don't have to make an object of this class to implement this method   *      
            * MyClass.foo();          // this is correct                                *     
            * MyClass.blabla();       // this is not correct because any non static     *
            * method you must make an object from the class to access it like this :    *            
            * MyClass m = new MyClass();                                                *     
            * m.blabla();                                                               *    
            * ***************************************************************************/

            // access static method without make an object 
            MyClass.foo();

            MyClass m = new MyClass();
            // access non static method via make object 
            m.blabla();
            /* 
              access static method make a warning but the code run ok 
               because you don't have to make an object from MyClass 
               you can easily call it MyClass.foo(); 
            */
            m.foo();
        }    
    }
    /* output of the code */
    /*
    this is static routine ... 
    this is static method 
    this is non static method 
    this is static method
    */

 - this code explain static method - non static Variables and what is the diff 


     public class Myclass2 {

                // you can declare static variable here : 
                // or you can write  int callCount = 0; 
                // make the same thing 
                //static int callCount = 0; = int callCount = 0;
                static int callCount = 0;    

                public void method() {
                    /********************************************************************* 
                    Can i declare a static variable inside static member function in Java?
                    - no you can't 
                    static int callCount = 0;  // error                                                   
                    ***********************************************************************/
                /* static variable */
                callCount++;
                System.out.println("Calls in method (1) : " + callCount);
                }

                public void method2() {
                int callCount2 = 0 ; 
                /* non static variable */   
                callCount2++;
                System.out.println("Calls in method (2) : " + callCount2);
                }


            public static void main(String[] args) {
             Myclass2 m = new Myclass2();
             /* method (1) calls */
             m.method(); 
             m.method();
             m.method();
             /* method (2) calls */
             m.method2();
             m.method2();
             m.method2();
            }

        }
        // output 

        // Calls in method (1) : 1
        // Calls in method (1) : 2
        // Calls in method (1) : 3
        // Calls in method (2) : 1
        // Calls in method (2) : 1
        // Calls in method (2) : 1 

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

How to give ASP.NET access to a private key in a certificate in the certificate store?

For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.

I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.

Error when deploying an artifact in Nexus

Server id should match with the repository id of maven settings.xml

How do I get a UTC Timestamp in JavaScript?

If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:

var currentUnixTimestap = ~~(+new Date() / 1000);

This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.

How it works:

  • Create date object : new Date().
  • Convert to timestamp by adding unary + before object creation to convert it to timestamp integer. : +new Date().
  • Convert milliseconds to seconds: +new Date() / 1000
  • Use double tildes to round off the value to integer. : ~~(+new Date())

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Where are shared preferences stored?

Shared Preferences are the key/value pairs that we can store. They are internal type of storage which means we do not have to create an external database to store it. To see it go to, 1) Go to View in the menu bar. Select Tool Windows. 2) Click on Device File Explorer. 3) Device File Explorer opens up in the right hand side. 4) Find the data folder and click on it. 5) In the data folder, you can select another data folder. 6) Try to search for your package name in this data folder. Ex: com.example.com 7) Then Click on shared_prefs and open the .xml file.

Hope this helps!

How to align checkboxes and their labels consistently cross-browsers

I've never had a problem with doing it like this:

<form>
  <div>
    <input type="checkbox" id="cb" /> <label for="cb">Label text</label>
  </div>
</form>

What is the best way to get all the divisors of a number?

Given your factorGenerator function, here is a divisorGen that should work:

def divisorGen(n):
    factors = list(factorGenerator(n))
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
                break
            f[i] = 0
            i += 1
            if i >= nfactors:
                return

The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator.

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

How to get whole and decimal part of a number?

Just a new simple solution, for those of you who want to get the Integer part and Decimal part splitted as two integer separated values:

5.25 -> Int part: 5; Decimal part: 25

$num = 5.25;
$int_part = intval($num);
$dec_part = $num * 100 % 100;

This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).

Haven't tested thoroughly with extreme values, but it works fine for me for price calculations.

But, watch out! Now from -5.25 you get: Integer part: -5; Decimal part: -25

In case you want to get always positive numbers, simply add abs() before the calculations:

$num = -5.25;
$num = abs($num);
$int_part = intval($num);
$dec_part = $num * 100 % 100;

Finally, bonus snippet for printing prices with 2 decimals:

$message = sprintf("Your price: %d.%02d Eur", $int_part, $dec_part);

...so that you avoid getting 5.5 instead of 5.05. ;)

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

How to remove hashbang from url?

You should add mode history to your router like the below

export default new Router({
  mode: 'history',
  routes: [
    {
     ...
    }
  ]
}) 

PowerShell script to return versions of .NET Framework on a machine?

If you're going to use the registry you have to recurse in order to get the full version for the 4.x Framework. The earlier answers both return the root number on my system for .NET 3.0 (where the WCF and WPF numbers, which are nested under 3.0, are higher -- I can't explain that), and fail to return anything for 4.0 ...

EDIT: For .Net 4.5 and up, this changed slightly again, so there's now a nice MSDN article here explaining how to convert the Release value to a .Net version number, it's a total train wreck :-(

This looks right to me (note that it outputs separate version numbers for WCF & WPF on 3.0. I don't know what that's about). It also outputs both Client and Full on 4.0 (if you have them both installed):

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select PSChildName, Version, Release

Based on the MSDN article, you could build a lookup table and return the marketing product version number for releases after 4.5:

$Lookup = @{
    378389 = [version]'4.5'
    378675 = [version]'4.5.1'
    378758 = [version]'4.5.1'
    379893 = [version]'4.5.2'
    393295 = [version]'4.6'
    393297 = [version]'4.6'
    394254 = [version]'4.6.1'
    394271 = [version]'4.6.1'
    394802 = [version]'4.6.2'
    394806 = [version]'4.6.2'
    460798 = [version]'4.7'
    460805 = [version]'4.7'
    461308 = [version]'4.7.1'
    461310 = [version]'4.7.1'
    461808 = [version]'4.7.2'
    461814 = [version]'4.7.2'
    528040 = [version]'4.8'
    528049 = [version]'4.8'
}

# For One True framework (latest .NET 4x), change the Where-Object match 
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
  Get-ItemProperty -name Version, Release -EA 0 |
  Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}}, 
@{name = "Product"; expression = {$Lookup[$_.Release]}}, 
Version, Release

In fact, since I keep having to update this answer, here's a script to generate the script above (with a little extra) from the markdown source for that web page. This will probably break at some point, so I'm keeping the current copy above.

# Get the text from github
$url = "https://raw.githubusercontent.com/dotnet/docs/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md"
$md = Invoke-WebRequest $url -UseBasicParsing
$OFS = "`n"
# Replace the weird text in the tables, and the padding
# Then trim the | off the front and end of lines
$map = $md -split "`n" -replace " installed [^|]+" -replace "\s+\|" -replace "\|$" |
    # Then we can build the table by looking for unique lines that start with ".NET Framework"
    Select-String "^.NET" | Select-Object -Unique |
    # And flip it so it's key = value
    # And convert ".NET FRAMEWORK 4.5.2" to  [version]4.5.2
    ForEach-Object { 
        [version]$v, [int]$k = $_ -replace "\.NET Framework " -split "\|"
        "    $k = [version]'$v'"
    }

# And output the whole script
@"
`$Lookup = @{
$map
}

# For extra effect we could get the Windows 10 OS version and build release id:
try {
    `$WinRelease, `$WinVer = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR
    `$WindowsVersion = "`$(`$WinVer -join '.') (`$WinRelease)"
} catch {
    `$WindowsVersion = [System.Environment]::OSVersion.Version
}

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
    Get-ItemProperty -name Version, Release -EA 0 |
    # For The One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
    Where-Object { `$_.PSChildName -match '^(?!S)\p{L}'} |
    Select-Object @{name = ".NET Framework"; expression = {`$_.PSChildName}}, 
                @{name = "Product"; expression = {`$Lookup[`$_.Release]}}, 
                Version, Release,
    # Some OPTIONAL extra output: PSComputerName and WindowsVersion
    # The Computer name, so output from local machines will match remote machines:
    @{ name = "PSComputerName"; expression = {`$Env:Computername}},
    # The Windows Version (works on Windows 10, at least):
    @{ name = "WindowsVersion"; expression = { `$WindowsVersion }}
"@

Setting custom UITableViewCells height

If all your rows are the same height, just set the rowHeight property of the UITableView rather than implementing the heightForRowAtIndexPath. Apple Docs:

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

How do I see which checkbox is checked?

Try this

index.html

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />  
    <input type="submit" name="formSubmit" value="Submit" /> 
</form>

form.php

<html>
<head>
</head>
<body>

<?php
    if(isset($_POST['like']))
    {
        echo "<h1>You like Stackoverflow.<h1>";
    }
    else
    {
        echo "<h1>You don't like Stackoverflow.</h1>";
    }   
?>

</body>
</html>

Or this

<?php
    if(isset($_POST['like'])) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

Android Studio: Plugin with id 'android-library' not found

Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!

Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.+'
    }
}

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

How to represent a fix number of repeats in regular expression?

In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$"); for further information see the javadoc

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

Your JSON string is malformed: the type of center is an array of invalid objects. Replace [ and ] with { and } in the JSON string around longitude and latitude so they will be objects:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

How to detect shake event with android?

There are a lot of solutions to this question already, but I wanted to post one that:

  • Doesn't use a library depricated in API 3
  • Calculates the magnitude of the acceleration correctly
  • Correctly applies a timeout between shake events

Here is such a solution:

// variables for shake detection
private static final float SHAKE_THRESHOLD = 3.25f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private SensorManager mSensorMgr;

To initialize the timer:

// Get a sensor manager to listen for shakes
mSensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

// Listen for shakes
Sensor accelerometer = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
    mSensorMgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

SensorEventListener methods to override:

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        long curTime = System.currentTimeMillis();
        if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {

            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            double acceleration = Math.sqrt(Math.pow(x, 2) +
                    Math.pow(y, 2) +
                    Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
            Log.d(APP_NAME, "Acceleration is " + acceleration + "m/s^2");

            if (acceleration > SHAKE_THRESHOLD) {
                mLastShakeTime = curTime;
                Log.d(APP_NAME, "Shake, Rattle, and Roll");
            }
        }
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // Ignore
}

When you are all done

// Stop listening for shakes
mSensorMgr.unregisterListener(this);

Can't bind to 'ngIf' since it isn't a known property of 'div'

Instead of [ngIf] you should use *ngIf like this:

<div *ngIf="isAuth" id="sidebar">

How to add 20 minutes to a current date?

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

Ignore case in Python strings

Just use the str().lower() method, unless high-performance is important - in which case write that sorting method as a C extension.

"How to write a Python Extension" seems like a decent intro..

More interestingly, This guide compares using the ctypes library vs writing an external C module (the ctype is quite-substantially slower than the C extension).

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

@Autowired and static method

This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:

@Component
public class Spring {
  private static final Logger LOG = LoggerFactory.getLogger (Spring.class);

  private static Spring spring;

  @Autowired
  private ApplicationContext context;

  @PostConstruct
  public void registerInstance () {
    spring = this;
  }

  private Spring (ApplicationContext context) {
    this.context = context;
  }

  private static synchronized void initContext () {
    if (spring == null) {
      LOG.info ("Initializing Spring Context...");
      ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
      spring = new Spring (context);
    }
  }

  public static <T> T getBean(String name, Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(name, className);
  }

  public static <T> T getBean(Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(className);
  }

  public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
    initContext();
    return spring.context.getAutowireCapableBeanFactory ();
  }
}

The important piece here is the initContext method. It ensures that the context will always get initialized. But, do note that initContext will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

For me this worked: (added into .ssh\config)

Host *
HostkeyAlgorithms +ssh-dss
PubkeyAcceptedKeyTypes +ssh-dss

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Styling the arrow on bootstrap tooltips

You can use this to change tooltip-arrow color

.tooltip.bottom .tooltip-arrow {
  top: 0;
  left: 50%;
  margin-left: -5px;
  border-bottom-color: #000000; /* black */
  border-width: 0 5px 5px;
}

How to get annotations of a member variable?

Or you could try this

try {
    BeanInfo bi = Introspector.getBeanInfo(User.getClass());
    PropertyDescriptor[] properties = bi.getPropertyDescriptors();
    for(PropertyDescriptor property : properties) {
        //One way
        for(Annotation annotation : property.getAnnotations()){
            if(annotation instanceof Column) {
                String string = annotation.name();
            }
        }
        //Other way
        Annotation annotation = property.getAnnotation(Column.class);
        String string = annotation.name();
    }
}catch (IntrospectonException ie) {
    ie.printStackTrace();
}

Hope this will help.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

For me the problem was a wrong include directory. I have no idea why this caused the error with the seemingly missing lib as the include directory only contains the header files. And the library directory had the correct path set.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Solving Quadratic Equation

This line is causing problems:

(-b+math.sqrt(b**2-4*a*c))/2*a

x/2*a is interpreted as (x/2)*a. You need more parentheses:

(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)

Also, if you're already storing d, why not use it?

x = (-b + math.sqrt(d)) / (2 * a)

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

bash "if [ false ];" returns true instead of false -- why?

I found that I can do some basic logic by running something like:

A=true
B=true
if ($A && $B); then
    C=true
else
    C=false
fi
echo $C

Load vs. Stress testing

Load testing :- Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Stress Testing :- Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

The basic difference is as under

click here to see the exact difference

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

import java.util.Timer;
import java.util.TimerTask;

class Clock {
    private Timer mTimer = new Timer();

    private int mSecondsPassed = 0;
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            mSecondsPassed++;
            System.out.println("Seconds passed: " + mSecondsPassed);
        }
    };

    private void start() {
        mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
    }

    public static void main(String[] args) {
        Clock c = new Clock();
        c.start();
    }
}

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

In my case I misspelled , I was referring as ngmodel istead of ngModel :) Hope It helps!

Expected - [(ngModel)] Actual - [(ngmodel)]

jQuery add required to input fields

I have found that the following implementations are effective:

$('#freeform_first_name').removeAttr('required');

$('#freeform_first_name').attr('required', 'required');

These commands (attr, removeAttr, prop) behave differently depending on the version of JQuery you are using. Please reference the documentation here: https://api.jquery.com/attr/

How to get the path of current worksheet in VBA?

Use Application.ActiveWorkbook.Path for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName for the path with the workbook name.

How can I Remove .DS_Store files from a Git repository?

In case you want to remove DS_Store files to every folder and subfolder:


In case of already committed DS_Store:

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

Ignore them by:

echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global

Vagrant stuck connection timeout retrying

My solution to this issue was that my old laptop was taking wayyyyyyyyyyy too long to start up. I opened Virtual Box, connected to the box and waited for the screen to load. Took about 8 minutes.

Then it connected and mounted my folders and went ahead.

just be patient sometimes!

change image opacity using javascript

Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:

var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter  = 'alpha(opacity=90)'; // IE fallback

What does the "static" modifier after "import" mean?

Say you have static fields and methods inside a class called MyClass inside a package called myPackage and you want to access them directly by typing myStaticField or myStaticMethod without typing each time MyClass.myStaticField or MyClass.myStaticMethod.

Note : you need to do an import myPackage.MyClass or myPackage.* for accessing the other resources

Summing elements in a list

You can use map function and pythons inbuilt sum() function. It simplifies the solution. And reduces the complexity.
a=map(int,raw_input().split())
sum(a)
Done!

What does `m_` variable prefix mean?

One argument that I haven't seen yet is that a prefix such as m_ can be used to prevent name clashing with #define'd macro's.

Regex search for #define [a-z][A-Za-z0-9_]*[^(] in /usr/include/term.h from curses/ncurses.

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

Vue - Deep watching an array of objects and calculating the change?

I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

new Vue({
  methods: {
    setValue: function() {
      this.$data.oldPeople = _.cloneDeep(this.$data.people);
    },
  },
  mounted() {
    this.setValue();
  },
  el: '#app',
  data: {
    people: [
      {id: 0, name: 'Bob', age: 27},
      {id: 1, name: 'Frank', age: 32},
      {id: 2, name: 'Joe', age: 38}
    ],
    oldPeople: []
  },
  watch: {
    people: {
      handler: function (after, before) {
        // Return the object that changed
        var vm = this;
        let changed = after.filter( function( p, idx ) {
          return Object.keys(p).some( function( prop ) {
            return p[prop] !== vm.$data.oldPeople[idx][prop];
          })
        })
        // Log it
        vm.setValue();
        console.log(changed)
      },
      deep: true,
    }
  }
})

See the updated codepen

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Upgrade Android Studio.

I had this issue with Android Studio 1.3.1 and none of the other answers worked for me, but after updating to 1.5.1 there were no problems.

Java: How to insert CLOB into oracle database

I had similar issue. Changed one of my table column from varchar2 to CLOB. I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.

I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

AWS S3 CLI - Could not connect to the endpoint URL

You should specify the region in your CLI script, rather than rely on default region specified using aws configure (as the current most popular answer asserts). Another answer alluded to that, but the syntax is wrong if you're using CLI via AWS Tools for Powershell.

This example forces region to us-west-2 (Northern California), PowerShell syntax:

aws s3 ls --region us-west-2

"Too many characters in character literal error"

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

Reading serial data in realtime in Python

A very good solution to this can be found here:

Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.

It is also supposed to be fast according to the author:

The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.

class ReadLine:
    def __init__(self, s):
        self.buf = bytearray()
        self.s = s

    def readline(self):
        i = self.buf.find(b"\n")
        if i >= 0:
            r = self.buf[:i+1]
            self.buf = self.buf[i+1:]
            return r
        while True:
            i = max(1, min(2048, self.s.in_waiting))
            data = self.s.read(i)
            i = data.find(b"\n")
            if i >= 0:
                r = self.buf + data[:i+1]
                self.buf[0:] = data[i+1:]
                return r
            else:
                self.buf.extend(data)

ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)

while True:

    print(rl.readline())

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I already tried all of the possible solutions on stackoverflow and didn't work What I tried:

  1. Disable Hyper-V in windows feature
  2. Disable Hyper-V with command
  3. Disable Device Guard
  4. etc etc Above solution still give me information about Hyper-V in System Information and the HAXM still failed to install.

But finally I found the solution, you have to disable Hyper-V from System Configuration:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Check System Information then Hyper-V is off now

How to parse dates in multiple formats using SimpleDateFormat

If working in Java 1.8 you can leverage the DateTimeFormatterBuilder

public static boolean isTimeStampValid(String inputString)
{
    DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm:ss.SSSZ]" + "[yyyy-MM-dd]"));

    DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();

    try {
        dateTimeFormatter.parse(inputString);
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

See post: Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

Converting bool to text in C++

Use boolalpha to print bool to string.

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference

Java - Find shortest path between 2 points in a distance weighted map

This maybe too late but No one provided a clear explanation of how the algorithm works

The idea of Dijkstra is simple, let me show this with the following pseudocode.

Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.

At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.

The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.

If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.

Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.

Credits to Lars Vogel

Increment a Integer's int value?

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

How do I implement charts in Bootstrap?

Github did this using the HTML canvas element.

This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

If you use a browser inspector, you see inside every list element a div with a canvas element.

<div class="participation-graph">
   <canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>

With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.

Do a search about jquery pluggins that fit your requirement.

Hope this pointers help you to achieve that.

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

line breaks in a textarea

What I found works in the form is str_replace('&lt;br&gt;', PHP_EOL, $textarea);

Can CSS force a line break after each word in an element?

The best solution is the word-spacing property.

Add the <p> in a container with a specific size (example 300px) and after you have to add that size as the value in the word-spacing.

HTML

<div>
 <p>Sentence Here</p>
</div>

CSS

div {
 width: 300px;
}

p {
 width: auto;
 text-align: center;
 word-spacing: 300px;
}

In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.

Here an example Codepen

SQL Server equivalent of MySQL's NOW()?

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

Select N random elements from a List<T> in C#

Using linq:

YourList.OrderBy(x => rnd.Next()).Take(5)

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

MERGE INTO target
USING
(
    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    UNION ALL
    SELECT id, null some_value, 1 deleteMe
    FROM
    (
        SELECT id FROM target
        MINUS
        SELECT id FROM source
    )
) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
WHEN NOT MATCHED THEN
    INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;


--Results:
select * from target;

ID  SOME_VALUE   ISDELETED
1   new value 1  0
2   old value 2  1
3   new value 3  0

How to enable native resolution for apps on iPhone 6 and 6 Plus?

I didn't want to introduce an asset catalog.

Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]

<key>UILaunchImages</key>
<array>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-667h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{375, 667}</string>
    </dict>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-736h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{414, 736}</string>
    </dict>
</array>

Archive the artifacts in Jenkins

Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.

A common convention is to put the result of a build into a build, target or bin directory.

The Jenkins archiver can use globs (target/*.jar) to easily pick up the right file even if you have a unique name per build.

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

Open a webpage in the default browser

This worked perfectly for me. Since this is for personal use, I used Firefox as my browser.

 Dim url As String
    url = "http://www.google.com"
    Process.Start("Firefox", url)

ggplot2: sorting a plot

I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .

As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.

I get the desired result by adding + xlim(rev(levels(x$variable))) to the ggplot statement:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))

This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim() should work in general.

Postgres user does not exist?

The solution is simple:
log in as root
and after:

su - postgres

psql

How to install Hibernate Tools in Eclipse?

Well, most convenient and safest way is to use JBoss update site within Eclipse software updates (Help -> Software Updates... -> Add Site...):

The latest stable release update site for JBoss Tools

There you can find Hibernate tools together with other handy JBoss plugins.

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

How to use php serialize() and unserialize()

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


Take for example this common problem:

How do I pass a PHP array to Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript can easily reverse this into an actual Javascript array.

This is just as valid a representation of the same data structure though:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

A simple explanation of Naive Bayes Classification

Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.

In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.

During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.

So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.

The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.

In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.

Now I come to your other question about Naive Bayes.

To demonstrate the concept of Naïve Bayes Classification, consider the example given below:

enter image description here

As indicated, the objects can be classified as either GREEN or RED. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.

Since there are twice as many GREEN objects as RED, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership GREEN rather than RED. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of GREEN and RED objects, and often used to predict outcomes before they actually happen.

Thus, we can write:

Prior Probability of GREEN: number of GREEN objects / total number of objects

Prior Probability of RED: number of RED objects / total number of objects

Since there is a total of 60 objects, 40 of which are GREEN and 20 RED, our prior probabilities for class membership are:

Prior Probability for GREEN: 40 / 60

Prior Probability for RED: 20 / 60

Having formulated our prior probability, we are now ready to classify a new object (WHITE circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN (or RED) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

enter image description here

enter image description here

From the illustration above, it is clear that Likelihood of X given GREEN is smaller than Likelihood of X given RED, since the circle encompasses 1 GREEN object and 3 RED ones. Thus:

enter image description here

enter image description here

Although the prior probabilities indicate that X may belong to GREEN (given that there are twice as many GREEN compared to RED) the likelihood indicates otherwise; that the class membership of X is RED (given that there are more RED objects in the vicinity of X than GREEN). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

enter image description here

Finally, we classify X as RED since its class membership achieves the largest posterior probability.

Angular: How to update queryParams without changing route

In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.

  let urlTree = this.router.parseUrl(this.router.url);
  urlTree.queryParams['newParamKey'] = 'newValue';

  this.router.navigateByUrl(urlTree); 

The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.

import { Router } from '@angular/router';

constructor(private router: Router) { }

appendAQueryParam() {

  const urlTree = this.router.createUrlTree([], {
    queryParams: { newParamKey: 'newValue' },
    queryParamsHandling: "merge",
    preserveFragment: true });

  this.router.navigateByUrl(urlTree); 
}

In order to remove a query parameter this way you can set it to undefined or null.

Is header('Content-Type:text/plain'); necessary at all?

It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser;

<?php
header('Content-Type:text/html');
?>
<p>Hello</p>

You will see:

hello

(note that you will get the same results if you miss off the header line in this case - text/html is php's default)

Change it to text/plain

<?php
header('Content-Type:text/plain');
?>
<p>Hello</p>

You will see:

<p>Hello</p>

Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request:

<?php
header('Content-Type:text/html');
print "Your name is " . $_GET['name']

Someone can put a link to a URL like http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe.

Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.

PHP script to loop through all of the files in a directory?

If you don't have access to DirectoryIterator class try this:

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

How do I monitor all incoming http requests?

You might consider running Fiddler as a reverse proxy, you should be able to get clients to connect to Fiddler's address and then forward the requests from Fiddler to your application.

This will require either a bit of port manipulation or client config, depending on what's easier based on your requirements.

Details of how to do it are here: http://www.fiddler2.com/Fiddler/Help/ReverseProxy.asp

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

Note about bug of MySQL Connector/C on macOS (my current version is 10.13.2), fix the mysql_config and reinstall mysqlclient or MySQL-python, here is the detail

Android setOnClickListener method - How does it work?

That what manual says about setOnClickListener method is:

public void setOnClickListener (View.OnClickListener l)

Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.

Parameters

l View.OnClickListener: The callback that will run

And normally you have to use it like this

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
    ...
}

Take a look at this lesson as well Building a Simple Calculator using Android Studio.

Why fragments, and when to use fragments instead of activities?

#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?

Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;

  • The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.

  • The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.

  • You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.

  • Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.

  • You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.

Bonus 2

The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.

How can I display a tooltip on an HTML "option" tag?

If increasing the number of visible options is available, the following might work for you:

<html>
    <head>
        <title>Select Option Tooltip Test</title>
        <script>
            function showIETooltip(e){
                if(!e){var e = window.event;}
                var obj = e.srcElement;
                var objHeight = obj.offsetHeight;
                var optionCount = obj.options.length;
                var eX = e.offsetX;
                var eY = e.offsetY;

                //vertical position within select will roughly give the moused over option...
                var hoverOptionIndex = Math.floor(eY / (objHeight / optionCount));

                var tooltip = document.getElementById('dvDiv');
                tooltip.innerHTML = obj.options[hoverOptionIndex].title;

                mouseX=e.pageX?e.pageX:e.clientX;
                mouseY=e.pageY?e.pageY:e.clientY;

                tooltip.style.left=mouseX+10;
                tooltip.style.top=mouseY;

                tooltip.style.display = 'block';

                var frm = document.getElementById("frm");
                frm.style.left = tooltip.style.left;
                frm.style.top = tooltip.style.top;
                frm.style.height = tooltip.offsetHeight;
                frm.style.width = tooltip.offsetWidth;
                frm.style.display = "block";
            }
            function hideIETooltip(e){
                var tooltip = document.getElementById('dvDiv');
                var iFrm = document.getElementById('frm');
                tooltip.innerHTML = '';
                tooltip.style.display = 'none';
                iFrm.style.display = 'none';
            }
        </script>
    </head>
    <body>
        <select onmousemove="showIETooltip();" onmouseout="hideIETooltip();" size="10">
            <option title="Option #1" value="1">Option #1</option>
            <option title="Option #2" value="2">Option #2</option>
            <option title="Option #3" value="3">Option #3</option>
            <option title="Option #4" value="4">Option #4</option>
            <option title="Option #5" value="5">Option #5</option>
            <option title="Option #6" value="6">Option #6</option>
            <option title="Option #7" value="7">Option #7</option>
            <option title="Option #8" value="8">Option #8</option>
            <option title="Option #9" value="9">Option #9</option>
            <option title="Option #10" value="10">Option #10</option>
        </select>
        <div id="dvDiv" style="display:none;position:absolute;padding:1px;border:1px solid #333333;;background-color:#fffedf;font-size:smaller;z-index:999;"></div>
        <iframe id="frm" style="display:none;position:absolute;z-index:998"></iframe>
    </body>
</html>

How to connect PHP with Microsoft Access database

If you are struggling with the connection in the XAMPP environment I suggest uncommenting the following entry in the php.ini file.

extension = odbc

I received an error without it: Uncaught pdoexception: could not find driver

Type List vs type ArrayList in Java

I would say that 1 is preferred, unless

  • you are depending on the implementation of optional behavior* in ArrayList, in that case explicitly using ArrayList is more clear
  • You will be using the ArrayList in a method call which requires ArrayList, possibly for optional behavior or performance characteristics

My guess is that in 99% of the cases you can get by with List, which is preferred.

  • for instance removeAll, or add(null)

Pass Model To Controller using Jquery/Ajax

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

XAMPP Object not found error

I was getting this error

https://docs.google.com/file/d/0B-dUcqacTOLPcmI3SENMZFBLWG8/edit?usp=drivesdk

but I have done some coding into htdocs/index.php and made this like wamp homepage some thing like this

https://docs.google.com/file/d/0B-dUcqacTOLPVC1ORS1saGdOclU/edit?usp=drivesdk

What is "Connect Timeout" in sql server connection string?

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

Principal Component Analysis (PCA) in Python

Another Python PCA using numpy. The same idea as @doug but that one didn't run.

from numpy import array, dot, mean, std, empty, argsort
from numpy.linalg import eigh, solve
from numpy.random import randn
from matplotlib.pyplot import subplots, show

def cov(X):
    """
    Covariance matrix
    note: specifically for mean-centered data
    note: numpy's `cov` uses N-1 as normalization
    """
    return dot(X.T, X) / X.shape[0]
    # N = data.shape[1]
    # C = empty((N, N))
    # for j in range(N):
    #   C[j, j] = mean(data[:, j] * data[:, j])
    #   for k in range(j + 1, N):
    #       C[j, k] = C[k, j] = mean(data[:, j] * data[:, k])
    # return C

def pca(data, pc_count = None):
    """
    Principal component analysis using eigenvalues
    note: this mean-centers and auto-scales the data (in-place)
    """
    data -= mean(data, 0)
    data /= std(data, 0)
    C = cov(data)
    E, V = eigh(C)
    key = argsort(E)[::-1][:pc_count]
    E, V = E[key], V[:, key]
    U = dot(data, V)  # used to be dot(V.T, data.T).T
    return U, E, V

""" test data """
data = array([randn(8) for k in range(150)])
data[:50, 2:4] += 5
data[50:, 2:5] += 5

""" visualize """
trans = pca(data, 3)[0]
fig, (ax1, ax2) = subplots(1, 2)
ax1.scatter(data[:50, 0], data[:50, 1], c = 'r')
ax1.scatter(data[50:, 0], data[50:, 1], c = 'b')
ax2.scatter(trans[:50, 0], trans[:50, 1], c = 'r')
ax2.scatter(trans[50:, 0], trans[50:, 1], c = 'b')
show()

Which yields the same thing as the much shorter

from sklearn.decomposition import PCA

def pca2(data, pc_count = None):
    return PCA(n_components = 4).fit_transform(data)

As I understand it, using eigenvalues (first way) is better for high-dimensional data and fewer samples, whereas using Singular value decomposition is better if you have more samples than dimensions.

Visual studio code CSS indentation and formatting

Install HookyQR.beautify extension. It will beautify your javascript, JSON, CSS, Sass, and HTML in Visual Studio Code. It is the most use extensions for this purpose

Sort ObservableCollection<string> through C#

myObservableCollection.ToList().Sort((x, y) => x.Property.CompareTo(y.Property));

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

Do Facebook Oauth 2.0 Access Tokens Expire?

This is a fair few years later, but the Facebook Graph API Explorer now has a little info symbol next to the access token that allows you to access the access token tool app, and extend the API token for a couple of months. Might be helpful during development.

enter image description here

Property getters and setters

Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.

Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:

class Point {
  private var _x: Int = 0             // _x -> backingX
  var x: Int {
    set { _x = 2 * newValue }
    get { return _x / 2 }
  }
}

Specifically, in the Swift REPL:

 15> var pt = Point()
pt: Point = {
  _x = 0
}
 16> pt.x = 10
 17> pt
$R3: Point = {
  _x = 20
}
 18> pt.x
$R4: Int = 10

Last Key in Python Dictionary

yes there is : len(data)-1.

For the first element it´s : 0

How to load local html file into UIWebView

by this you can load html file which is in your project Assets(bundle) to webView.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

may be this is useful to you.

Eliminate space before \begin{itemize}

The "proper" LaTeX ways to do it is to use a package which allows you to specify the spacing you want. There are several such package, and these two pages link to lists of them...

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

Import a file from a subdirectory?

Create an empty file __init__.py in subdirectory /lib. And add at the begin of main code

from __future__ import absolute_import 

then

import lib.BoxTime as BT
...
BT.bt_function()

or better

from lib.BoxTime import bt_function
...
bt_function()

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

Method call if not null in C#

I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.

Extension Methods ( IfNotNull method )

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList();

    List<Address> allAddresses = GetAllAddresses();
    List<Employee> employees = GetAllEmployees(); // count > 1000

    List<Address> addresses = new List<Address>();

    for (int i = 0; i < employees.Count; i += 1000)
    {
        int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000;
        var query = (from address in allAddresses
                     where employees.GetRange(i, count).Contains(address.EmployeeId)
                     && address.State == "UT"
                     select address).ToList();

        addresses.AddRange(query);
    }

Hope this helps someone.

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

How can Print Preview be called from Javascript?

You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.

That's why your example uses Active X, which bypasses the JavaScript security issues.

So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.

Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.

What is the max size of VARCHAR2 in PL/SQL and SQL?

If you use UTF-8 encoding then one character can takes a various number of bytes (2 - 4). For PL/SQL the varchar2 limit is 32767 bytes, not characters. See how I increase a PL/SQL varchar2 variable of the 4000 character size:

SQL> set serveroutput on
SQL> l
  1  declare
  2    l_var varchar2(30000);
  3  begin
  4    l_var := rpad('A', 4000);
  5    dbms_output.put_line(length(l_var));
  6    l_var := l_var || rpad('B', 10000);
  7    dbms_output.put_line(length(l_var));
  8* end;
SQL> /
4000
14000

PL/SQL procedure successfully completed.

But you can't insert into your table the value of such variable:

SQL> ed
Wrote file afiedt.buf

  1  create table ttt (
  2    col1 varchar2(2000 char)
  3* )
SQL> /

Table created.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    l_var varchar2(30000);
  3  begin
  4      l_var := rpad('A', 4000);
  5      dbms_output.put_line(length(l_var));
  6      l_var := l_var || rpad('B', 10000);
  7      dbms_output.put_line(length(l_var));
  8      insert into ttt values (l_var);
  9* end;
SQL> /
4000
14000
declare
*
ERROR at line 1:
ORA-01461: can bind a LONG value only for insert into a LONG column
ORA-06512: at line 8

As a solution, you can try to split this variable's value into several parts (SUBSTR) and store them separately.

Where is my .vimrc file?

In SUSE Linux Enterprise Server (SLES) and openSUSE the global one is located at /etc/vimrc.

To edit it, simply do vi /etc/vimrc.

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

How to get xdebug var_dump to show full object/array

I know this is a super old post, but I figured this may still be helpful.

If you're comfortable with reading json format you could replace your var_dump with:

return json_encode($myvar);

I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.

Also, because the json_encoded data is a string it means you can write it to the error log easily

error_log(json_encode($myvar));

It probably isn't the best choice for every situation, but it's a choice!

Submitting a form by pressing enter without a submit button

Here is the code that worked to me sure it will help you

<form name="loginBox" target="#here" method="post">
  <input name="username" type="text" /><br />
  <input name="password" type="password" />
  <input type="submit" />
</form>

<script type="text/javascript">
  $(function () {
    $("form").each(function () {
      $(this)
        .find("input")
        .keypress(function (e) {
          if (e.which == 10 || e.which == 13) {
            this.form.submit();
          }
        });
      $(this).find("input[type=submit]").hide();
    });
  });
</script>

jQuery when element becomes visible

I like plugin https://github.com/hazzik/livequery It works without timers!

Simple usage

$('.some:visible').livequery( function(){ ... } );

But you need to fix a mistake. Replace line

$jQlq.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html', 'prop', 'removeProp');

to

$jQlq.registerPlugin('show', 'append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html', 'prop', 'removeProp');

Reading numbers from a text file into an array in C

5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as

5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  

for 16 numbers.

If your file has input

5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 

then change %d specifier in your fscanf to %d,.

  fscanf(myFile, "%d,", &numberArray[i] );  

Here is your full code after few modifications:

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE *myFile;
    myFile = fopen("somenumbers.txt", "r");

    //read file into array
    int numberArray[16];
    int i;

    if (myFile == NULL){
        printf("Error Reading File\n");
        exit (0);
    }

    for (i = 0; i < 16; i++){
        fscanf(myFile, "%d,", &numberArray[i] );
    }

    for (i = 0; i < 16; i++){
        printf("Number is: %d\n\n", numberArray[i]);
    }

    fclose(myFile);

    return 0;
}

How do I extend a class with c# extension methods?

They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending’’ methods. Extension methods are not instance members on the type. The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.

Check the full example here http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201

Example:

class Extension
    {
        static void Main(string[] args)
        {
            string s = "sudhakar";
            Console.WriteLine(s.GetWordCount());
            Console.ReadLine();
        }

    }
    public static class MyMathExtension
    {

        public static int GetWordCount(this System.String mystring)
        {
            return mystring.Length;
        }
    }

start/play embedded (iframe) youtube-video on click of an image

You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.

What's the easiest way to install a missing Perl module?

On Fedora you can use

# yum install foo

as long as Fedora has an existing package for the module.

How can I install Visual Studio Code extensions offline?

Now you can download an extension directly in the "Resources" section, there's a "Download extension" link, I hope this information is still useful.

Controller 'ngModel', required by directive '...', can't be found

You can also remove the line

  require: 'ngModel',

if you don't need ngModel in this directive. Removing ngModel will allow you to make a directive without thatngModel error.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Java: how to convert HashMap<String, Object> to array

To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Sets which offer no guarantee as to order.

Map<String, Object> map = new HashMap<String, Object>();
String[] keys = new String[map.size()];
Object[] values = new Object[map.size()];
int index = 0;
for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
    keys[index] = mapEntry.getKey();
    values[index] = mapEntry.getValue();
    index++;
}

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

How to resolve the "ADB server didn't ACK" error?

I've got a kind of botch for the old ADB server didn't ACK * failed to start daemon * issue which might help, though i haven't seen anyone else with my problem so maybe not. Anyway...

I changed the default install location for my HTC sensation to 2 (SD card), but when trying to revert back to 0 (internal) i was getting this error. Looking in task manager showed there were 2 instances of adb.exe running, one of which kept stopping and starting and was impossible to kill, the other could be killed but then a new instance would start almost immediately.

The only way i could get adb to start successfully was to get my command ready in the command window, go to task manager to end the adb.exe, then when the window came up saying 'are you sure you want to kill adb.exe' dragged that over the command window, clicked OK then immediately pressed Enter to run the command. It seems that the short window between adb.exe being killed and restarting itself is sufficient to run a command, though if you try to do something else it won't work and you have to repeat this process each time you want to run a command.

PITA but it's the only way an uneducated numpty like myself could get round it - hopefully it'll help someone...

How to add text inside the doughnut chart using Chart.js?

This is based on Cmyker's update for Chart.js 2. (posted as another answer as I can't comment yet)

I had an issue with the text alignment on Chrome when the legend is displayed as the chart height does not include this so it's not aligned correctly in the middle. Fixed this by accounting for this in the calculation of fontSize and textY.

I calculated percentage inside the method rather than a set value as I have multiple of these on the page. Assumptions are that your chart only has 2 values (otherwise what is the percentage of? and that the first is the one you want to show the percentage for. I have a bunch of other charts too so I do a check for type = doughnut. I'm only using doughnuts to show percentages so it works for me.

Text color seems a bit hit and miss depending on what order things run in etc so I ran into an issue when resizing that the text would change color (between black and the primary color in one case, and secondary color and white in another) so I "save" whatever the existing fill style was, draw the text (in the color of the primary data) then restore the old fill style. (Preserving the old fill style doesn't seem needed but you never know.)

https://jsfiddle.net/g733tj8h/

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx,
        type = chart.config.type;

    if (type == 'doughnut')
    {
      var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
                    (chart.config.data.datasets[0].data[0] +
                    chart.config.data.datasets[0].data[1]));
      var oldFill = ctx.fillStyle;
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);

      ctx.restore();
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle"

      var text = percent + "%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = (height + chart.chartArea.top) / 2;

      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
      ctx.fillText(text, textX, textY);
      ctx.fillStyle = oldFill;
      ctx.save();
    }
  }
});

_x000D_
_x000D_
var data = {_x000D_
  labels: ["Red","Blue"],_x000D_
  datasets: [_x000D_
    {_x000D_
      data: [300, 50],_x000D_
      backgroundColor: ["#FF6384","#36A2EB"],_x000D_
    }]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
  beforeDraw: function(chart) {_x000D_
    var width = chart.chart.width,_x000D_
        height = chart.chart.height,_x000D_
        ctx = chart.chart.ctx,_x000D_
        type = chart.config.type;_x000D_
_x000D_
    if (type == 'doughnut')_x000D_
    {_x000D_
     var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /_x000D_
                    (chart.config.data.datasets[0].data[0] +_x000D_
                    chart.config.data.datasets[0].data[1]));_x000D_
   var oldFill = ctx.fillStyle;_x000D_
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);_x000D_
      _x000D_
      ctx.restore();_x000D_
      ctx.font = fontSize + "em sans-serif";_x000D_
      ctx.textBaseline = "middle"_x000D_
_x000D_
      var text = percent + "%",_x000D_
          textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
          textY = (height + chart.chartArea.top) / 2;_x000D_
   _x000D_
      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];_x000D_
      ctx.fillText(text, textX, textY);_x000D_
      ctx.fillStyle = oldFill;_x000D_
      ctx.save();_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
var myChart = new Chart(document.getElementById('myChart'), {_x000D_
  type: 'doughnut',_x000D_
  data: data,_x000D_
  options: {_x000D_
   responsive: true,_x000D_
    legend: {_x000D_
      display: true_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
_x000D_
_x000D_

How do I create batch file to rename large number of files in a folder?

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=Vacation2010
SET new=December
for /f "tokens=*" %%f in ('dir /b *.jpg') do (
  SET newname=%%f
  SET newname=!newname:%old%=%new%!
  move "%%f" "!newname!"
)

What this does is it loops over all .jpg files in the folder where the batch file is located and replaces the Vacation2010 with December inside the filenames.

What is the difference between Task.Run() and Task.Factory.StartNew()

The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).

However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.

For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.

One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:

Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);

As it is stated here:

So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method. This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters. It’s a shortcut. In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters. When you pass an Action to Task.Run:

Task.Run(someAction);

that’s exactly equivalent to:

Task.Factory.StartNew(someAction, 
    CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

Error in plot.new() : figure margins too large, Scatter plot

Invoking dev.off() to make RStudio open up a new graphics device with default settings worked for me. HTH.

html button to send email

You can use mailto, here is the HTML code:

<a href="mailto:EMAILADDRESS">

Replace EMAILADDRESS with your email.

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

The same problem when I used 'org.springframework.android:spring-android-rest-template:2.0.0.M1' in Android Studio 1.0.1. I need include this in build.gradle

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

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.

Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).

I.e. This will not work

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);

but this will work:

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);

The effect is the same if using the EnableCors Attribute.

Javascript: Unicode string to hex

Here you go. :D

"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"

for non unicode

"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"

ASCII (utf-8) binary HEX string to string

"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

String to ASCII (utf-8) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")

--- unicode ---

String to UNICODE (utf-16) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")

UNICODE (utf-16) binary HEX string to string

"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

Pretty printing XML in Python

Use etree.indent and etree.tostring

import lxml.etree as etree

root = etree.fromstring('<html><head></head><body><h1>Welcome</h1></body></html>')
etree.indent(root, space="  ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)

output

<html>
  <head/>
  <body>
    <h1>Welcome</h1>
  </body>
</html>

Removing namespaces and prefixes

import lxml.etree as etree


def dump_xml(element):
    for item in element.getiterator():
        item.tag = etree.QName(item).localname

    etree.cleanup_namespaces(element)
    etree.indent(element, space="  ")
    result = etree.tostring(element, pretty_print=True).decode()
    return result


root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)

output

<document>
  <name>hello world</name>
</document>

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

Running the new Intel emulator for Android

Not every processor is supporting the virtualization!

To find out your chipset abilities go to http://ark.intel.com/, insert the name of your processor in the search line and check out the resolve.

Advanced Technologies: ...

Intel® Virtualization Technology (VT-x) = ???

If you see "No", you can forget HAXM!

Can Windows Containers be hosted on linux?

We can run Linux containers on Windows. Docker for Windows uses Hyper-v based Linux-Kit or WSL2 as backend to facilitate Linux containers.

If any Linux distribution having this kind of setup, we can run Windows containers. Docker for Linux supports only Linux containers.

jQuery scroll() detect when user stops scrolling

please check the jquery mobile scrollstop event

$(document).on("scrollstop",function(){
  alert("Stopped scrolling!");
});

Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

Display loading image while post with ajax

make sure to change in ajax call

async: true,
type: "GET",
dataType: "html",

How to change the background color of the options menu?

After spending a considerable amount of time trying all the options, the only way I was able to get an app using AppCompat v7 to change the overflow menu background was using the itemBackground attribute:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="android:itemBackground">@color/overflow_background</item>
    ...
</style>

Tested from API 4.2 to 5.0.

Xampp MySQL not starting - "Attempting to start MySQL service..."

Did you use the default installation path?

In my case, when i ran mysql_start.bat I got the following error:

Can`t find messagefile 'D:\xampp\mysql\share\errmsg.sys'

I moved my xampp folder to the root of the drive and it started working.

Hope it helps

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

just remove password

Change this

mydb = mysql.connector.connect(host="localhost",user="root",password='password',auth_plugin='mysql_native_password')

To this

mydb = mysql.connector.connect(host="localhost",user="root",auth_plugin='mysql_native_password')

It worked for me

Server Discovery And Monitoring engine is deprecated

I want to add to this thread that it may also have to do with other dependencies.

For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.

enter image description here

Difference between char* and const char*?

Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.

What is the difference between char * const and const char *?

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

In jQuery, how do I get the value of a radio button when they all have the same name?

in your selector, you should also specify that you want the checked radiobutton:

$(function(){
    $("#submit").click(function(){      
        alert($('input[name=q12_3]:checked').val());
    });
 });

Android Shared preferences for creating one time activity (example)

You could also take a look at a past sample project of mine, written for this purpose. I saves locally a name and retrieves it either upon a user's request or when the app starts.

But, at this time, it would be better to use commit (instead of apply) for persisting the data. More info here.

Get selected text from a drop-down list (select box) using jQuery

 $("#selectID option:selected").text();

Instead of #selectID you can use any jQuery selector, like .selectClass using class.

As mentioned in the documentation here.

The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them.

.text() As per the documentation here.

Get the combined text contents of each element in the set of matched elements, including their descendants.

So you can take text from any HTML element using the .text() method.

Refer the documentation for a deeper explanation.

How to use bootstrap-theme.css with bootstrap 3?

Upon downloading Bootstrap 3.x, you'll get bootstrap.css and bootstrap-theme.css (not to mention the minified versions of these files that are also present).

bootstrap.css

bootstrap.css is completely styled and ready to use, if such is your desire. It is perhaps a bit plain but it is ready and it is there.

You do not need to use bootstrap-theme.css if you don't want to and things will be just fine.

bootstrap-theme.css

bootstrap-theme.css is just what the name of the file is trying to suggest: it is a theme for bootstrap that is creatively considered 'THE bootstrap theme'. The name of the file confuses things just a bit since the base bootstrap.css already has styling applied and I, for one, would consider those styles to be the default. But that conclusion is apparently incorrect in light of things said in the Bootstrap documentation's examples section in regard to this bootstrap-theme.css file:

"Load the optional Bootstrap theme for a visually enhanced experience."

The above quote is found here http://getbootstrap.com/getting-started/#examples on a thumbnail that links to this example page http://getbootstrap.com/examples/theme/. The idea is that bootstrap-theme.css is THE bootstrap theme AND it's optional.

Themes at BootSwatch.com

About the themes at BootSwatch.com: These themes are not implemented like bootstrap-theme.css. The BootSwatch themes are modified versions of the original bootstrap.css. So, you should definitely NOT use a theme from BootSwatch AND the bootstrap-theme.css file at the same time.

Custom Theme

About Your Own Custom Theme: You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

smooth scroll to top

Some time has passed since this was asked.

Now it is possible to not only specify number to window.scroll function, but also pass an object with three properties: top, left and behavior. So if we would like to have a smooth scroll up with native JavaScript, we can now do something like this:

let button = document.querySelector('button-id');
let options = {top: 0, left: 0, behavior: 'smooth'}; // left and top are coordinates
button.addEventListener('click', () => { window.scroll(options) });

https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

Where is android_sdk_root? and how do I set it.?

In Android Studio 3.2.1 I got this error because I installed a new API(28) level emulator without installing that API SDK components. After I installed SDK platform and SDK platform tools for the API level 28 and updated Android Emulator the emulator started running.

Hope it may help someone.

Angular JS POST request not sending JSON data

you can use your method by this way

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/apiControllerName/methodName',
    method: 'POST',
    params: {application:app, from:d1, to:d2},
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    //timeout: 1,
    //cache: false,
    //transformRequest: false,
    //transformResponse: false
}).then(function (results) {
    return results;
}).catch(function (e) {

});

How to convert int to float in C?

This should give you the result you want.

double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);

Note that the first operand is a double

Loading local JSON file

In TypeScript you can use import to load local JSON files. For example loading a font.json:

import * as fontJson from '../../public/fonts/font_name.json';

This requires a tsconfig flag --resolveJsonModule:

// tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

For more information see the release notes of typescript: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

ssh script returns 255 error

This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.

ssh returns 255 when an error occurred or 255 is returned by the remote script:

 EXIT STATUS

     ssh exits with the exit status of the remote command or
     with 255 if an error occurred.

Usually you would an error message something similar to:

ssh: connect to host host.domain.com port 22: No route to host

Or

ssh: connect to host HOSTNAME port 22: Connection refused

Check-list:

  • What happens if you run the ssh command directly from the command line?

  • Are you able to ping that machine?

  • Does the remote has ssh installed?

  • If installed, then is the ssh service running?

Reading/Writing a MS Word file in PHP

phpLiveDocx is a Zend Framework component and can read and write DOC and DOCX files in PHP on Linux, Windows and Mac.

See the project web site at:

http://www.phplivedocx.org

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

Select and display only duplicate records in MySQL

I think this way is the simplier. The output displays the id and the payer's email where the payer's email is in more than one record at this table. The results are sorted by id.

    SELECT id, payer_email
    FROM paypal_ipn_orders
    WHERE COUNT( payer_email )>1
    SORT BY id;

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Try a different protocol. git:// may have problems from your firewall, for example; try a git clone with https: instead.

CSS: 100% width or height while keeping aspect ratio?

Simple solution:

min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
margin: 0;
padding: 0;

By the way, if you want to center it in a parent div container, you can add those css properties:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

It should really work as expected :)

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

List of encodings that Node.js supports

The encodings are spelled out in the buffer documentation.

Buffers and character encodings:

Character Encodings

  • utf8: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.
  • utf16le: Multi-byte encoded Unicode characters. Unlike utf8, each character in the string will be encoded using either 2 or 4 bytes.
  • latin1: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000 to U+00FF.

Binary-to-Text Encodings

  • base64: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.
  • hex: Encode each byte as two hexadecimal characters.

Legacy Character Encodings

  • ascii: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.
  • binary: Alias for 'latin1'.
  • ucs2: Alias of 'utf16le'.

How to dynamically create CSS class in JavaScript and apply?

Looked through the answers and the most obvious and straight forward is missing: use document.write() to write out a chunk of CSS you need.

Here is an example (view it on codepen: http://codepen.io/ssh33/pen/zGjWga):

<style>
   @import url(http://fonts.googleapis.com/css?family=Open+Sans:800);
   .d, body{ font: 3vw 'Open Sans'; padding-top: 1em; }
   .d {
       text-align: center; background: #aaf;
       margin: auto; color: #fff; overflow: hidden; 
       width: 12em; height: 5em;
   }
</style>

<script>
   function w(s){document.write(s)}
   w("<style>.long-shadow { text-shadow: ");
   for(var i=0; i<449; i++) {
      if(i!= 0) w(","); w(i+"px "+i+"px #444");
   }
   w(";}</style>");
</script> 

<div class="d">
    <div class="long-shadow">Long Shadow<br> Short Code</div>
</div>

Pandas: rolling mean by time interval

visualize the rolling averages to see if it makes sense. I don't understand why sum was used when the rolling average was requested.

  df=pd.read_csv('poll.csv',parse_dates=['enddate'],dtype={'favorable':np.float,'unfavorable':np.float,'other':np.float})

  df.set_index('enddate')
  df=df.fillna(0)

 fig, axs = plt.subplots(figsize=(5,10))
 df.plot(x='enddate', ax=axs)
 plt.show()


 df.rolling(window=3,min_periods=3).mean().plot()
 plt.show()
 print("The larger the window coefficient the smoother the line will appear")
 print('The min_periods is the minimum number of observations in the window required to have a value')

 df.rolling(window=6,min_periods=3).mean().plot()
 plt.show()

How can I get a list of users from active directory?

PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.

Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx

Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all

using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
    using (var searcher = new DirectorySearcher(root))
    {
        // looking for a specific user
        searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
        // I only care about what groups the user is a memberOf
        searcher.PropertiesToLoad.Add("memberOf");

        // FYI, non-null results means the user was found
        var results = searcher.FindOne();

        var properties = results?.Properties;
        if (properties?.Contains("memberOf") == true)
        {
            // ... iterate over all the groups the user is a member of
        }
    }
}

Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.

For authenticating the user:

using (var context = new PrincipalContext(ContextType.Domain))
{
    return context.ValidateCredentials(username, password);
}

Unable to preventDefault inside passive event listener

To still be able to scroll this worked for me

if (e.changedTouches.length > 1) e.preventDefault();

How do I get unique elements in this array?

This should work for you:

Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.

#An array of multiple data entries
@table1 = Table1.find(:all) 

#extracts **activity** for each entry in the array @table1, and returns only the ones which are unique 

@unique_activities = @table1.map{|t| t.activity}.uniq 

how to display full stored procedure code?

use pgAdmin or use pg_proc to get the source of your stored procedures. pgAdmin does the same.

MySQL - UPDATE query with LIMIT

I would suggest a two step query

I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id, substitute with whatever your PK is called.

1 - figure out the primary key number for column 1000.

SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000

2 - update the table.

UPDATE smartmeter_usage.users_reporting SET panel_id = 3 
WHERE panel_id IS NULL AND id >= @id 
ORDER BY id 
LIMIT 1000

Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.

JSON find in JavaScript

I had come across this issue for a complex model with several nested objects. A good example of what I was looking at doing would be this: Lets say you have a polaroid of yourself. And that picture is then put into a trunk of a car. The car is inside of a large crate. The crate is in the hold of a large ship with many other crates. I had to search the hold, look in the crates, check the trunk, and then look for an existing picture of me.

I could not find any good solutions online to use, and using .filter() only works on arrays. Most solutions suggested just checking to see if model["yourpicture"] existed. This was very undesirable because, from the example, that would only search the hold of the ship and I needed a way to get them from farther down the rabbit hole.

This is the recursive solution I made. In comments, I confirmed from T.J. Crowder that a recursive version would be required. I thought I would share it in case anyone came across a similar complex situation.

function ContainsKeyValue( obj, key, value ){
    if( obj[key] === value ) return true;
    for( all in obj )
    {
        if( obj[all] != null && obj[all][key] === value ){
            return true;
        }
        if( typeof obj[all] == "object" && obj[all]!= null ){
            var found = ContainsKeyValue( obj[all], key, value );
            if( found == true ) return true;
        }
    }
    return false;
}

This will start from a given object inside of the graph, and recurse down any objects found. I use it like this:

var liveData = [];
for( var items in viewmodel.Crates )
{
    if( ContainsKeyValue( viewmodel.Crates[items], "PictureId", 6 ) === true )
    {
        liveData.push( viewmodel.Crates[items] );
    }
}

Which will produce an array of the Crates which contained my picture.

PHP Remove elements from associative array

$key = array_search("Mark As Spam", $array);
unset($array[$key]);

For 2D arrays...

$remove = array("Mark As Spam", "Completed");
foreach($arrays as $array){
    foreach($array as $key => $value){
        if(in_array($value, $remove)) unset($array[$key]);
    }
}

Where do alpha testers download Google Play Android apps?

You need to publish the app before it becomes available for testing.

if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.

EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.

Only the direct link to the application package will work. (only for the activated testers).

Angular 2 / 4 / 5 not working in IE11

I have an Angular4 application, even for me also it was not working in IE11 browser, i have done below changes, now its working correctly. Just add below code in the index.html file

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Just you need to uncomment these below lines from polyfills.ts file

import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

These above 2 steps will solve your problem, please let me know if anything will be there. Thanks!!!

Simple proof that GUID is not unique

GUIDs are 124 bits because 4 bits hold the version number.