Programs & Examples On #Pyrex

0

Get JSF managed bean by name in any Servlet related class

I use the following method:

public static <T> T getBean(final String beanName, final Class<T> clazz) {
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
}

This allows me to get the returned object in a typed manner.

How can I search for a commit message on GitHub?

As of mid-2019

  1. type your query in the top left search box
  2. hit Enter
  3. click "Commits"

Screenshot:

enter image description here

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

How to get day of the month?

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(aDate);
    return cal.get(Calendar.DAY_OF_MONTH);
}

Missing XML comment for publicly visible type or member

Jon Skeet's answer works great for when you're building with VisualStudio. However, if you're building the sln via the command line (in my case it was via Ant) then you may find that msbuild ignores the sln supression requests.

Adding this to the msbuild command line solved the problem for me:

/p:NoWarn=1591

Laravel Advanced Wheres how to pass variable into function?

@kajetons' answer is fully functional.

You can also pass multiple variables by passing them like: use($var1, $var2)

DB::table('users')->where(function ($query) use ($activated,$var2) {
    $query->where('activated', '=', $activated);
    $query->where('var2', '>', $var2);
})->get();

pandas read_csv and filter columns with usecols

This code achieves what you want --- also its weird and certainly buggy:

I observed that it works when:

a) you specify the index_col rel. to the number of columns you really use -- so its three columns in this example, not four (you drop dummy and start counting from then onwards)

b) same for parse_dates

c) not so for usecols ;) for obvious reasons

d) here I adapted the names to mirror this behaviour

import pandas as pd
from StringIO import StringIO

csv = """dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5
"""

df = pd.read_csv(StringIO(csv),
        index_col=[0,1],
        usecols=[1,2,3], 
        parse_dates=[0],
        header=0,
        names=["date", "loc", "", "x"])

print df

which prints

                x
date       loc   
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Set value of hidden field in a form using jQuery's ".val()" doesn't work

If you are searching for haml then this is the answer for hidden field to set value to a hidden field like

%input#forum_id.hidden

In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.

$('#forum_id').attr('val',forum_id.toString());

How to display Toast in Android?

Extending activity using baseadapter used this

Toast.makeText(getActivity(), 
    "Your Message", Toast.LENGTH_LONG).show();

or if you are using activity or mainactivity

Toast.makeText(MainActivity.this, 
    "Your Message", Toast.LENGTH_LONG).show();

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

How to convert list data into json in java

Using gson it is much simpler. Use following code snippet:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

Converting back from JSON string to your Java object

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

How to get the path of a running JAR file?

public static String dir() throws URISyntaxException
{
    URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
    String name= Main.class.getPackage().getName()+".jar";
    String path2 = path.getRawPath();
    path2=path2.substring(1);

    if (path2.contains(".jar"))
    {
        path2=path2.replace(name, "");
    }
    return path2;}

Works good on Windows

$(this).serialize() -- How to add a value?

Don't forget you can always do:

<input type="hidden" name="NonFormName" value="NonFormValue" />

in your actual form, which may be better for your code depending on the case.

Ruby: Calling class method from instance

Similar your question, you could use:

class Truck
  def default_make
    # Do something
  end

  def initialize
    super
    self.default_make
  end
end

Convert a Unicode string to an escaped ASCII string

To store actual Unicode codepoints, you have to first decode the String's UTF-16 codeunits to UTF-32 codeunits (which are currently the same as the Unicode codepoints). Use System.Text.Encoding.UTF32.GetBytes() for that, and then write the resulting bytes to the StringBuilder as needed,i.e.

static void Main(string[] args) 
{ 
    String originalString = "This string contains the unicode character Pi(p)"; 
    Byte[] bytes = Encoding.UTF32.GetBytes(originalString);
    StringBuilder asAscii = new StringBuilder();
    for (int idx = 0; idx < bytes.Length; idx += 4)
    { 
        uint codepoint = BitConverter.ToUInt32(bytes, idx);
        if (codepoint <= 127) 
            asAscii.Append(Convert.ToChar(codepoint)); 
        else 
            asAscii.AppendFormat("\\u{0:x4}", codepoint); 
    } 
    Console.WriteLine("Final string: {0}", asAscii); 
    Console.ReadKey(); 
}

How can I use async/await at the top level?

I can't seem to wrap my head around why this does not work.

Because main returns a promise; all async functions do.

At the top level, you must either:

  1. Use a top-level async function that never rejects (unless you want "unhandled rejection" errors), or

  2. Use then and catch, or

  3. (Coming soon!) Use top-level await, a proposal that has reached Stage 3 in the process that allows top-level use of await in a module.

#1 - Top-level async function that never rejects

(async () => {
    try {
        var text = await main();
        console.log(text);
    } catch (e) {
        // Deal with the fact the chain failed
    }
})();

Notice the catch; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch function (rather than try/catch syntax):

(async () => {
    var text = await main();
    console.log(text);
})().catch(e => {
    // Deal with the fact the chain failed
});

...which is a bit more concise (I like it for that reason).

Or, of course, don't handle errors and just allow the "unhandled rejection" error.

#2 - then and catch

main()
    .then(text => {
        console.log(text);
    })
    .catch(err => {
        // Deal with the fact the chain failed
    });

The catch handler will be called if errors occur in the chain or in your then handler. (Be sure your catch handler doesn't throw errors, as nothing is registered to handle them.)

Or both arguments to then:

main().then(
    text => {
        console.log(text);
    },
    err => {
        // Deal with the fact the chain failed
    }
);

Again notice we're registering a rejection handler. But in this form, be sure that neither of your then callbacks doesn't throw any errors, nothing is registered to handle them.

#3 top-level await in a module

You can't use await at the top level of a non-module script, but the top-level await proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:

// In a module, once the top-level `await` proposal lands
try {
    var text = await main();
    console.log(text);
} catch (e) {
    // Deal with the fact the chain failed
}

Note that if you do this, any module that imports from your module will wait until the promise you're awaiting settles; when a module using top-level await is evaluated, it basically returns a promise to the module loader (like an async function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.

How to check if a number is a power of 2

for any power of 2, the following also holds.

n&(-n)==n

NOTE: fails for n=0 , so need to check for it
Reason why this works is:
-n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3+ and Xcode 9+ Try using this

extension ViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let collectionWidth = collectionView.bounds.width
    return CGSize(width: collectionWidth/3, height: collectionWidth/3)

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0

}

How are VST Plugins made?

I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.

https://www.juce.com/

Make Frequency Histogram for Factor Variables

Data as factor can be used as input to the plot function.

An answer to a similar question has been given here: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html

 x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),  
 50, replace=T)
 x=as.factor(x)
 plot(x)

IIS w3svc error

Make sure these 2 services running and their startup type is automatic.If they disabled and not running right click on them and go to properties and change from there.

  1. Windows process activation service
  2. Worldwide web publishing service.

Simple way to calculate median with MySQL

create table med(id integer);
insert into med(id) values(1);
insert into med(id) values(2);
insert into med(id) values(3);
insert into med(id) values(4);
insert into med(id) values(5);
insert into med(id) values(6);

select (MIN(count)+MAX(count))/2 from 
(select case when (select count(*) from 
med A where A.id<B.id)=(select count(*)/2 from med) OR 
(select count(*) from med A where A.id>B.id)=(select count(*)/2 
from med) then cast(B.id as float)end as count from med B) C;

 ?column? 
----------
  3.5
(1 row)

OR

select cast(avg(id) as float) from 
(select t1.id from med t1 JOIN med t2 on t1.id!= t2.id 
group by t1.id having ABS(SUM(SIGN(t1.id-t2.id)))=1) A;

How to get these two divs side-by-side?

I found the below code very useful, it might help anyone who comes searching here

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
    <div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
    <div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

How to sum up elements of a C++ vector?

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

SELECT st1.*
FROM some_table st1
inner join 
(
    SELECT relevant_field
    FROM some_table
    GROUP BY relevant_field
    HAVING COUNT(*) > 1
)st2 on st2.relevant_field = st1.relevant_field;

I've tried your query on one of my databases, and also tried it rewritten as a join to a sub-query.

This worked a lot faster, try it!

Uninstalling Android ADT

I found a solution by myself after doing some research:

  • Go to Eclipse home folder.
  • Search for 'android' => In Windows 7 you can use search bar.
  • Delete all the file related to android, which is shown in the results.
  • Restart Eclipse.
  • Install the ADT plugin again and Restart plugin.

Now everything works fine.

Check if string contains only digits

If you use jQuery:

$.isNumeric('1234'); // true
$.isNumeric('1ab4'); // false

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to define Gradle's home in IDEA?

AFAIK it is GRADLE_HOME not GRADLE_USER_HOME (see gradle installation http://www.gradle.org/installation).

On the other hand I played a bit with Gradle support in Idea 13 Cardea and I think the gradle home is not automatically discover by Idea. If so you can file a issue in youtrack.

Also, if you use gradle 1.6+ you can use the Graldle support for setting the build and wrapper. I think idea automatically discover the wrapper based gradle project.

$ gradle setupBuild --type java-library

$ gradle wrapper

Note: Supported library types: basic, maven, java

Regards

How to get the difference (only additions) between two files in linux

git diff path/file.css | grep -E "^\+" | grep -v '+++ b/' | cut -c 2-
  • grep -E "^\+" is from previous accepted answer, it is incomplete because leaves non-source stuff
  • grep -v '+++ b' removes non-source line with file name of later version
  • cut -c 2- removes column of + signs, also may use sed 's/^\+//'

comm or sdiff were not an option because of git.

Programmatically close aspx page from code behind

 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }

How do you redirect HTTPS to HTTP?

If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It worked for me :)

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

keypress, ctrl+c (or some combo like that)

In my case, I was looking for a keydown ctrl key and click event. My jquery looks like this:

$('.linkAccess').click( function (event) {
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Verified if the link is not null */
    if('' !== value){
      window.open(value);
    }
  }
});

Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.

How can I scale the content of an iframe?

I just tested and for me, none of the other solutions worked. I simply tried this and it worked perfectly on Firefox and Chrome, just as I had expected:

<div class='wrap'>
    <iframe ...></iframe>
</div>

and the css:

.wrap {
    width: 640px;
    height: 480px;
    overflow: hidden;
}

iframe {
    width: 76.92% !important;
    height: 76.92% !important;
    -webkit-transform: scale(1.3);
    transform: scale(1.3);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
}

This scales all the content by 30%. The width/height percentages of course need to be adjusted accordingly (1/scale_factor).

Android Device Chooser -- device not showing up

The device was not showing up because of the following line in android manifest file---

<uses-sdk android:minSdkVersion="18"
        android:targetSdkVersion="18"/>

I changed it to---

<uses-sdk android:minSdkVersion="8"
        android:targetSdkVersion="19"/>

Now it worked.

How do check if a PHP session is empty?

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )
    die( "Login required." );

(Assuming you want to check if someone is logged in)

Ruby/Rails: converting a Date to a UNIX timestamp

Solution for Ruby 1.8 when you have an arbitrary DateTime object:

1.8.7-p374 :001 > require 'date'
 => true 
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
 => "1326585600"

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Setting Icon for wpf application (VS 08)

Note: (replace file.ico with your actual icon filename)

  1. Add the icon to the project with build action of "Resource".
  2. In the Project Properties, set the Application Icon to file.ico
  3. In the main Window XAML set: Icon=".\file.ico" on the Window

Use RSA private key to generate public key?

openssl genrsa -out mykey.pem 1024

will actually produce a public - private key pair. The pair is stored in the generated mykey.pem file.

openssl rsa -in mykey.pem -pubout > mykey.pub

will extract the public key and print that out. Here is a link to a page that describes this better.

EDIT: Check the examples section here. To just output the public part of a private key:

openssl rsa -in key.pem -pubout -out pubkey.pem

To get a usable public key for SSH purposes, use ssh-keygen:

ssh-keygen -y -f key.pem > key.pub

Generating PDF files with JavaScript

I maintain PDFKit, which also powers pdfmake (already mentioned here). It works in both Node and the browser, and supports a bunch of stuff that other libraries do not:

  • Embedding subsetted fonts, with support for unicode.
  • Lots of advanced text layout stuff (columns, page breaking, full unicode line breaking, basic rich text, etc.).
  • Working on even more font stuff for advanced typography (OpenType/AAT ligatures, contextual substitution, etc.). Coming soon: see the fontkit branch if you're interested.
  • More graphics stuff: gradients, etc.
  • Built with modern tools like browserify and streams. Usable both in the browser and node.

Check out http://pdfkit.org/ for a full tutorial to see for yourself what PDFKit can do. And for an example of what kinds of documents can be produced, check out the docs as a PDF generated from some Markdown files using PDFKit itself: http://pdfkit.org/docs/guide.pdf.

You can also try it out interactively in the browser here: http://pdfkit.org/demo/browser.html.

Load dimension value from res/values/dimension.xml from source code

    This works but the value I get is multiplied times the screen density factor
  (1.5 for hdpi, 2.0 for xhdpi, etc).

I think it is good to get the value as per resolution but if you not want to do this give this in px.......

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

I think it is good to change the value as per resolution but if you not want to do this give this in px.......

refer this link

as per this

dp

Density-independent Pixels - An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.

px

Pixels - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

How can I replace the deprecated set_magic_quotes_runtime in php?

In PHP 7 we can use:

ini_set('magic_quotes_runtime', 0);

instead of set_magic_quotes_runtime(0);

Mongoose: Find, modify, save

Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

User.update({username: oldUsername}, {
    username: newUser.username, 
    password: newUser.password, 
    rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
   //handle it
})

Export specific rows from a PostgreSQL table as INSERT SQL script

have u tried in pgadmin executing query with " EXECUTE QUERY WRITE RESULT TO FILE " option

its only export the data, else try like

pg_dump -t view_name DB_name > db.sql

-t option used for ==> Dump only tables (or views or sequences) matching table, refer

Flash CS4 refuses to let go

I have found one related behaviour that may help (sounds like your specific problem runs deeper though):

Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.

Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

Export javascript data to CSV file without server interaction

@adeneo answer works for Firefox and chrome... For IE the below can be used.

_x000D_
_x000D_
if (window.navigator.msSaveOrOpenBlob) {_x000D_
  var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
    type: "text/csv;charset=utf-8;"_x000D_
  });_x000D_
  navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
_x000D_
_x000D_

How can I remove the search bar and footer added by the jQuery DataTables plugin?

I think the simplest way is:

<th data-searchable="false">Column</th>

You can edit only the table you have to modify, without change common CSS or JS.

How to get the onclick calling object?

The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){
  e = e || window.event;
  var src = e.target || e.srcElement;
  //src element is the eventsource
}

Adding days to $Date in PHP

Here is a small snippet to demonstrate the date modifications:

$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

Calculating and printing the nth prime number

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.

Having the output of a console application in Visual Studio instead of the console

If you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:

Example taken from C# In Depth by Jon Skeet: Example taken from C# In Depth by Jon Skeet This produce this output at Text Explorer: Task Explorer

When we click on Blue Output, under Elapsed Time, at right, and it produces this: Standard Output

Standard Output is our desired Output, produced by Console.WriteLine.

It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.

Connecting to local SQL Server database using C#

You try with this string connection

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

Replace values in list using Python

>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

case statement in SQL, how to return multiple variables?

In a SQL CASE clause, the first successfully matched condition is applied and any subsequent matching conditions are ignored.

How can I start an Activity from a non-Activity class?

You can define a context for your application say ExampleContext which will hold the context of your application and then use it to instantiate an activity like this:

var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);

Please bear in mind that this code is written in C# as I use MonoDroid, but I believe it is very similar to Java. For how to create an ApplicationContext look at this thread

This is how I made my Application Class

    [Application]
    public class Application : Android.App.Application, IApplication
    {
        public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
        {

        }
        public object MyObject { get; set; }
    }

When does a process get SIGABRT (signal 6)?

abort() sends the calling process the SIGABRT signal, this is how abort() basically works.

abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.

Install IPA with iTunes 11

For OS X Yosemite and above, and Xcode 6+

Open Xcode > Window > Devices

Choose your device. You can see the installed application list and add a new one by hitting +

screenshot of Xcode Devices

adb doesn't show nexus 5 device

My windows solution:

Go here and download and unzip to an easy location:

http://developer.android.com/sdk/win-usb.html#top

  • Right click 'My Computer' or 'Computer'

  • Select properties

  • Select Device manager

  • Look for your device. It should have a yellow mark above it.

  • Click 'update driver software'.

  • select browse my computer for driver software.

  • select the usb_driver folder you saved earlier.

  • install it

and wala. magic.

How do I kill a process using Vb.NET or C#?

You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.

private bool isWordRunning() 
{
    return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}

Of course, you can only do this if your app has a GUI

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

How do I access the $scope variable in browser's console using AngularJS?

Say you want to access the scope of the element like

<div ng-controller="hw"></div>

You could use the following in the console:

angular.element(document.querySelector('[ng-controller=hw]')).scope();

This will give you the scope at that element.

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

Some databases are designed to communicate over the web using ports assigned by the Internet Assigned Number Authority (IANA) and when run on individual PC use the ports with localhost. Some common databases with their default ports (the defualts can usually be overridden):

Port Database

1433 Microsoft SQL Server https://support.microsoft.com/en-us/kb/287932

3306 MySQL https://dev.mysql.com/doc/refman/4.1/en/connecting.html

5432 PostgreSQL

1527 Apache Derby (database)

Some web servers and databases are paired together such as Apache/MySQL (as in LAMP or XXAMP) or MS Internet Information Server (IIS)/MS SQL Server (IIS/SQL Server) in which case you have to be concerned with both the port of the database and the web server -- a common example of this is WordPress which uses Apache/MySQL.

DataGridView checkbox column - value and functionality

if u make this column in sql database (bit) as a data type u should edit this code

DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
dataGridView1.Columns.Insert(0, doWork);

with this

DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "False";
doWork.TrueValue = "True";
dataGridView1.Columns.Insert(0, doWork);

Text size and different android screen sizes

@forcelain I think you need to check this Google IO Pdf for Design. In that pdf go to Page No:77 in which you will find how there suggesting for using dimens.xml for different devices of android for Example see Below structure :

res/values/dimens.xml

res/values-small/dimens.xml

res/values-normal/dimens.xml

res/values-large/dimens.xml

res/values-xlarge/dimens.xml

for Example you have used below dimens.xml in values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <dimen name="text_size">18sp</dimen>
</resources>

In other values folder you need to change values for your text size .

Note: As indicated by @espinchi the small, normal, large and xlarge have been deprecated since Android 3.2 in favor of the following:

Declaring Tablet Layouts for Android 3.2

For the first generation of tablets running Android 3.0, the proper way to declare tablet layouts was to put them in a directory with the xlarge configuration qualifier (for example, res/layout-xlarge/). In order to accommodate other types of tablets and screen sizes—in particular, 7" tablets—Android 3.2 introduces a new way to specify resources for more discrete screen sizes. The new technique is based on the amount of space your layout needs (such as 600dp of width), rather than trying to make your layout fit the generalized size groups (such as large or xlarge).

The reason designing for 7" tablets is tricky when using the generalized size groups is that a 7" tablet is technically in the same group as a 5" handset (the large group). While these two devices are seemingly close to each other in size, the amount of space for an application's UI is significantly different, as is the style of user interaction. Thus, a 7" and 5" screen should not always use the same layout. To make it possible for you to provide different layouts for these two kinds of screens, Android now allows you to specify your layout resources based on the width and/or height that's actually available for your application's layout, specified in dp units.

For example, after you've designed the layout you want to use for tablet-style devices, you might determine that the layout stops working well when the screen is less than 600dp wide. This threshold thus becomes the minimum size that you require for your tablet layout. As such, you can now specify that these layout resources should be used only when there is at least 600dp of width available for your application's UI.

You should either pick a width and design to it as your minimum size, or test what is the smallest width your layout supports once it's complete.

Note: Remember that all the figures used with these new size APIs are density-independent pixel (dp) values and your layout dimensions should also always be defined using dp units, because what you care about is the amount of screen space available after the system accounts for screen density (as opposed to using raw pixel resolution). For more information about density-independent pixels, read Terms and concepts, earlier in this document. Using new size qualifiers

The different resource configurations that you can specify based on the space available for your layout are summarized in table 2. These new qualifiers offer you more control over the specific screen sizes your application supports, compared to the traditional screen size groups (small, normal, large, and xlarge).

Note: The sizes that you specify using these qualifiers are not the actual screen sizes. Rather, the sizes are for the width or height in dp units that are available to your activity's window. The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout. Thus, the sizes you declare should be specifically about the sizes needed by your activity—the system accounts for any space used by system UI when declaring how much space it provides for your layout. Also beware that the Action Bar is considered a part of your application's window space, although your layout does not declare it, so it reduces the space available for your layout and you must account for it in your design.

Table 2. New configuration qualifiers for screen size (introduced in Android 3.2). Screen configuration Qualifier values Description smallestWidth swdp

Examples: sw600dp sw720dp

The fundamental size of a screen, as indicated by the shortest dimension of the available screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your application's has at least dps of width available for its UI.

For example, if your layout requires that its smallest dimension of screen area be at least 600 dp at all times, then you can use this qualifier to create the layout resources, res/layout-sw600dp/. The system will use these resources only when the smallest dimension of available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived height or width. The smallestWidth is a fixed screen size characteristic of the device; the device's smallestWidth does not change when the screen's orientation changes.

The smallestWidth of a device takes into account screen decorations and system UI. For example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI.

This is an alternative to the generalized screen size qualifiers (small, normal, large, xlarge) that allows you to define a discrete number for the effective size available for your UI. Using smallestWidth to determine the general screen size is useful because width is often the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally. The available width is also the key factor in determining whether to use a one-pane layout for handsets or multi-pane layout for tablets. Thus, you likely care most about what the smallest possible width will be on each device. Available screen width wdp

Examples: w720dp w1024dp

Specifies a minimum available width in dp units at which the resources should be used—defined by the value. The system's corresponding value for the width changes when the screen's orientation switches between landscape and portrait to reflect the current actual width that's available for your UI.

This is often useful to determine whether to use a multi-pane layout, because even on a tablet device, you often won't want the same multi-pane layout for portrait orientation as you do for landscape. Thus, you can use this to specify the minimum width required for the layout, instead of using both the screen size and orientation qualifiers together. Available screen height hdp

Examples: h720dp h1024dp etc.

Specifies a minimum screen height in dp units at which the resources should be used—defined by the value. The system's corresponding value for the height changes when the screen's orientation switches between landscape and portrait to reflect the current actual height that's available for your UI.

Using this to define the height required by your layout is useful in the same way as wdp is for defining the required width, instead of using both the screen size and orientation qualifiers. However, most apps won't need this qualifier, considering that UIs often scroll vertically and are thus more flexible with how much height is available, whereas the width is more rigid.

While using these qualifiers might seem more complicated than using screen size groups, it should actually be simpler once you determine the requirements for your UI. When you design your UI, the main thing you probably care about is the actual size at which your application switches between a handset-style UI and a tablet-style UI that uses multiple panes. The exact point of this switch will depend on your particular design—maybe you need a 720dp width for your tablet layout, maybe 600dp is enough, or 480dp, or some number between these. Using these qualifiers in table 2, you are in control of the precise size at which your layout changes.

For more discussion about these size configuration qualifiers, see the Providing Resources document. Configuration examples

To help you target some of your designs for different types of devices, here are some numbers for typical screen widths:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Using the size qualifiers from table 2, your application can switch between your different layout resources for handsets and tablets using any number you want for width and/or height. For example, if 600dp is the smallest available width supported by your tablet layout, you can provide these two sets of layouts:

res/layout/main_activity.xml # For handsets res/layout-sw600dp/main_activity.xml # For tablets

In this case, the smallest width of the available screen space must be 600dp in order for the tablet layout to be applied.

For other cases in which you want to further customize your UI to differentiate between sizes such as 7” and 10” tablets, you can define additional smallest width layouts:

res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) res/layout-sw720dp/main_activity.xml

For 10” tablets (720dp wide and bigger)

Notice that the previous two sets of example resources use the "smallest width" qualifier, swdp, which specifies the smallest of the screen's two sides, regardless of the device's current orientation. Thus, using swdp is a simple way to specify the overall screen size available for your layout by ignoring the screen's orientation.

However, in some cases, what might be important for your layout is exactly how much width or height is currently available. For example, if you have a two-pane layout with two fragments side by side, you might want to use it whenever the screen provides at least 600dp of width, whether the device is in landscape or portrait orientation. In this case, your resources might look like this:

res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width or more)

Notice that the second set is using the "available width" qualifier, wdp. This way, one device may actually use both layouts, depending on the orientation of the screen (if the available width is at least 600dp in one orientation and less than 600dp in the other orientation).

If the available height is a concern for you, then you can do the same using the hdp qualifier. Or, even combine the wdp and hdp qualifiers if you need to be really specific.

How to resolve git's "not something we can merge" error

If the string containing the reference is produced by another Git command (or any other shell command for that matter), make sure that it doesn't contain a return carriage at the end. You will have to strip it before passing the string to "git merge".

Note that it's pretty obvious when this happens, because the error message in on 2 lines:

merge: 26d8e04b29925ea5b59cb50501ab5a14dd35f0f9
 - not something we can merge

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

Difference Between Cohesion and Coupling

simply, Cohesion represents the degree to which a part of a code base forms a logically single, atomic unit. Coupling, on the other hand, represents the degree to which a single unit is independent from others. In other words, it is the number of connections between two or more units. The fewer the number, the lower the coupling.

In essence, high cohesion means keeping parts of a code base that are related to each other in a single place. Low coupling, at the same time, is about separating unrelated parts of the code base as much as possible.

Types of code from a cohesion and coupling perspective:

Ideal is the code that follows the guideline. It is loosely coupled and highly cohesive. We can illustrate such code with this picture: enter image description here

God Object is a result of introducing high cohesion and high coupling. It is an anti-pattern and basically stands for a single piece of code that does all the work at once: enter image description here poorly selected takes place when the boundaries between different classes or modules are selected poorlyenter image description here

Destructive decoupling is the most interesting one. It sometimes occurs when a programmer tries to decouple a code base so much that the code completely loses its focus:enter image description here

read more here

String vs. StringBuilder

String and StringBuilder are actually both immutable, the StringBuilder has built in buffers which allow its size to be managed more efficiently. When the StringBuilder needs to resize is when it is re-allocated on the heap. By default it is sized to 16 characters, you can set this in the constructor.

eg.

StringBuilder sb = new StringBuilder(50);

Break a previous commit into multiple commits

You can do interactive rebase git rebase -i. Man page has exactly what you want:

http://git-scm.com/docs/git-rebase#_splitting_commits

How to use jQuery in chrome extension?

In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

manifest.json

{
  "name": "JQuery Light",
  "version": "1",
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png"
  },

  "content_scripts": [
    {
      "matches": [
        "https://*.google.com/*"
      ],
      "js": [
        "jquery-3.3.1.min.js",
        "myscript.js"
      ]
    }
  ],

  "background": {
    "scripts": [
      "background.js"
    ]
  }

}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

myscript.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
        console.log('Hello world!')
        }
    }
);

Java - Get a list of all Classes loaded in the JVM

One way if you already know the package top level path is to use OpenPojo

final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively("my.package.path", null);

Then you can go over the list and perform any functionality you desire.

What's the best way to determine the location of the current PowerShell script?

I found that the older solutions posted here didn't work for me on PowerShell V5. I came up with this:

try {
    $scriptPath = $PSScriptRoot
    if (!$scriptPath)
    {
        if ($psISE)
        {
            $scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath
        }
        else {
            Write-Host -ForegroundColor Red "Cannot resolve script file's path"
            exit 1
        }
    }
}
catch {
    Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)"
    exit 2
}

Write-Host "Path: $scriptPath"

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

How do you import an Eclipse project into Android Studio now?

Android Studio has been improved since this question was posted, and the latest versions of Android Studio (as of this writing, we are at 2.1.1) have fairly good Eclipse importing capabilities, so importing Eclipse projects directly into Android Studio is now the best approach for migrating projects from Eclipse into Android Studio.

I will describe how to do this below, including a few of the pitfalls that one might encounter. I will deal in particular with importing an Eclipse workspace that contains multiple apps sharing one or more project libraries (the approaches posted thus far seem limited to importing just one Eclipse app project and its project libraries). While I don't deal with every possible issue, I do go into a lot of detail regarding some of them, which I hope will be helpful to those going through this process for the first time themselves.

I recently imported the projects from an Eclipse workspace. This workspace included four library projects that were shared between up to nine projects each.

Some background:

An Eclipse workspace contains multiple projects, which may be library projects or apps.

An Android Studio project is analogous to an Eclipse workspace, in that it can contain both library projects and apps. However, a library project or an app is represented by a "module" in Android Studio, whereas it is represented by a "project" in Eclipse.

So, to summarize: Eclipse workspaces will end up as Android Studio projects, and Eclipse projects inside a workspace will end up as Android Studio modules inside a project.

You should start the import process by creating an Android Studio project (File / New / New Project). You might give this project the same (or similar) name as you gave your Eclipse workspace. This project will eventually hold all of your modules, one each for each Eclipse project (including project libraries) that you will import.

The import process does not change your original Eclipse files, so long as you place the imported files in a different folder hierarchy, so you should choose a folder for this project that is not in your original Eclipse hierarchy. For example, if your Eclipse projects are all in a folder called Android, you might create a sibling folder called AStudio.

Your Android Studio project can then be created as a sub-folder of this new folder. The New Project wizard will prompt you to enter this top-level project folder, into which it will create your project.

Android Studio's new project wizard will then ask you to configure a single module at the time you create the project. This can be a little confusing at first, because they never actually tell you that you are creating a module, but you are; you are creating a project with a single module in it. Apparently, every project is required to have at least one module, so, since you are relying on Eclipse to provide your modules, your initial module will be a placeholder to vacuously satisfy that formal requirement.

Thus, you probably will want to create an initial module for your project that does as little as possible. Therefore, select Phone and Tablet as the type of your module, accept the default minimum SDK (API level 8), and select Add No Activity for your module.

Next, select one of the Eclipse app projects in your workspace that requires the largest number of libraries as your first project to import. The advantage of doing this is that when you import that project, all the library projects that it uses (directly, or indirectly, if some of your library projects themselves require other library projects) will get imported along with it as part of the importing process.

Each of these imported projects will get its own module within your Android Studio project. All of these modules will be siblings of one another (both in your project hierarchy, and in the folder hierarchy where their files are placed), just as if you had imported the modules separately. However, the dependencies between the modules will be created for you (in your app's build.gradle files) as part of the importing process.

Note that after you finish importing, testing and debugging this "most dependent" Eclipse project and its supporting library projects, you will go on to import a second Eclipse app project (if you have a second one in your workspace) and its library project modules (with those imported earlier getting found by the import wizard as existing modules and re-used for this new module, rather than being duplicated).

So, you should never have to import even a single library project from Eclipse directly; they will all be brought in indirectly, based on their dependencies upon app projects that you import. This is assuming that all of your library projects in the workspace are created to serve the needs of one or more app projects in that same workspace.

To perform the import of this first app project, back in Android Studio, while you are in the project that you just created, select File / New / New Module. You might think that you should be using File / New / Import Module, but no, you should not, because if you do that, Android Studio will create a new project to hold your imported module, and it will import your module to that project. You actually could create your first module that way, but then the second through Nth modules would still require that you use this other method (for importing a module into an existing project), and so I think that just starting with an "empty" project (or rather, one with its own vacuous, do-nothing placeholder module), and then importing each of your Eclipse projects as a new module into that project (i.e., the approach we are taking here), may be less confusing.

So, you are going to take your practically-empty new project, and perform a File / New / New Module in it. The wizard that this invokes will give you a choice of what kind of module you want to create. You must select "Import Eclipse ADT Project." That is what accesses the wizard that knows how to convert an Eclipse project into an Android Studio module (along with the library modules on which it depends) within your current Android Studio project.

When prompted for a source folder, you should enter the folder for your Eclipse project (this is the folder that contains that project's AndroidManifest.xml file).

The import wizard will then display the module name that it intends to create (similar to your original Eclipse project's name, but with a lower-case first letter because that is a convention that distinguishes module names from project names (which start with an upper-case letter). It usually works pretty well to accept this default.

Below the module name is a section titled "Additional required modules." This will list every library required by the module you are importing (or by any of its libraries, etc.). Since this is the first module you are importing, none of these will already be in your project, so each of them will have its Import box checked by default. You should leave these checked because you need these modules. (Note that when you import later Eclipse app projects, if a library that they need has already been imported, those libraries will still appear here, but there will be a note that "Project already contains module with this name," and the Import box will be un-checked by default. In that case, you should leave the box unchecked, so that the importer will hook up your newly-imported module(s) to the libraries that have already been imported. It may be that accepting the default names that Android Studio creates for your modules will be important for allowing the IDE to find and re-use these library modules.

Next, the importer will offer to replace any jars and library sources with Gradle dependencies, and to create camelCase module names for any dependent modules, checking all those options by default. You should generally leave these options checked and continue. Read the warning, though, about possible problems. Remember that you can always delete an imported module or modules (via the Project Structure dialog) and start the import process over again.

The next display that I got (YMMV) claims that the Android Support Repository is not installed in my SDK installation. It provides a button to open the Android SDK Manager for purposes of installing it. However, that button did not work for me. I manually opened the SDK manager as a separate app, and found that the Android Support Repository was already installed. There was an update, however. I installed that, and tapped the Refresh button in the import dialog, but that did nothing. So, I proceeded, and the perceived lack of this Repository did not seem to hurt the importing process (although I did get messages regarding it being missing from time to time later on, while working with the imported code, which I was able to appease by clicking a supplied link that corrected the problem - at least temporarily). Eventually this problem went away when I installed an update to the repository, so you may not experience it at all.

At this point, you will click Finish, and after a bit it should create your modules and build them. If all goes well, you should get a BUILD SUCCESSFUL message in your Gradle Console.

One quirk is that if the build fails, you may not see your imported modules in the Project hierarchy. It seems that you need to get to the first valid build before the new modules will appear there (my experience, anyway). You may still be able to see the new modules in the File / Project Structure dialog (e.g., if you want to delete them and start your import over).

Remember that since you are not changing your original Eclipse projects, you can always delete the modules that you have just imported (if importing goes badly), and start all over again. You can even make changes to the Eclipse side after deleting your Android Studio modules, if that will make importing go better the second time (so long as you preserve your fallback ability to build your existing source under Eclipse). As you'll see when we discuss version control below, it may be necessary for you to retain your ability to build under Eclipse, because the project structure is changed under Android Studio, so if you need to go back to a commit that precedes your move to Android Studio (e.g., to make a bug fix), you will want to have the ability to build that earlier commit in Eclipse.

To delete a module, you must select File / Project Structure, then select the module from the left side of the dialog, and then hit the delete key. For some reason, I was not able to delete a module directly in the Project hierarchy; it had to be done using this Project Structure dialog.

The import wizard generates an import-summary.txt file containing a detailed list of any issues it may have encountered, along with actions taken to resolve them. You should read it carefully, as it may provide clues as to what is happening if you have trouble building or running the imported code. It will also help you to find things that the importer moves around to accommodate the different structure of Android Studio projects.

If all does not go well, then have at look at these possible problems that you may encounter, along with solutions for those problems:

Generally speaking, there are two main kinds of problems that I encountered:

  1. Proguard problems
  2. Manifest problems

When Proguard is messed up, the (obfuscated) names of methods in your libraries may not match the names being used to invoke them from your app, and you will get compiler errors like "error: cannot find symbol class ..."

In Eclipse, Proguard stuff is pretty much ignored for library projects, with the Proguard stuff for any app project that you are building determining the obfuscation, etc. for not just itself, but for processing all of the libraries on which it depends. And that is generally what you want.

In Android Studio, however, you need to make some changes to attain this same effect. Basically, in the build.gradle files for each of your library project modules, you will want something like this:

buildTypes {
    release {
        minifyEnabled false
        consumerProguardFiles 'proguard.cfg'
    }
}

Where proguard.cfg is your library module's own proguard configuration file.

The term "consumer" in "consumerProguardFiles" apparently refers to the app module that is using this library module. So the proguard commands from that app are used in preference to those of the library module itself, and apparently this results in obfuscations that are coordinated and compatible, so that all calls from the app module to its library modules are made with matching symbols.

These "consumerProguardFiles" entries are not created automatically during the import process (at least that was my own experience) so you will want to make sure to edit that into your library modules' build.gradle files if they are not created for you during importing.

If you wanted to distribute your library projects separately, with obfuscation, then you would need an individual proguard file for them; I have not done this myself, and so that is beyond the scope of this answer.

In the app module, you will want something like this:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles 'proguard.cfg'
    }
}

(BTW, as of this writing, while my apps are running just fine, I have not yet directly confirmed that things are actually getting obfuscated using this approach, so do check this yourself - e.g., by using a decompiler like apktool. I will be checking this later on, and will edit this answer when I get that info).

The second kind of problem is due to the fact that Eclipse pretty much ignores the manifest files for library projects when compiling an app project that uses those library projects, while in Android Studio, there is an interleaving of the two that apparently does not consistently prioritize the app's manifest over those of its libraries.

I encountered this because I had a library manifest that listed (just for documentation purposes) an abstract Activity class as the main activity. There was a class derived from this abstract class in my app that was declared in the manifest of each app that used the library.

In Eclipse, this never caused any problems, because the library manifests were ignored. But in Android Studio, I ended up with that abstract class as my activity class for the app, which caused a run-time error when the code made an attempt to instantiate that abstract class.

You have two choices in this case:

  1. Use tools syntax to override specific library manifest stuff in your app manifest - for example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.goalstate.WordGames.FullBoard.trialsuite"
       xmlns:tools="http://schemas.android.com/tools"
       .
       .
        <application
           tools:replace="android:name"

or,

  1. Strip out practically everything from your library modules' manifests, and rely upon the app module's manifest to provide every value. Note that you do need to have a manifest for each library module, but not much more is required than the header and a bare manifest element with just a package attribute in it.

I tried both and ended up with approach 2., above, as the simpler method. However, if you wanted to distribute your library modules separately, you would need to create a more meaningful manifest file that reflects each library module's own individual requirements.

There is probably a more "correct" way to do this which puts requirements (e.g., permissions) for each library in the library manifest itself, and allows the automatic interleaving process to combine these with those declared for the app. However, given that Eclipse ignores the manifests for libraries, it seems safer at least initially to rely entirely on the app manifests and just strip the library manifests down to the bare bones.

Be aware that some of the project properties, and also the manifest attributes, from your Eclipse project will have been used to construct portions of your build.gradle files. Specifically, your compileSdkVersion in build.gradle is set to the project build version from the Eclipse project properties, applicationId is the package name from your app's manifest, and minSdkVersion and targetSdkVersion are also copied from the app's manifest file. The dependencies section of build.gradle comes from the library project dependencies in your project's properties.

Note that this may make some of your AndroidManifest.xml values redundant and quite possibly residual (i.e., unused). This could create confusion. My understanding is that the build.gradle values are the ones that actually have an effect, and that the manifest values like targetSdkVersion are not used any more for purposes of building. However, they may still be used by app stores such as Google Play; I don't know for certain one way or the other, so at this point I am just maintaining them in tandem.

Besides the above two kinds of issue, there are more routine things like importing a project that has a project build level of 22 when you have only installed SDK level 23 in Android Studio. In that situation, it is probably better to edit your app module's build.gradle file to move compileSdkVersion from 22 (the imported value) to 23, than it would be to install the SDK for level 22, but either approach should work.

Throughout this entire process, when something does not build properly and you make a change to try to address it, you might want to try Build / Rebuild Project and/or Tools / Android / Sync Project with Gradle Files, and/or File / Invalidate Caches/Restart, to make sure that your changes have been fully incorporated. I don't know exactly when these are truly necessary, because I don't know how much is done incrementally when you haven't yet had a successful build, but I performed them all fairly regularly as a kind of superstitious ritual, and I'm fairly certain that it helped. For example, when I got a Resources$NotFound runtime error that appeared to be from an inability to find the launch icon resource, I tried all three, and the problem was fixed.

When you have performed the above for your first Eclipse project and have attained a successful build, then with luck, you can select your app module from the dropdown at the top of the Android Studio display to the left of the play button, then click the play button itself, then select a device or Android Virtual Device, and the app should be loaded for running.

Likewise, you should be able to create a signed copy of your app using the Build / Generate Signed APK feature. Note that some import-related errors may appear when running your signed copy that do not appear when using the play button, so you need to confirm that both are working before deciding that your import is complete.

Following this, you will probably want to turn on version control. I am using git myself, but there are a number of other options available.

Version control is mostly beyond the scope of this answer, but there are a few things that are affected by the importing process. First, in Eclipse you might have your various projects in various folders stuck all over the place, but when you import into Android Studio, all modules will be created as direct child folders of your main project folder. So if you had a separate git folder for each project in Eclipse, or for related groups of projects organized under a parent folder for each group (as I did), that is not going to translate very well to Android Studio.

My knowledge of this is limited as I have not worked with version control yet in Android Studio, so maybe there is a way around this, but it appears that all version control in Android Studio is unified at the project level, and so all of your modules will be under a single git archive.

This means that you may need to abandon your old git archive and start fresh with a new archive for your imported source code. And that means that you will want to keep your old git archive around, so that it can be used with Eclipse to perform any needed bug fixes, etc., at least for a while. And you also will want it to preserve a history of your project.

If you are fortunate enough to have had all of your projects organized under a single Eclipse workspace, and if you were using a single git archive for those projects, then it is possible that you might just copy your old git archive from in and under your Eclipse workspace folder to in and under your Android Studio project folder. Then, you could edit any still-relevant .gitignore items from you Eclipse project into the auto-generated .gitignore file for your Android Studio project, and let git figure out what has been changed during the importing process (and some things will have been moved around - for example, the manifest file is no longer at the top level of your module). Others have reported that git is pretty good at figuring out what has changed; I have not tried this myself.

But even if you did this, going back to a commit that precedes your move from Eclipse to Android Studio would be going back to a set of files that would only make sense from inside Eclipse. So it sounds, well, "difficult" to work with. Especially since Eclipse will still be pointing to its original set of project folders.

I personally had multiple git archives for my various sets of related projects, and so I decided to just make a clean break and start git over again in Android Studio. If you had to do this, it could affect your planning, because you would want to be at a very stable point in your code development before making the move in that case, since you will lose some accessibility to that older code within your version control system (e.g., ability to merge with post-import code) once you have made the move to Android Studio.

The part of this answer that pertains to git is partly speculative, since I have not actually worked with version control yet on my imported project files, but I wanted to include it to give some idea of the challenges, and I plan to update my answer after I have worked more with version control inside Android Studio.

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

How do I abort the execution of a Python script?

If the entire program should stop use sys.exit() otherwise just use an empty return.

Image Greyscale with CSS & re-color on mouse-over?

Answered here: Convert an image to grayscale in HTML/CSS

You don't even need to use two images which sounds like a pain or an image manipulation library, you can do it with cross browser support (current versions) and just use CSS. This is a progressive enhancement approach which just falls back to color versions on older browsers:

img {
  filter: url(filters.svg#grayscale);
  /* Firefox 3.5+ */
  filter: gray;
  /* IE6-9 */
  -webkit-filter: grayscale(1);
  /* Google Chrome & Safari 6+ */
}
img:hover {
  filter: none;
  -webkit-filter: none;
}

and filters.svg file like this:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="grayscale">
    <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" />
  </filter>
</svg>

How do you run a SQL Server query from PowerShell?

To avoid SQL Injection with varchar parameters you could use

function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars

How is AngularJS different from jQuery

AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it's not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Read more details here: angularjs-vs-jquery

How to read all rows from huge table?

I did it like below. Not the best way i think, but it works :)

    Connection c = DriverManager.getConnection("jdbc:postgresql://....");
    PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
    s.setMaxRows(100);
    int lastId = 0;
    for (;;) {
        s.setInt(1, lastId);
        ResultSet rs = s.executeQuery();

        int lastIdBefore = lastId;
        while (rs.next()) {
            lastId = Integer.parseInt(rs.getObject(1).toString());
            // ...
        }

        if (lastIdBefore == lastId) {
            break;
        }
    }

How to get a complete list of ticker symbols from Yahoo Finance?

I had same problem, but I think I have simple solution(code is from my RoR app): Extract industry ids from yahoo.finance.sectors and add it to db:

    select = "select * from yahoo.finance.sectors"
    generate_query select
    @data.each do |data|
      data["industry"].each do |ind|
        unless ind.kind_of?(Array)
          unless ind["id"].nil?
            id = ind["id"].to_i
            if id > 0
              Industry.where(id: id).first_or_create(name: ind["name"]).update_attribute(:name, ind["name"])
            end
          end
        end
      end
    end

Extract all comanies with their symbols with industry ids:

    ids = Industry.all.map{|ind| "'#{ind.id.to_s}'" }.join(",")
    select = "select * from yahoo.finance.industry where id in"
    generate_query select, ids
    @data.each do |ts|
      unless ts.kind_of?(Array) || ts["company"].nil?
        if ts["company"].count == 2 && ts["company"].first[0] == "name"
          t = ts["company"]
          Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
        else
          ts["company"].each do |t|
            Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
          end
        end
      end
    end
  end

Connection hellper:

def generate_query(select, ids = nil)
    if params[:form] || params[:action] == "sectors" || params[:controller] == "tickets"
      if params[:action] == "sectors" || params[:controller] == "tickets"
        if ids.nil?
          query= select
        else
          query= "#{select} (#{ids})"
        end
      else
        if params[:form][:ids]
          @conditions = params_parse params[:form][:ids]
          query = "#{select} (#{@conditions})"
        end
      end
      yql_execut(query)
    end
  end

  def yql_execut(query)
    # TODO: OAuth ACCESS (http://developer.yahoo.com/yql/guide/authorization.html)
    base_url = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="
    dirty_data = JSON.parse(HTTParty.get(base_url +  URI.encode(query)).body)
    if dirty_data["query"]["results"] == nil
      @data, @count, @table_head = nil
    else
      @data = dirty_data["query"]["results"].to_a[0][1].to_a
      @count = dirty_data["query"]["count"]
      if @count == 1
        @table_head = @data.map{|h| h[0].capitalize}
      else
        @table_head = @data.to_a.first.to_a.map{|h| h[0].capitalize}
      end
    end
  end

Sorry for mess, but this is first testing version for my project and I needed it very fast. There are some helpers variabels and other things for my app, sorry for it. But I have question: Have many symbols do you have? I have 5500.

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

Regular Expression to select everything before and up to a particular text

After executing the below regex, your answer is in the first capture.

/^(.*?)\.txt/

How to trigger HTML button when you press Enter in textbox?

It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.

Can't drop table: A foreign key constraint fails

I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.

Basically, your table should be changed like so:

ALTER TABLE 'bericht' DROP FOREIGN KEY 'your_foreign_key';

ALTER TABLE 'bericht' ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;

Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.

Hope this helps.

Javascript: formatting a rounded number to N decimals

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

jquery validate check at least one checkbox

It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.

How do I concatenate two strings in C?

Concatenate Strings

Concatenating any two strings in C can be done in atleast 3 ways :-

1) By copying string 2 to the end of string 1

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  int i,j=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=strlen(str1);str2[j]!='\0';i++)  //Copying string 2 to the end of string 1
  {
     str1[i]=str2[j];
     j++;
  }
  str1[i]='\0';
  printf("\nConcatenated string: ");
  puts(str1);
  return 0;
}

2) By copying string 1 and string 2 to string 3

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX],str3[MAX];
  int i,j=0,count=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=0;str1[i]!='\0';i++)          //Copying string 1 to string 3
  {
    str3[i]=str1[i];
    count++;
  }
  for(i=count;str2[j]!='\0';i++)     //Copying string 2 to the end of string 3
  {
    str3[i]=str2[j];
    j++;
  }
  str3[i]='\0';
  printf("\nConcatenated string : ");
  puts(str3);
  return 0;
}

3) By using strcat() function

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  strcat(str1,str2);                    //strcat() function
  printf("\nConcatenated string : ");
  puts(str1);
  return 0;
}

Find the index of a char in string?

"abcdefgh..".IndexOf("d")

returns 3

In general returns first occurrence index, if not present returns -1

How can you run a Java program without main method?

public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

I tried almost all of the above options, but was not able to install google play services, however just found from the faq section of genymotion that the only way to access google play services is to use the packages provided by OpenGapps.

I tried and this worked:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

Measure string size in Bytes in php

PHP's strlen() function returns the number of ASCII characters.

strlen('borsc') -> 5 (bytes)

strlen('boršc') -> 7 (bytes)

$limit_in_kBytes = 20000;

$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
    $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
    // here you can handle (0 - n) parts of string
    $pointer++;
}

$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string

.. or you can use a function like this:

function parseStrToArr($string, $limit_in_kBytes){
    $ret = array();

    $pointer = 0;
    while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
        $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
        $pointer++;
    }

    $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);

    return $ret;
}

$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

How to ensure that there is a delay before a service is started in systemd?

You can run the sleep command before your ExecStart with ExecStartPre :

[Service]
ExecStartPre=/bin/sleep 30

C++ IDE for Linux?

Shorter answer is: choosing whatever "editor" you like, then use GDB console or a simple GDB front end to debug your application. The debuggers come with fancy IDEs such as Netbeans sucks for C/C++. I use Netbeans as my editor, and Insight and GDB console as my debugger.

With insight, you have a nice GUI and the raw power of GDB.

As soon as you get used to GDB commands, you will start to love it since you can do things you will never be able to do using an GUI. You can use even use Python as your script language if you are using GDB 7 or newer version.

Most people here paid more attentions to the "Editors" of the IDEs. However, if you are developing a large project in C/C++, you could easily spend more than 70% of your time on the "debuggers". The debuggers of the fancy IDEs are at least 10 years behind Visual Studio. For instance, Netbenas has very similar interfaces with Visual Studio. But its debugger has a number of disadvantages compared to Visual Studio.

  1. Very slow to display even a array with only a few hundreds of elements
  2. No highlighting for changed value ( By default, visual studio shows changed values in the watch windows in red)
  3. Very limited ability to show memory.
  4. You cannot modify the source code then continue to run. If a bug takes a long time to hit, you would like to change the source and apply the changes live and continue to run your application.
  5. You cannot change the "next statement" to run. In Visual Studio, you can use "Set Next Statement" to change how your application runs. Although this feature could crash your application if not used properly, but it will save you a lot of time. For instance, if you found the state of your application is not correct, but you do not know what caused the problems, you might want to rerun a certain region of the your source codes without restarting your application.
  6. No built-in support for STL such as vector, list, deque and map etc.
  7. No watch points. You need to have this feature, when you need to stop your application right at the point a variable is changed. Intel based computers have hardware watch points so that the watch points will not slow down your system. It might takes many hours to find some hard-to-find bugs without using watch points. "Visual Studio" calls "watch pointer" as "Data BreakPoint".

The list can be a lot longer.

I was so frustrated by the disadvantages of the Netbeans or other similar IDEs, so that I started to learn GDB itself. I found GDB itself are very powerful. GDB does not have all the "disadvantages" mentioned above. Actually, GDB is very powerful, it is even better than Visual Studio in many ways. Here I just show you a very simple example.

For instance, you have a array like:

struct IdAndValue
{
  int ID;
  int value;
};


IdAndValue IdAndValues[1000];

When your application stops, and you want to examine the data in IdAndValues. For instance, if you want to find the ordinals and values in the array for a particular "ID", you can create a script like the following:

define PrintVal 
set $i=0
printf "ID = %d\n", $arg0
while $i<1000
  if IdAndValues[$i].ID == $arg0
    printf "ordinal = %d, value = %d\n", $i, IdAndValues[$i].vaue
    set $i++
  end
end
end

You can use all variables in your application in the current context, your own variables (in our example, it is $i), arguments passed (in our example, it is $arg0) and all GDB commands (built-in or user defined).

Use PrintVal 1 from GDB prompt to print out values for ID "1"

By the way, NetBeans does come with a GDB console, but by using the console, you could crash Netbeans. And I believe that is why the console is hidden by default in NetBeans

.gitignore after commit

However, will it automatically remove these committed files from the repository?

No.

The 'best' recipe to do this is using git filter-branch as written about here:

The man page for git-filter-branch contains comprehensive examples.

Note You'll be re-writing history. If you had published any revisions containing the accidentally added files, this could create trouble for users of those public branches. Inform them, or perhaps think about how badly you need to remove the files.

Note In the presence of tags, always use the --tag-name-filter cat option to git filter-branch. It never hurts and will save you the head-ache when you realize later taht you needed it

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

Jquery UI datepicker. Disable array of Dates

$('input').datepicker({
   beforeShowDay: function(date){
       var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
       return [ array.indexOf(string) == -1 ]
   }
});

How to check object is nil or not in swift?

func isObjectValid(someObject: Any?) -> Any? {
    if someObject is String {
        if let someObject = someObject as? String {
            return someObject
        }else {
            return ""
        }
    }else if someObject is Array<Any> {
        if let someObject = someObject as? Array<Any> {
            return someObject
        }else {
            return []
        }
    }else if someObject is Dictionary<AnyHashable, Any> {
        if let someObject = someObject as? Dictionary<String, Any> {
            return someObject
        }else {
            return [:]
        }
    }else if someObject is Data {
        if let someObject = someObject as? Data {
            return someObject
        }else {
            return Data()
        }
    }else if someObject is NSNumber {
        if let someObject = someObject as? NSNumber{
            return someObject
        }else {
            return NSNumber.init(booleanLiteral: false)
        }
    }else if someObject is UIImage {
        if let someObject = someObject as? UIImage {
            return someObject
        }else {
            return UIImage()
        }
    }
    else {
        return "InValid Object"
    }
}

This function checks any kind of object and return's default value of the kind of object, if object is invalid.

Raising a number to a power in Java

Too late for the OP of course, but still... Rearranging the expression as:

int bmi = (10000 * weight) / (height * height)

Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:

double bmi = (10000.0 * weight) / (height * height)

would still be an improvement.

Count number of objects in list

I spent ages trying to figure this out but it is simple! You can use length(·). length(mylist) will tell you the number of objects mylist contains.

... and just realised someone had already answered this- sorry!

Detecting IE11 using CSS Capability/Feature Detection

Try this:

/*------Specific style for IE11---------*/
 _:-ms-fullscreen, :root 
 .legend 
{ 
  line-height: 1.5em;
  position: relative;
  top: -1.1em;   
}

Implement a simple factory pattern with Spring 3 annotations

Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:

    public interface NamedService {
       String name();
    }

and add abstract class:

public abstract class AbstractFactory<T extends NamedService> {

    private final Map<String, T> map;

    protected AbstractFactory(List<T> list) {
        this.map = list
                .stream()
                .collect(Collectors.toMap(NamedService::name, Function.identity()));
    }

    /**
     * Factory method for getting an appropriate implementation of a service
     * @param name name of service impl.
     * @return concrete service impl.

     */
    public T getInstance(@NonNull final String name) {
        T t = map.get(name);
        if(t == null)
            throw new RuntimeException("Unknown service name: " + name);
        return t;
    }
}

Then we create a concrete factory of specific objects like MyService:

 public interface MyService extends NamedService {
           String name();
           void doJob();
 }

@Component
public class MyServiceFactory extends AbstractFactory<MyService> {

    @Autowired
    protected MyServiceFactory(List<MyService> list) {
        super(list);
    }
}

where List the list of implementations of MyService interface at compile time.

This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.

if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).

How to insert 1000 rows at a time

By the way why don't you use XML data insertion through Stored Procedure?

Here is the link to do that... Inserting Bulk Data through XML-Stored Procedure

Showing empty view when ListView is empty

First check the list contains some values:

if (list.isEmpty()) {
    listview.setVisibility(View.GONE);
}

If it is then OK, otherwise use:

else {
     listview.setVisibility(View.VISIBLE);
}

Regular expression for URL validation (in JavaScript)

/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/

Why is my CSS style not being applied?

Posting, since it might be useful for someone in the future:

For me, when I got here, the solution was browser cache. Had to hard refresh Chrome (cmd/ctrl+shift+R) to get the new styles applied, it seems the old ones got cached really "deep".

This question/answer might come in handy for someone. And hard refresh tips for different browsers for those who don't use Chrome.

How do I add a reference to the MySQL connector for .NET?

When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.

1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).

2)

By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.

If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#LNPLS00809

How to display list items on console window in C#

I found this easier to understand:

List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
        for (int i = 0; i < names.Count; i++)
        {
            Console.WriteLine(names[i]);
        }

How do I append one string to another in Python?

Basically, no difference. The only consistent trend is that Python seems to be getting slower with every version... :(


List

%%timeit
x = []
for i in range(100000000):  # xrange on Python 2.7
    x.append('a')
x = ''.join(x)

Python 2.7

1 loop, best of 3: 7.34 s per loop

Python 3.4

1 loop, best of 3: 7.99 s per loop

Python 3.5

1 loop, best of 3: 8.48 s per loop

Python 3.6

1 loop, best of 3: 9.93 s per loop


String

%%timeit
x = ''
for i in range(100000000):  # xrange on Python 2.7
    x += 'a'

Python 2.7:

1 loop, best of 3: 7.41 s per loop

Python 3.4

1 loop, best of 3: 9.08 s per loop

Python 3.5

1 loop, best of 3: 8.82 s per loop

Python 3.6

1 loop, best of 3: 9.24 s per loop

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

What should every programmer know about security?

Rule #1 of security for programmers: Don't roll your own

Unless you are yourself a security expert and/or cryptographer, always use a well-designed, well-tested, and mature security platform, framework, or library to do the work for you. These things have spent years being thought out, patched, updated, and examined by experts and hackers alike. You want to gain those advantages, not dismiss them by trying to reinvent the wheel.

Now, that's not to say you don't need to learn anything about security. You certainly need to know enough to understand what you're doing and make sure you're using the tools correctly. However, if you ever find yourself about to start writing your own cryptography algorithm, authentication system, input sanitizer, etc, stop, take a step back, and remember rule #1.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Variables have a type and a value.

  • $var = "test" is a string that contain "test"
  • $var2 = 24 is an integer vhose value is 24.

When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do

if ($var == 1) {... do something ...}

PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.

When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.

This is useful, for example, when you have a function that can return false (on error) and 0 (result) :

if(myFunction() == false) { ... error on myFunction ... }

This code is wrong as if myFunction() returns 0, it is casted to false and you seem to have an error. The correct code is :

if(myFunction() === false) { ... error on myFunction ... }

because the test is that the return value "is a boolean and is false" and not "can be casted to false".

AngularJS access scope from outside js function

Here's a reusable solution: http://jsfiddle.net/flobar/r28b0gmq/

function accessScope(node, func) {
    var scope = angular.element(document.querySelector(node)).scope();
    scope.$apply(func);
}

window.onload = function () {

    accessScope('#outer', function (scope) {
        // change any property inside the scope
        scope.name = 'John';
        scope.sname = 'Doe';
        scope.msg = 'Superhero';
    });

};

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

Why do this() and super() have to be the first statement in a constructor?

So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.

Actually you can execute logic with several expessions, you just have to wrap your code in a static function and call it in the super statement.

Using your example:

public class MySubClassC extends MyClass {
    public MySubClassC(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(createList(item));  // OK
    }

    private static List createList(item) {
        List list = new ArrayList();
        list.add(item);
        return list;
    }
}

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

In Firebase, is there a way to get the number of children of a node without loading all the node data?

write a cloud function to and update the node count.

// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.userscount = functions.database.ref('/users/')
    .onWrite(event => {

      console.log('users number : ', event.data.numChildren());


      return event.data.ref.parent.child('count/users').set(event.data.numChildren());
    }); 

Refer :https://firebase.google.com/docs/functions/database-events

root--| |-users ( this node contains all users list) |
|-count |-userscount : (this node added dynamically by cloud function with the user count)

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

How does java do modulus calculations with negative numbers?

Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

How to prune local tracking branches that do not exist on remote anymore

It will list the local branches whose remote tracking branch is deleted from remote

$ git remote prune origin --dry-run

If you want to de-reference these local branches from local which are un tracked

$ git remote prune origin

:touch CSS pseudo-class or something similar?

I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

Can I run Keras model on gpu?

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).

Pandas: convert dtype 'object' to int

This was my data

## list of columns 
l1 = ['PM2.5', 'PM10', 'TEMP', 'BP', ' RH', 'WS','CO', 'O3', 'Nox', 'SO2'] 

for i in l1:
 for j in range(0, 8431): #rows = 8431
   df[i][j] = int(df[i][j])

I recommend you to use this only with small data. This code has complexity of O(n^2).

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Java ResultSet how to check if there are any results

Assuming you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst(). This avoids having to back-track if the data is to be read.

As explained in the documentation, this returns false if the cursor is not before the first record or if there are no rows in the ResultSet.

if (!resultSet.isBeforeFirst() ) {    
    System.out.println("No data"); 
} 

 

Java Package Does Not Exist Error

Right click your maven project in bottom of the drop down list Maven >> reimport

it works for me for the missing dependancyies

How to add List<> to a List<> in asp.net

Use List.AddRange(collection As IEnumerable(Of T)) method.

It allows you to append at the end of your list another collection/list.

Example:

List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);

Export SQL query data to Excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

Is there any way to call a function periodically in JavaScript?

Since you want the function to be executed periodically, use setInterval

Consider marking event handler as 'passive' to make the page more responsive

For jquery-ui-dragable with jquery-ui-touch-punch I fixed it similar to Iván Rodríguez, but with one more event override for touchmove:

jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener('touchstart', handle, { passive: !ns.includes('noPreventDefault') });
    }
};
jQuery.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener('touchmove', handle, { passive: !ns.includes('noPreventDefault') });
    }
};

Invalid argument supplied for foreach()

More concise extension of @Kris's code

function secure_iterable($var)
{
    return is_iterable($var) ? $var : array();
}

foreach (secure_iterable($values) as $value)
{
     //do stuff...
}

especially for using inside template code

<?php foreach (secure_iterable($values) as $value): ?>
    ...
<?php endforeach; ?>

How can I remove the extension of a filename in a shell script?

If your filename contains a dot (other than the one of the extension) then use this:

echo $filename | rev | cut -f 2- -d '.' | rev

iCheck check if checkbox is checked

I wrote some simple thing:

When you initialize icheck as:

$('input').iCheck({
    checkboxClass: 'icheckbox_square-blue',
    radioClass: 'iradio_square-blue',
    increaseArea: '20%' // optional
});

Add this code under it:

$('input').on('ifChecked', function (event){
    $(this).closest("input").attr('checked', true);          
});
$('input').on('ifUnchecked', function (event) {
    $(this).closest("input").attr('checked', false);
});

After this you can easily find your original checkbox's state. I wrote this code for using icheck in gridView and accessed its state from server side by C#.

Simply find your checkBox from its id.

How do I get list of methods in a Python class?

methods = [(func, getattr(o, func)) for func in dir(o) if callable(getattr(o, func))]

gives an identical list as

methods = inspect.getmembers(o, predicate=inspect.ismethod)

does.

Array Index Out of Bounds Exception (Java)

import java.io.*;
import java.util.Scanner;
class ar1 {
    public static void main(String[] args) {
        //Scanner sc=new Scanner(System.in);
        int[] a={10,20,30,40,12,32};
        int bi=0,sm=0;
        //bi=sc.nextInt();
        //sm=sc.nextInt();
        for(int i=0;i<=a.length-1;i++) {
            if(a[i]>a[i+1]) 
                bi=a[i];

            if(a[i]<a[i+1])
                sm=a[i];
        }
        System.out.println("big"+bi+"small"+sm);
    }
}

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

How to extract base URL from a string in JavaScript?

Well, URL API object avoids splitting and constructing the url's manually.

 let url = new URL('https://stackoverflow.com/questions/1420881');
 alert(url.origin);

Session timeout in ASP.NET

After changing the session timeout value in IIS, Kindly restart the IIS. To achieve this go to command prompt. Type IISRESET and press enter.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

For me the accepted answer did not yet work. I started off as suggested here:

ln -s /usr/bin/nodejs /usr/bin/node

After doing this I was getting the following error:

/usr/local/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3

The solution was to download the most recent version of node from https://nodejs.org/en/download/ .

Then I did:

sudo tar -xf node-v10.15.0-linux-x64.tar.xz --directory /usr/local --strip-components 1

Now the update was finally successful: npm -v changed from 3.2.1 to 6.4.1

Bootstrap: add margin/padding space between columns

You may use the padding and margin shorthand Bootstrap 4 classes as follows:

For extra small devices i.e. xs

{property}{sides}-{size}

For other devices/viewports (small, medium, large and extra large)

{property}{sides}-{breakpoint}-{size}

Where:

property = m for margin and p for padding

Following are sides shorthand meanings:

l = defines the left-margin or left-padding
r = defines the right-margin or right-padding
t = defines the top-margin or top-padding
b = defines the bottom-margin or right-padding
x = For setting left and right padding and margins by the single call
y = For setting top and bottom margins
blank = margin and padding for all sides

The breakpoint = sm, md, lg, and xl.

Combining all the above, the left padding complete code can be (for example):

For left padding in extra small devices

pl-2

or for medium to extra large

pl-md-2

Replace given value in vector

Perhaps replace is what you are looking for:

> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1

Or, if you don't have x (any specific reason why not?):

replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)

Many people are familiar with gsub, so you can also try either of the following:

as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))

Update

After reading the comments, perhaps with is an option:

with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Bootstrap 3 and Youtube in Modal

Found this in another thread, and it works great on desktop and mobile - which is something that didn't seem true with some of the other solutions. Add this script to the end of your page:

<!--Script stops video from playing when modal is closed-->
<script>
    $("#myModal").on('hidden.bs.modal', function (e) {
        $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
    });
</script>   

Create Table from View

Looks a lot like Oracle, but that doesn't work on SQL Server.

You can, instead, adopt the following syntax...

SELECT
  *
INTO
  new_table
FROM
  old_source(s)

Double free or corruption after queue::push

You need to define a copy constructor, assignment, operator.

class Test {
   Test(const Test &that); //Copy constructor
   Test& operator= (const Test &rhs); //assignment operator
}

Your copy that is pushed on the queue is pointing to the same memory your original is. When the first is destructed, it deletes the memory. The second destructs and tries to delete the same memory.

How to convert an int value to string in Go?

fmt.Sprintf, strconv.Itoa and strconv.FormatInt will do the job. But Sprintf will use the package reflect, and it will allocate one more object, so it's not an efficient choice.

enter image description here

How can I set the default value for an HTML <select> element?

Set selected="selected" for the option you want to be the default.

<option selected="selected">
3
</option>

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

Open and write data to text file using Bash?

You can redirect the output of a command to a file:

$ cat file > copy_file

or append to it

$ cat file >> copy_file

If you want to write directly the command is echo 'text'

$ echo 'Hello World' > file

Node.js Hostname/IP doesn't match certificate's altnames

The other way to fix this in other circumstances is to use NODE_TLS_REJECT_UNAUTHORIZED=0 as an environment variable

NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js

WARNING: This is a bad idea security-wise

How to solve static declaration follows non-static declaration in GCC C code?

I have had this issue in a case where the static function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.

How to make a JSONP request from Javascript without JQuery?

I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js

Take a look at it and let me know if you need any help using or understanding the code.

Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/

How to remove trailing whitespaces with sed?

You can use the in place option -i of sed for Linux and Unix:

sed -i 's/[ \t]*$//' "$1"

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

sed -i '' -E 's/[ '$'\t'']+$//' "$1"

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.

number of values in a list greater than a certain number

You can do like this using function:

l = [34,56,78,2,3,5,6,8,45,6]  
print ("The list : " + str(l))   
def count_greater30(l):  
    count = 0  
    for i in l:  
        if i > 30:  
            count = count + 1.  
    return count
print("Count greater than 30 is : " + str(count)).  
count_greater30(l)

How do I format a String in an email so Outlook will print the line breaks?

I also had this issue with plain/text mail type.Form Feed \f worked for me.

curl.h no such file or directory

yes please download curl-devel as instructed above. also don't forget to link to lib curl:

-L/path/of/curl/lib/libcurl.a (g++)

cheers

Attach event to dynamic elements in javascript

I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT. Here is the code with a simple example:

_x000D_
_x000D_
String.prototype.addEventListener=function(eventHandler, functionToDo){_x000D_
  let selector=this;_x000D_
  document.body.addEventListener(eventHandler, function(e){_x000D_
    e=(e||window.event);_x000D_
    e.preventDefault();_x000D_
    const path=e.path;_x000D_
    path.forEach(function(elem){_x000D_
      const selectorsArray=document.querySelectorAll(selector);_x000D_
      selectorsArray.forEach(function(slt){_x000D_
        if(slt==elem){_x000D_
          if(typeof functionToDo=="function") functionToDo(el=slt, e=e);_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
// And here is how we can use it actually !_x000D_
_x000D_
"input[type='number']".addEventListener("click", function(element, e){_x000D_
 console.log( e ); // Console log the value of the current number input_x000D_
});
_x000D_
<input type="number" value="25">_x000D_
<br>_x000D_
<input type="number" value="15">_x000D_
<br><br>_x000D_
<button onclick="addDynamicInput()">Add a Dynamic Input</button>_x000D_
<script type="text/javascript">_x000D_
  function addDynamicInput(){_x000D_
    const inpt=document.createElement("input");_x000D_
          inpt.type="number";_x000D_
          inpt.value=Math.floor(Math.random()*30+1);_x000D_
    document.body.prepend(inpt);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Remove empty strings from a list of strings

Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.

strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]

The answer for this will be ["first", "second"].
If you want to use filter method instead, you can do like
list(filter(lambda item: item.strip(), strings)). This is give the same result.

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

Python Pandas : pivot table with aggfunc = count unique distinct

aggfunc=pd.Series.nunique provides distinct count.

Full Code:

df2.pivot_table(values='X', rows='Y', cols='Z', 
                         aggfunc=pd.Series.nunique)

Credit to @hume for this solution (see comment under the accepted answer). Adding as an answer here for better discoverability.

How to set a:link height/width with css?

add display: block;

a-tag is an inline element so your height and width are ignored.

#header div#snav div a{
    display:block;
    width:150px;
    height:77px;
}

MySQL Error 1093 - Can't specify target table for update in FROM clause

how about this query hope it helps

DELETE FROM story_category LEFT JOIN (SELECT category.id FROM category) cat ON story_category.id = cat.id WHERE cat.id IS NULL

Check a collection size with JSTL

use ${fn:length(companies) > 0} to check the size. This returns a boolean

MySQL select one column DISTINCT, with corresponding other columns

SELECT ID,LastName 
From TABLE_NAME 
GROUP BY FirstName 
HAVING COUNT(*) >=1

Convert MySQL to SQlite

There are different ways to do this. I also had this problem and I searched a lot and then I got a simple way to convert MySQL to SQLite.

Follow these steps:

  1. First You Need to Install SQLite DB Browser (very small and fast to view Tables and Data)

  2. Open your MySQL File in Notepad or it would be great if you open in Notepad++

  3. Remove First extra Lines Contains Information or Queries and Save it.

  4. Open SQLite DB Browser, Create Database, then Tables, and Same Types as it is in MySQL Database.

  5. In Menu Bar of SQLite DB Browser Select File-> then Import data MySQL File which you saved.

It will easily Convert into SQLite After Warning Dialog.

If error then remove more extra lines if your MySQL file have.

You can also Install MySQL to SQLite Converter Software on trial Basis, but the information I am giving for conversion is life time.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

With JQuery this stuff is pretty easy to do. Since you can bind to sets.

Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

Extracting extension from filename in Python

# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs

import os.path

class LinkChecker:

    @staticmethod
    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
        else:
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
            else:
                return ""

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

Remove Identity from a column in a table

Bellow code working as fine, when we don't know identity column name.

Need to copy data into new temp table like Invoice_DELETED. and next time we using:

insert into Invoice_DELETED select * from Invoice where ...


SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = @InvoiceID

For more explanation see: https://dba.stackexchange.com/a/138345/101038

How to round the double value to 2 decimal points?

public static double addDoubles(double a, double b) {
        BigDecimal A = new BigDecimal(a + "");
        BigDecimal B = new BigDecimal(b + "");
        return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

How do you run a command as an administrator from the Windows command line?

Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

I found this instead. Just put it all before your code, and it works perfectly.

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

How to send a simple string between two programs using pipes?

dup2( STDIN_FILENO, newfd )

And read:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );    

But, I think that fcntl can be a better solution

echo "salut" | code

LINQ orderby on date field in descending order

This statement will definitely help you:

env = env.OrderByDescending(c => c.ReportDate).ToList();

Facebook API error 191

For me, it was a missing app domain. Go into the app, and make sure that you have the root of your site set up as an app domain. See screenshot.

app domains is in the basic settings of your app

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

JavaScript - document.getElementByID with onClick

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

How to check if a map contains a key in Go?

    var empty struct{}
    var ok bool
    var m map[string]struct{}
    m = make(map[string]struct{})
    m["somestring"] = empty


    _, ok = m["somestring"]
    fmt.Println("somestring exists?", ok) 
    _, ok = m["not"]
    fmt.Println("not exists?", ok)

Then, go run maps.go somestring exists? true not exists? false

In C# check that filename is *possibly* valid (not that it exists)

There are several methods you could use that exist in the System.IO namespace:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

bool IsValidFilename(string testName) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

    // other checks for UNC, drive-path format, etc

    return true;
}