Programs & Examples On #Updatepanelanimationexte

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Create controller for partial view in ASP.NET MVC

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

Laravel 5 Carbon format datetime

If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance

So it should be

$suborder['payment_date'] = $item->created_at->format('Y-m-d')

But if it is not then, you need convert it to Carbon object as Milan Maharjan answer

$createdAt = Carbon::parse($item['created_at']);

Content is not allowed in Prolog SAXParserException

to simply remove it, paste your xml file into notepad, you'll see the extra character before the first tag. Remove it & paste back into your file - bof

ASP.NET Core - Swashbuckle not creating swagger.json file

If you have any issues in your controller to map to an unique URL you get this error.

The best way to find the cause of issue is exclude all controllers from project. Then try running the app by enabling one controller or one or more methods in a controller at a time to find the controllers/ controller method(S) which have an issue. Or you could get smart and do a binary search logic to find the disable enable multiple controller/methods to find the faulty ones.

Some of the causes is

  1. Having public methods in controller without HTTP method attributes

  2. Having multiple methods with same Http attributes which could map to same api call if you are not using "[action]" based mapping

  3. If you are using versioning make sure you have the method in all the controller versions (if using inheritance even though you use from base)

C# Change A Button's Background Color

// WPF

// Defined Color
button1.Background = Brushes.Green;

// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));

JavaScript: remove event listener

Try this, it worked for me.

<button id="btn">Click</button>
<script>
 console.log(btn)
 let f;
 btn.addEventListener('click', f=function(event) {
 console.log('Click')
 console.log(f)
 this.removeEventListener('click',f)
 console.log('Event removed')
})  
</script>

Trigger insert old values- values that was updated

In your trigger, you have two pseudo-tables available, Inserted and Deleted, which contain those values.

In the case of an UPDATE, the Deleted table will contain the old values, while the Inserted table contains the new values.

So if you want to log the ID, OldValue, NewValue in your trigger, you'd need to write something like:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS 
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

Basically, you join the Inserted and Deleted pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted table, the new value from the Inserted table, and you store everything in the LogTable

VBA Public Array : how to?

Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

What is the difference between Builder Design pattern and Factory Design pattern?

  • Constructing a complex object step by step : builder pattern

  • A simple object is created by using a single method : factory method pattern

  • Creating Object by using multiple factory method : Abstract factory pattern

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

A generic list of anonymous class

static void Main()
{
    List<int> list = new List<int>();
    list.Add(2);
    list.Add(3);
    list.Add(5);
    list.Add(7);
}

How to move table from one tablespace to another in oracle 11g

Moving tables:

First run:

SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';

-- Or suggested in the comments (did not test it myself)

SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; ' 
FROM dba_tables 
WHERE OWNER = '<SCHEMA>' 
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>

Where <schema_name> is the name of the user. And <tablespace_name> is the destination tablespace.

As a result you get lines like:

ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Moving indexes:

First run:

SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;' 
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';

The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.

As a result you should get something like:

ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Last but not least, moving LOBs:

First run:

SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';

This moves the LOB objects to the other tablespace.

As a result you should get something like:

ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);

Paste the results in a script or in a oracle sql developer like application and run it.

O and there is one more thing:

For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.

Dialog to pick image from gallery or from camera

I have merged some solutions to make a complete util for picking an image from Gallery or Camera. These are the features of ImagePicker util gist (also in a Github lib):

  • Merged intents for Gallery and Camera resquests.
  • Resize selected big images (e.g.: 2500 x 1600)
  • Rotate image if necesary

Screenshot:

ImagePicker starting intent

Edit: Here is a fragment of code to get a merged Intent for Gallery and Camera apps together. You can see the full code at ImagePicker util gist (also in a Github lib):

public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resInfo) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent targetedIntent = new Intent(intent);
        targetedIntent.setPackage(packageName);
        list.add(targetedIntent);
    }
    return list;
}

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

Easiest way to copy a table from one database to another?

it's worked good for me

CREATE TABLE dbto.table_name like dbfrom.table_name;
insert into  dbto.table_name select * from dbfrom.table_name;

mySQL select IN range

To select data in numerical range you can use BETWEEN which is inclusive.

SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;

Passing JavaScript array to PHP through jQuery $.ajax

This worked for me:

$.ajax({
    url:"../messaging/delete.php",
    type:"POST",
    data:{messages:selected},
    success:function(data){
     if(data === "done"){

     }
     info($("#notification"), data);
    },
    beforeSend:function(){
         info($("#notification"),"Deleting "+count+" messages");
    },
    error:function(jqXHR, textStatus, errorMessage){
        error($("#notification"),errorMessage);
    }
});

And this for your PHP:

$messages = $_POST['messages']
foreach($messages as $msg){
    echo $msg;
}

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

OracleCommand SQL Parameters Binding

Here is how I solved the same problem using the Oracle.DataAccess.Client Namespace.

using Oracle.DataAccess.Client;


string strConnection = ConfigurationManager.ConnectionStrings["oConnection"].ConnectionString;

dataConnection = new OracleConnectionStringBuilder(strConnection);

OracleConnection oConnection = new OracleConnection(dataConnection.ToString());

oConnection.Open();

OracleCommand tmpCommand = oConnection.CreateCommand();
tmpCommand.Parameters.Add("user", OracleDbType.Varchar2, txtUser.Text, ParameterDirection.Input);
tmpCommand.CommandText = "SELECT USER, PASS FROM TB_USERS WHERE USER = :1";

try
{
    OracleDataReader tmpReader = tmpCommand.ExecuteReader(CommandBehavior.SingleRow);
    
    if (tmpReader.HasRows)
    {
        // PT: IMPLEMENTE SEU CÓDIGO    
        // ES: IMPLEMENTAR EL CÓDIGO
        // EN: IMPLEMENT YOUR CODE
    }
}
catch(Exception e)
{
        // PT: IMPLEMENTE SEU CÓDIGO    
        // ES: IMPLEMENTAR EL CÓDIGO
        // EN: IMPLEMENT YOUR CODE
}

What are the advantages and disadvantages of recursion?

Any algorithm implemented using recursion can also be implemented using iteration.

Why not to use recursion

  1. It is usually slower due to the overhead of maintaining the stack.
  2. It usually uses more memory for the stack.

Why to use recursion

  1. Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn't necessarily reduce space requirements or speed of execution).
  2. Reduces time complexity.
  3. Performs better in solving problems based on tree structures.

For example, the Tower of Hanoi problem is more easily solved using recursion as opposed to iteration.

Remove Primary Key in MySQL

Without an index, maintaining an autoincrement column becomes too expensive, that's why MySQL requires an autoincrement column to be a leftmost part of an index.

You should remove the autoincrement property before dropping the key:

ALTER TABLE user_customer_permission MODIFY id INT NOT NULL;
ALTER TABLE user_customer_permission DROP PRIMARY KEY;

Note that you have a composite PRIMARY KEY which covers all three columns and id is not guaranteed to be unique.

If it happens to be unique, you can make it to be a PRIMARY KEY and AUTO_INCREMENT again:

ALTER TABLE user_customer_permission MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT;

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); },

How can I determine the status of a job?

we can query the msdb in many ways to get the details.

few are

select job.Name, job.job_ID, job.Originating_Server,activity.run_requested_Date,
datediff(minute, activity.run_requested_Date, getdate()) as Elapsed 
from msdb.dbo.sysjobs_view job 
inner join msdb.dbo.sysjobactivity activity on (job.job_id = activity.job_id) 
where run_Requested_date is not null 
and stop_execution_date is null 
and job.name like 'Your Job Prefix%'

How to split a file into equal parts, without breaking individual lines?

I made a bash script, that given a number of parts as input, split a file

#!/bin/sh

parts_total="$2";
input="$1";

parts=$((parts_total))
for i in $(seq 0 $((parts_total-2))); do
  lines=$(wc -l "$input" | cut -f 1 -d" ")
  #n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1
  n=$(awk  -v lines=$lines -v parts=$parts 'BEGIN { 
    n = lines/parts;
    rounded = sprintf("%.0f", n);
    if(n>rounded){
      print rounded + 1;
    }else{
      print rounded;
    }
  }');
  head -$n "$input" > split${i}
  tail -$((lines-n)) "$input" > .tmp${i}
  input=".tmp${i}"
  parts=$((parts-1));
done
mv .tmp$((parts_total-2)) split$((parts_total-1))
rm .tmp*

I used head and tail commands, and store in tmp files, for split the files

#10 means 10 parts
sh mysplitXparts.sh input_file 10

or with awk, where 0.1 is 10% => 10 parts, or 0.334 is 3 parts

awk -v size=$(wc -l < input) -v perc=0.1 '{
  nfile = int(NR/(size*perc)); 
  if(nfile >= 1/perc){
    nfile--;
  } 
  print > "split_"nfile
}' input

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How do I get the day month and year from a Windows cmd.exe script?

A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.

::: Begin set date

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date
::: End set date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.

can't multiply sequence by non-int of type 'float'

Python allows for you to multiply sequences to repeat their values. Here is a visual example:

>>> [1] * 5
[1, 1, 1, 1, 1]

But it does not allow you to do it with floating point numbers:

>>> [1] * 5.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

decompiling DEX into Java sourcecode

A more complete version of fred's answer:

Manual way

First you need a tool to extract all the (compiled) classes on the DEX to a JAR.
There's one called dex2jar, which is made by a chinese student.

Then, you can use jd-gui to decompile the classes on the JAR to source code.
The resulting source should be quite readable, as dex2jar applies some optimizations.

Automatic way

You can use APKTool. It will automatically extract all the classes (.dex), resources (.asrc), then it will convert binary XML to human-readable XML, and it will also dissassemble the classes for you.
Disassembly will always be more robust than decompiling, especially with
JARs obfuscated with Pro Guard!

Just tell APKTool to decode the APK into a directory, then modify what you want,
and finally encode it back to an APK. That's all.

Important: APKTool dissassembles. It doesn't decompile.
The generated code won't be Java source.
But you should be able to read it, and even edit it if you're familiar with jasmin.
If you want Java source, please go over the Manual way.

What exactly does += do in python?

Note x += y is not the same as x = x + y in some situations where an additional operator is included because of the operator precedence combined with the fact that the right hand side is always evaluated first, e.g.

>>> x = 2
>>> x += 2 and 1
>>> x
3

>>> x = 2
>>> x = x + 2 and 1
>>> x
1

Note the first case expand to:

>>> x = 2
>>> x = x + (2 and 1)
>>> x
3

You are more likely to encounter this in the 'real world' with other operators, e.g.

x *= 2 + 1 == x = x * (2 + 1) != x = x * 2 + 1

Remove all occurrences of char from string

Hello Try this code below

public class RemoveCharacter {

    public static void main(String[] args){
        String str = "MXy nameX iXs farXazX";
        char x = 'X';
        System.out.println(removeChr(str,x));
    }

    public static String removeChr(String str, char x){
        StringBuilder strBuilder = new StringBuilder();
        char[] rmString = str.toCharArray();
        for(int i=0; i<rmString.length; i++){
            if(rmString[i] == x){

            } else {
                strBuilder.append(rmString[i]);
            }
        }
        return strBuilder.toString();
    }
}

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

How to get file creation date/time in Bash/Debian?

mikyra's answer is good.The fact just like what he said.

[jason@rh5 test]$ stat test.txt
  File: `test.txt'
  Size: 0               Blocks: 8          IO Block: 4096   regular empty file
Device: 802h/2050d      Inode: 588720      Links: 1
Access: (0664/-rw-rw-r--)  Uid: (  500/   jason)   Gid: (  500/   jason)
Access: 2013-03-14 01:58:12.000000000 -0700
Modify: 2013-03-14 01:58:12.000000000 -0700
Change: 2013-03-14 01:58:12.000000000 -0700

if you want to verify wich file was created first,you can structure your file name by appending system date when you create a series of files.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

I had tried almost all the above methods.

Finally fixed it by including the

script src="{%static 'App/js/jquery.js' %}"

just after loading the staticfiles i.e {% load staticfiles %} in base.html

Catching multiple exception types in one catch block

In PHP >= 7.1 this is possible. See this answer.


If you can modify the exceptions, use this answer.

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

But it would probably be better to use multiple catch blocks as described in aforementioned answer.

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}

You need to use a Theme.AppCompat theme (or descendant) with this activity

I had the same problem, but it solved when i put this on manifest: android:theme="@style/Theme.AppCompat.

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name_test"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat">

        ...    

    </application>

Insert Data Into Temp Table with Query

SQL Server R2 2008 needs the AS clause as follows:

SELECT * 
INTO #temp
FROM (
    SELECT col1, col2
    FROM table1
) AS x

The query failed without the AS x at the end.


EDIT

It's also needed when using SS2016, had to add as t to the end.

 Select * into #result from (SELECT * FROM  #temp where [id] = @id) as t //<-- as t

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Replace only some groups with Regex

A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

or using a MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

Another way, slightly messy, could be using a lookbehind/lookahead:

(?<=-)(\d+)(?=-)

Why is this jQuery click function not working?

Proper Browser Reload

Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.

See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

Oracle: how to UPSERT (update or insert into a table?)

Try this,

insert into b_building_property (
  select
    'AREA_IN_COMMON_USE_DOUBLE','Area in Common Use','DOUBLE', null, 9000, 9
  from dual
)
minus
(
  select * from b_building_property where id = 9
)
;

Google Maps API v3: Can I setZoom after fitBounds?

I've found a solution that does the check before calling fitBounds so you don't zoom in and suddenly zoom out

var bounds = new google.maps.LatLngBounds();

// extend bounds with each point

var minLatSpan = 0.001;
if (bounds.toSpan().lat() > minLatSpan) {
    gmap.fitBounds(bounds); 
} else {
    gmap.setCenter(bounds.getCenter());
    gmap.setZoom(16);
}

You'll have to play around with the minLatSpan variable a bit to get it where you want. It will vary based on both zoom-level and the dimensions of the map canvas.

You could also use longitude instead of latitude

socket.error: [Errno 48] Address already in use

Simple one line command to get rid of it, type below command in terminal,

ps -a

This will list out all process, checkout which is being used by Python and type bellow command in terminal,

kill -9 (processID) 

For example kill -9 33178

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. My solution was to make all vectors numeric.

How to read the Stock CPU Usage data

This should be the Unix load average. Wikipedia has a nice article about this.

The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes

UIImageView aspect fit and center

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

How do I download code using SVN/Tortoise from Google Code?

Create a folder where you want to keep the code, and right click on it. Choose SVN Checkout... and type http://wittytwitter.googlecode.com/svn/trunk into the URL of repository field.

You can also run

svn checkout http://wittytwitter.googlecode.com/svn/trunk

from the command line in the folder you want to keep it (svn.exe has to be in your path, of course).

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/

However, if you want to see the mongo's admin web page, you could do it, with this command:

mongod --rest --httpinterface

browsing this url: http://localhost:28017/

the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

Oracle PL/SQL - How to create a simple array variable?

Another solution is to use an Oracle Collection as a Hashmap:

declare 
-- create a type for your "Array" - it can be of any kind, record might be useful
  type hash_map is table of varchar2(1000) index by varchar2(30);
  my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
  i varchar2(30);
begin
  my_hmap('a') := 'apple';
  my_hmap('b') := 'box';
  my_hmap('c') := 'crow';
-- then how you use it:

  dbms_output.put_line (my_hmap('c')) ;

-- or to loop on every element - it's a "collection"
  i := my_hmap.FIRST;

  while (i is not null)  loop     
    dbms_output.put_line(my_hmap(i));      
    i := my_hmap.NEXT(i);
  end loop;

end;

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).


Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

read string from .resx file in C#

I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.

Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.

There may be reasons not to do this that I don't know about, but it worked for me.

JAXB Exception: Class not known to this context

Your ProfileDto class is not referenced in SearchResultDto. Try adding @XmlSeeAlso(ProfileDto.class) to SearchResultDto.

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

How to change the floating label color of TextInputLayout

you should change your colour here

<style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#673AB7</item>
        <item name="colorPrimaryDark">#512DA8</item>
        <item name="colorAccent">#FF4081</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Best way to use sql brackets use callback function in laravel eloquent.

YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere('b', 1);
})->where(function ($q) {
    $q->where('c', 1)->orWhere('d', 1);
});

You don't have to use = symbol, it's come as the default

Lest say if you have a query that contain brackets inside a brackets

WHERE (a = 1 OR (b = 1 and c = 5))


YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere(function($q2){
      $q2->where('b', 1)->where('c', 5);
    });
});

lest say you want to make values dynamics

YourModal::where(function ($q) use($val1, $val2) {
    $q->where('a', $val1)->orWhere(function($q2) use($val2){
      $q2->where('b', $val2)->where('c', $val2);
    });
});

cv2.imshow command doesn't work properly in opencv-python

I faced the same issue. I tried to read an image from IDLE and tried to display it using cv2.imshow(), but the display window freezes and shows pythonw.exe is not responding when trying to close the window.

The post below gives a possible explanation for why this is happening

pythonw.exe is not responding

"Basically, don't do this from IDLE. Write a script and run it from the shell or the script directly if in windows, by naming it with a .pyw extension and double clicking it. There is apparently a conflict between IDLE's own event loop and the ones from GUI toolkits."

When I used imshow() in a script and execute it rather than running it directly over IDLE, it worked.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

If Publishing in Visual Studio 2012 when erroring try unchecking the "Procompile during publishing" option in the Publish wizard.

Un-check "Precompile during publishing"

JetBrains / IntelliJ keyboard shortcut to collapse all methods

go to menu option Code > Folding to access all code folding related options and their shortcuts.

Fixed size div?

As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:

.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }

<div class="container">
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
</div>

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

JavaScript string with new line - but not using \n

I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

When to use .First and when to use .FirstOrDefault with LINQ?

Ok let me give my two cents. First / Firstordefault are for when you use the second constructor. I won't explain what it is, but it's when you would potentially always use one because you don't want to cause an exception.

person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
    return string.IsNullOrEmpty(p.Relationship);
}));

Javascript objects: get parent

Many of the answers here involve looping through an object and "manually" (albeit programmatically) creating a parent property that stores the reference to the parent. The two ways of implementing this seem to be...

  1. Use an init function to loop through at the time the nested object is created, or...
  2. Supply the nested object to a function that fills out the parent property

Both approaches have the same issue...

How do you maintain parents as the nested object grows/changes??

If I add a new sub-sub-object, how does it get its parent property filled? If you're (1) using an init function, the initialization is already done and over, so you'd have to (2) pass the object through a function to search for new children and add the appropriate parent property.

Using ES6 Proxy to add parent whenever an object/sub-object is set

The approach below is to create a handler for a proxy always adds a parent property each time an object is set. I've called this handler the parenter handler. The parenter responsibilities are to recognize when an object is being set and then to...

  1. Create a dummy proxy with the appropriate parent and the parenter handler

    var p = new Proxy({parent: target}, parenter);
    
  2. Copy in the supplied objects properties-- Because you're setting the proxy properties in this loop the parenter handler is working recursively; nested objects are given parents at each level

    for(key in value){
        p[key] = value[key];
      }
    
  3. Set the proxy not the supplied object

    return target[prop] = p;
    

Full code

var parenter = {
  set: function(target, prop, value){
    if(typeof value === "object"){
      var p = new Proxy({parent: target}, parenter);
      for(key in value){
        p[key] = value[key];
      }
      return target[prop] = p;
    }else{
      target[prop] = value;
    }
  }
}

var root = new Proxy({}, parenter);

// some examples
root.child1 = {
    color: "red", 
    value: 10, 
    otherObj: { 
       otherColor: "blue", 
       otherValue: 20
    }
}

// parents exist/behave as expected
console.log(root.child1.color)                 // "red"
console.log(root.child1.otherObj.parent.color) // "red"

// new children automatically have correct parent
root.child2 = {color: "green", value3: 50};
console.log(root.child2.parent.child1.color)   // "red"

// changes are detected throughout
root.child1.color = "yellow"
console.log(root.child2.parent.child1.color)   // "yellow"

Notice that all root children always have parent properties, even children that are added later.

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

Command-line tool for finding out who is locking a file

Handle didn't find that WhatsApp is holding lock on a file .tmp.node in temp folder. ProcessExplorer - Find works better Look at this answer https://superuser.com/a/399660

What is the difference between ports 465 and 587?

The correct answer to this question has been changed by the publication of RFC 8314. As a result, port 465 and 587 are both valid ports for a mail submission agent (MSA). Port 465 requires negotiation of TLS/SSL at connection setup and port 587 uses STARTTLS if one chooses to negotiate TLS. The IANA registry was updated to allow legitimate use of port 465 for this purpose. For mail relay, only port 25 is used so STARTTLS is the only way to do TLS with mail relay. It's helpful to think of mail relay and mail submission as two very different services (with many behavior differences like requiring auth, different timeouts, different message modification rules, etc.) that happen to use a similar wire protocol.

Submitting the value of a disabled input field

you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable

<input type="text" name="lat" value="22.2222" readonly="readonly" />

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

Please see what the update-alternatives command does (it has a nice man...).

Shortly - what happens when you have java-sun-1.4 and java-opensouce-1.0 ... which one takes "java"? It debian "/usr/bin/java" is symbolic link and "/usr/bin/java-sun-1.4" is an alternative to "/usr/bin/java"

Edit: As Richard said, update-alternatives is not enough. You actually need to use update-java-alternatives. More info at:

https://help.ubuntu.com/community/Java

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Javascript change Div style

Better change the class of the element (.regular is black, .alert is red):

function abc(){
  var myDiv = document.getElementById("test");
  if (myDiv.className == 'alert') {
    myDiv.className = 'regular';
  } else {
    myDiv.className = 'alert';
  }
}

Deleting Elements in an Array if Element is a Certain value VBA

It's simple. I did it the following way to get a string with unique values (from two columns of an output sheet):

Dim startpoint, endpoint, ArrCount As Integer
Dim SentToArr() As String

'created by running the first part (check for new entries)
startpoint = ThisWorkbook.Sheets("temp").Range("A1").Value
'set counter on 0
Arrcount = 0 
'last filled row in BG
endpoint = ThisWorkbook.Sheets("BG").Range("G1047854").End(xlUp).Row

'create arr with all data - this could be any data you want!
With ThisWorkbook.Sheets("BG")
    For i = startpoint To endpoint
        ArrCount = ArrCount + 1
        ReDim Preserve SentToArr(1 To ArrCount)
        SentToArr(ArrCount) = .Range("A" & i).Value
        'get prep
        ArrCount = ArrCount + 1
        ReDim Preserve SentToArr(1 To ArrCount)
        SentToArr(ArrCount) = .Range("B" & i).Value
    Next i
End With

'iterate the arr and get a key (l) in each iteration
For l = LBound(SentToArr) To UBound(SentToArr)
    Key = SentToArr(l)
    'iterate one more time and compare the first key (l) with key (k)
    For k = LBound(SentToArr) To UBound(SentToArr)
        'if key = the new key from the second iteration and the position is different fill it as empty
        If Key = SentToArr(k) And Not k = l Then
            SentToArr(k) = ""
        End If
    Next k
Next l

'iterate through all 'unique-made' values, if the value of the pos is 
'empty, skip - you could also create a new array by using the following after the IF below - !! dont forget to reset [ArrCount] as well:
'ArrCount = ArrCount + 1
'ReDim Preserve SentToArr(1 To ArrCount)
'SentToArr(ArrCount) = SentToArr(h)

For h = LBound(SentToArr) To UBound(SentToArr)
    If SentToArr(h) = "" Then GoTo skipArrayPart
    GetEmailArray = GetEmailArray & "; " & SentToArr(h)
skipArrayPart:
Next h

'some clean up
If Left(GetEmailArray, 2) = "; " Then
    GetEmailArray = Right(GetEmailArray, Len(GetEmailArray) - 2)
End If

'show us the money
MsgBox GetEmailArray

How to get the unix timestamp in C#

Below is a 2-way extension class that supports:

  • Timezone localization
  • Input\output in seconds or milliseconds.

In OP's case, usage is:

DateTime.Now.ToUnixtime();

or

DateTime.UtcNow.ToUnixtime();

Even though a direct answer exists, I believe using a generic approach is better. Especially because it's most likely a project that needs a conversion like this, will also need these extensions anyway, so it's better to use the same tool for all.

    public static class UnixtimeExtensions
    {
        public static readonly DateTime UNIXTIME_ZERO_POINT = new DateTime(1970, 1, 1, 0, 0,0, DateTimeKind.Utc);

        /// <summary>
        /// Converts a Unix timestamp (UTC timezone by definition) into a DateTime object
        /// </summary>
        /// <param name="value">An input of Unix timestamp in seconds or milliseconds format</param>
        /// <param name="localize">should output be localized or remain in UTC timezone?</param>
        /// <param name="isInMilliseconds">Is input in milliseconds or seconds?</param>
        /// <returns></returns>
        public static DateTime FromUnixtime(this long value, bool localize = false, bool isInMilliseconds = true)
        {
            DateTime result;

            if (isInMilliseconds)
            {
                result = UNIXTIME_ZERO_POINT.AddMilliseconds(value);
            }
            else
            {
                result = UNIXTIME_ZERO_POINT.AddSeconds(value);
            }

            if (localize)
                return result.ToLocalTime();
            else
                return result;
        }

        /// <summary>
        /// Converts a DateTime object into a Unix time stamp
        /// </summary>
        /// <param name="value">any DateTime object as input</param>
        /// <param name="isInMilliseconds">Should output be in milliseconds or seconds?</param>
        /// <returns></returns>
        public static long ToUnixtime(this DateTime value, bool isInMilliseconds = true)
        {
            if (isInMilliseconds)
            {
                return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalMilliseconds;
            }
            else
            {
                return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalSeconds;
            }
        }
    }

How can I mark a foreign key constraint using Hibernate annotations?

There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.

The following works for a non-primary key mapping as well.

Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:

@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;

Enter image description here

@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;

Multiple parameters in a List. How to create without a class?

If appropriate, you might use a Dictionary which is also a generic collection:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How can I define colors as variables in CSS?

If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.

colors.xml:

<?xml version="1.0"?>
<colors>
    <background>#ccc</background>
</colors>

styles.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
    <xsl:template match="/">body {
    background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>

Command to render css: xsltproc -o styles.css styles.xsl colors.xml

styles.css:

body {
    background-color: #ccc;
}

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

How to make the background image to fit into the whole page without repeating using plain css?

You can't resize background images with CSS2.

What you can do is have a container that resizes:

<div style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
  <img src='whatever.jpg' style='width:100%;height:100%' alt='[]' />
</div>

This way, the div will sit behind the page and take up the whole space, while resizing as needed. The img inside will automatically resize to fit the div.

Letsencrypt add domain to existing certificate

This is how i registered my domain:

sudo letsencrypt --apache -d mydomain.com

Then it was possible to use the same command with additional domains and follow the instructions:

sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com

Fixed position but relative to container

My project is .NET ASP Core 2 MVC Angular 4 template with Bootstrap 4. Adding "sticky-top" into main app component html (i.e. app.component.html) on the first row worked, as follows:

_x000D_
_x000D_
<div class='row sticky-top'>_x000D_
    <div class='col-sm-12'>_x000D_
        <nav-menu-top></nav-menu-top>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="row">_x000D_
    <div class='col-sm-3'>_x000D_
        <nav-menu></nav-menu>_x000D_
    </div>_x000D_
    <div class='col-sm-9 body-content'>_x000D_
        <router-outlet></router-outlet>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is that the convention or did I oversimplify this?

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

How to add column to numpy array

It can be done like this:

import numpy as np

# create a random matrix:
A = np.random.normal(size=(5,2))

# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))

In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.

vb.net get file names in directory?

Try this:

Dim text As String = ""
Dim files() As String = IO.Directory.GetFiles(sFolder)

For Each sFile As String In files
    text &= IO.File.ReadAllText(sFile)
Next

check the null terminating character in char*

The null character is '\0', not '/0'.

while (*(forward++) != '\0')

How to convert an IPv4 address into a integer in C#?

    public static Int32 getLongIPAddress(string ipAddress)
    {
        return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0));
    }

The above example would be the way I go.. Only thing you might have to do is convert to a UInt32 for display purposes, or string purposes including using it as a long address in string form.

Which is what is needed when using the IPAddress.Parse(String) function. Sigh.

How can I check if a command exists in a shell script?

Five ways, 4 for bash and 1 addition for zsh:

  • type foobar &> /dev/null
  • hash foobar &> /dev/null
  • command -v foobar &> /dev/null
  • which foobar &> /dev/null
  • (( $+commands[foobar] )) (zsh only)

You can put any of them to your if clause. According to my tests (https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/), the 1st and 3rd method are recommended in bash and the 5th method is recommended in zsh in terms of speed.

How can I set up an editor to work with Git on Windows?

I've had difficulty getting Git to cooperate with WordPad, Komodo Edit and pretty much every other editor I give it. Most open for editing, but Git clearly doesn't wait for the save/close to happen.

As a crutch, I've just been doing i.e.

git commit -m "Fixed the LoadAll method"

to keep things moving. It tends to keep my commit messages a little shorter than they probably should be, but clearly there's some work to be done on the Windows version of Git.

The GitGUI also isn't that bad. It takes a little bit of orientation, but after that, it works fairly well.

How do I clone a single branch in Git?

Let us take the example of flask repo. It has 3 branches in addition to master. Let us checkout the 1.1.x remote branch

clone the git repo

git clone https://github.com/pallets/flask

cd into the repo.

cd flask

fetch remote branch 1.1.x

git fetch origin 1.1.x

checkout the branch

git checkout 1.1.x

You will switch to the branch 1.1.x and it will track the remote 1.1.x branch.

Finding Number of Cores in Java

This is an additional way to find out the number of CPU cores (and a lot of other information), but this code requires an additional dependence:

Native Operating System and Hardware Information https://github.com/oshi/oshi

SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();

Get the number of logical CPUs available for processing:

centralProcessor.getLogicalProcessorCount();

How, in general, does Node.js handle 10,000 concurrent requests?

Single Threaded Event Loop Model Processing Steps:

  • Clients Send request to Web Server.

  • Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.

  • Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.

  • Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.

  • Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.

  • Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.

  • If yes, then pick up one Client Request from Event Queue

    1. Starts process that Client Request
    2. If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
    3. If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
  • Checks Threads availability from Internal Thread Pool
  • Picks up one Thread and assign this Client Request to that thread.
  • That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop

    very nicely explained by @Rambabu Posa for more explanation go throw this Link

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

How to do the equivalent of pass by reference for primitives in Java

You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.

In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,

From faq.perl.org[perlfaq7]

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

How to exclude records with certain values in sql select

One way:

SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
    SELECT * FROM StoreClients sc2 
    WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.

Start an activity from a fragment

You should use getActivity() to launch activities from fragments

Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);

Also, you should be naming classes with caps: MFragmentActivity instead of mFragmentActivity.

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

mysql datatype for telephone number and address

Store them as two fields for phone numbers - a "number" and a "mask" as TinyText types which do not need more than 255 items.

Before we store the files we parse the phone number to get the formatting that has been used and that creates the mask, we then store the number a digits only e.g.

Input: (0123) 456 7890
Number: 01234567890
Mask: (nnnn)_nnn_nnnn

Theoretically this allows us to perform comparison searches on the Number field such as getting all phone numbers that begin with a specific area code, without having to worry how it was input by the users

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

Remove numbers from string sql server

Not tested, but you can do something like this:

Create Function dbo.AlphasOnly(@s as varchar(max)) Returns varchar(max) As
Begin
  Declare @Pos int = 1
  Declare @Ret varchar(max) = null
  If @s Is Not Null
  Begin
    Set @Ret = ''
    While @Pos <= Len(@s)
    Begin
      If SubString(@s, @Pos, 1) Like '[A-Za-z]'
      Begin
        Set @Ret = @Ret + SubString(@s, @Pos, 1)
      End
      Set @Pos = @Pos + 1
    End
  End
  Return @Ret
End

The key is to use this as a computed column and index it. It doesn't really matter how fast you make this function if the database has to execute it against every row in your large table every time you run the query.

CSS3 selector to find the 2nd div of the same class

UPDATE: This answer was originally written in 2008 when nth-of-type support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2), unless you have to support IE8 and older.


Original answer from 2008 follows (Note that I would not recommend this anymore!):

If you can use Prototype JS you can use this code to set some style values, or add another classname:

// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });
// OR add class name:
$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...

(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)

But if you're generating the html serverside you might just as well add an extra class on the second item...

Reactjs convert html string to jsx

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Getting first and last day of the current month

string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

CSS to stop text wrapping under image

Very simple answer for this problem that seems to catch a lot of people:

<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>

    img {
        float: left;
    }
    p {
        overflow: hidden;
    }

See example: http://jsfiddle.net/vandigroup/upKGe/132/

How do I use installed packages in PyCharm?

Adding a Path

Go into File ? Settings ? Project Settings ? Project Interpreter.

Then press configure interpreter, and navigate to the "Paths" tab.

pycharm path tab

Press the + button in the Paths area. You can put the path to the module you'd like it to recognize.

But I don't know the path..

Open the python interpreter where you can import the module.

>> import gnuradio
>> gnuradio.__file__
"path/to/gnuradio"

Most commonly you'll have a folder structure like this:

foobarbaz/
  gnuradio/
    __init__.py
    other_file.py

You want to add foobarbaz to the path here.

The type or namespace name could not be found

I had the same issue. The target frameworks were fine for me. Still it was not working. I installed VS2010 sp1, and did a "Rebuild" on the PrjTest. Then it started working for me.

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

Replace comma with newline in sed on MacOS?

Use an ANSI-C quoted string $'string'

You need a backslash-escaped literal newline to get to sed. In bash at least, $'' strings will replace \n with a real newline, but then you have to double the backslash that sed will see to escape the newline, e.g.

echo "a,b" | sed -e $'s/,/\\\n/g'

Note this will not work on all shells, but will work on the most common ones.

How to compile c# in Microsoft's new Visual Studio Code?

SHIFT+CTRL+B should work

However sometimes an issue can happen in a locked down non-adminstrator evironment:

If you open an existing C# application from the folder you should have a .sln (solution file) etc..

Commonly you can get these message in VS Code

Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!

Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'

Finished
Failed to spawn 'dotnet --info'  //this is a possible issue

To which then you will be asked to install .NET CLI tools

If impossible to get SDK installed with no admin privilege - then use other solution.

How to Detect Browser Back Button event - Cross Browser

Correct answer is already there to answer the question. I want to mention new JavaScript API PerformanceNavigationTiming, it's replacing deprecated performance.navigation.

Following code will log in console "back_forward" if user landed on your page using back or forward button. Take a look at compatibility table before using it in your project.

var perfEntries = performance.getEntriesByType("navigation");
for (var i = 0; i < perfEntries.length; i++) {
    console.log(perfEntries[i].type);
}

Difference between Dictionary and Hashtable

Want to add a difference:

Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.

e.g.

       //No strict type declaration
        Hashtable hash = new Hashtable();
        hash.Add(1, "One");
        hash.Add(2, "Two");
        hash.Add(3, "Three");
        hash.Add(4, "Four");
        hash.Add(5, "Five"); 
        hash.Add(6, "Six");
        hash.Add(7, "Seven");
        hash.Add(8, "Eight");
        hash.Add(9, "Nine");
        hash.Add("Ten", 10);// No error as no strict type

        for(int i=0;i<=hash.Count;i++)//=>No error for index 0
        {
            //Can be accessed through indexers
            Console.WriteLine(hash[i]);
        }
        Console.WriteLine(hash["Ten"]);//=> No error in Has Table

here no error for key 0 & also for key "ten"(note: t is small)

//Strict type declaration
        Dictionary<int,string> dictionary= new Dictionary<int, string>();
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");
        dictionary.Add(4, "Four");
        dictionary.Add(5, "Five");
        dictionary.Add(6, "Six");
        dictionary.Add(7, "Seven");
        dictionary.Add(8, "Eight");
        dictionary.Add(9, "Nine");
        //dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added

        //for i=0, key doesn't  exist error
        for (int i = 1; i <= dictionary.Count; i++)
        {
            //Can be accessed through indexers
            Console.WriteLine(dictionary[i]);
        }
        //Error : The given key was not present in the dictionary.
        //Console.WriteLine(dictionary[10]);

here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

I believe the get() function immediately runs the select query and does not accept ORDER BY conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:

$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get(); 
return $query->result();

CodeIgniter Documentation order_by()

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

What is Node.js?

Q: The programming model is event driven, especially the way it handles I/O.

Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).

Q: It uses JavaScript and the parser is V8.

Yes

Q: It can be easily used to create concurrent server applications.

Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as http://www.easynodejs.com/ - which comes with full online documentation and a sample application.

How to edit/save a file through Ubuntu Terminal

Open the file using vi or nano. and then press " i " ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

how to dynamically add options to an existing select in vanilla javascript

Use the document.createElement function and then add it as a child of your select.

var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);

Should I add the Visual Studio .suo and .user files to source control?

Using Rational ClearCase the answer is no. Only the .sln & .*proj should be registered in source code control.

I can't answer for other vendors. If I recall correctly, these files are "user" specific options, your environment.

Bootstrap alert in a fixed floating div at the top of page

Just wrap your inner message inside a div on which you apply your padding : http://jsfiddle.net/Ez9C4/

<div id="message">
    <div style="padding: 5px;">
        <div id="inner-message" class="alert alert-error">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            test error message
        </div>
    </div>
</div>

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

How to turn off INFO logging in Spark?

This below code snippet for scala users :

Option 1 :

Below snippet you can add at the file level

import org.apache.log4j.{Level, Logger}
Logger.getLogger("org").setLevel(Level.WARN)

Option 2 :

Note : which will be applicable for all the application which is using spark session.

import org.apache.spark.sql.SparkSession

  private[this] implicit val spark = SparkSession.builder().master("local[*]").getOrCreate()

spark.sparkContext.setLogLevel("WARN")

Option 3 :

Note : This configuration should be added to your log4j.properties.. (could be like /etc/spark/conf/log4j.properties (where the spark installation is there) or your project folder level log4j.properties) since you are changing at module level. This will be applicable for all the application.

log4j.rootCategory=ERROR, console

IMHO, Option 1 is wise way since it can be switched off at file level.

make: Nothing to be done for `all'

When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.

If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.

If they are not present, make blindly builds everything under the rule.

Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!

How do I use popover from Twitter Bootstrap to display an image?

Very simple :)

<a href="#" id="blob" class="btn large primary" rel="popover">hover for popover</a>

var img = '<img src="https://si0.twimg.com/a/1339639284/images/three_circles/twitter-bird-white-on-blue.png" />';

$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });

http://jsfiddle.net/weuWk/

Invalid syntax when using "print"?

The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")

check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print

Bootstrap Modal Backdrop Remaining

Workaround is to hide the backdrop entirely if you don't need one like this: data-backdrop=""

<div class="modal fade preview-modal" data-backdrop="" id="preview-modal"  role="dialog" aria-labelledby="preview-modal" aria-hidden="true">

Convert decimal to binary in python

You can also use a function from the numpy module

from numpy import binary_repr

which can also handle leading zeros:

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.

Returning JSON object as response in Spring Boot

you can also use a hashmap for this

@GetMapping
public HashMap<String, Object> get() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", somePOJO);
    return map;
}

Removing the password from a VBA project

I found another way to solve this one to avoid password of VBA Project,with out loosing excel password.

use Hex-editor XVI32 for the process

if the file type is XLSM files:

  1. Open the XLSM file with 7-Zip (right click -> 7-Zip -> Open archive).
  2. Copy the xl/vbaProject.bin file out of the file (you can drag and drop from 7-Zip), don't close 7-Zip
  3. Open the vbaProject.bin file with HexEdit
  4. Search for "DPB=" and replace it with "DPx="
  5. Save the file
  6. Copy this file back into 7-Zip (again, drag and drop works)
  7. Open the XLSX file in Excel, if prompted to "Continue Loading Project", click Yes. If prompted with errors, click OK.
  8. Press Alt+ F11 to open the VBA editor.
  9. While press it will show error “Unexpected error (40230)”, just click OK (6 or 7 times) until it goes away.
  10. Then it will open Automatically

Excel - Combine multiple columns into one column

I created an example spreadsheet here of how to do this with simple Excel formulae, and without use of macros (you will need to make your own adjustments for getting rid of the first row, but this should be easy once you figure out how my example spreadsheet works):

https://docs.google.com/a/umich.edu/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c#gid=0

To get total number of columns in a table in sql

In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):

DECLARE @colCount1 INT;
DECLARE @colCount2 INT;

SELECT @colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
SELECT @colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';

IF (@colCount1 != @colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;

The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA (which is a schema, like dbo). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

How to export collection to CSV in MongoDB?

Solution for MongoDB Atlas users!

Add the --fields parameter as comma separated field names enclosed in double inverted quotes:

--fields "<FIELD 1>,<FIELD 2>..."

This is complete example:

mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."

Could not resolve this reference. Could not locate the assembly

Check if your project files are read-only. Remove the read-only property by right clicking on the project folder and select properties. In the properties screen remove the read-only checkbox. I came across the same problem, and this solved it for me.

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

Pls note: We may use break statements which are used to break/exit only from a loop, and not the entire program.

To exit from program: System.exit() Method:
System.exit has status code, which tells about the termination, such as:
exit(0) : Indicates successful termination.
exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.

How to view the list of compile errors in IntelliJ?

I think this comes closest to what you wish:

(From IntelliJ IDEA Q&A for Eclipse Users):

enter image description here

The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.

Things to do:

  1. Switch to 'Problems' view in the Project pane:

    enter image description here

  2. Enable the setting to compile the project automatically :

    enter image description here

  3. Finally, look at the Problems view:

    enter image description here

Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:

enter image description here

enter image description here

Relevant Links: The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122

VS 2017 Git Local Commit DB.lock error on every commit

enter image description here

For me these two files I have deleted by mistake, after undo these two files and get added in my changes, I was able to commit my changes to git.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I have found that when you are forced to use the Configuration Manager to run under x86 or anything other than the standard project "out of the box" settings, the IDE creates a bunch of sub directories under the bin folder for the web project.

Once this starts happening, if the Cassini server is running, then the project does not serve properly.

I fixed it by going into the Web Project properties -> Build settings and changing the Output Path to be bin\

Then rebuild and all works as it should.

How to format a phone number with jQuery

I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.

Problem

I would like my phone number html input field to auto-format (mask) the value as the user types.

Solution

Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.

Formatting a phone number is as easy as:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

How do you get the index of the current iteration of a foreach loop?

This way you can use the index and value using LINQ:

ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>
    {
        // element.Index
        // element.Value

    });

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

Clear git local cache

git rm --cached *.FileExtension

This must ignore all files from this extension

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

Compiling C++11 with g++

You can check your g++ by command:

which g++
g++ --version

this will tell you which complier is currently it is pointing.

To switch to g++ 4.7 (assuming that you have installed it in your machine),run:

sudo update-alternatives --config gcc

There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path              Priority   Status
------------------------------------------------------------
  0            /usr/bin/gcc-4.6   60        auto mode
  1            /usr/bin/gcc-4.6   60        manual mode
* 2            /usr/bin/gcc-4.7   40        manual mode

Then select 2 as selection(My machine already pointing to g++ 4.7,so the *)

Once you switch the complier then again run g++ --version to check the switching has happened correctly.

Now compile your program with

g++ -std=c++11 your_file.cpp -o main

Splitting dataframe into multiple dataframes

You can convert groupby object to tuples and then to dict:

df = pd.DataFrame({'Name':list('aabbef'),
                   'A':[4,5,4,5,5,4],
                   'B':[7,8,9,4,2,3],
                   'C':[1,3,5,7,1,0]}, columns = ['Name','A','B','C'])

print (df)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3
2    b  4  9  5
3    b  5  4  7
4    e  5  2  1
5    f  4  3  0

d = dict(tuple(df.groupby('Name')))
print (d)
{'b':   Name  A  B  C
2    b  4  9  5
3    b  5  4  7, 'e':   Name  A  B  C
4    e  5  2  1, 'a':   Name  A  B  C
0    a  4  7  1
1    a  5  8  3, 'f':   Name  A  B  C
5    f  4  3  0}

print (d['a'])
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

It is not recommended, but possible create DataFrames by groups:

for i, g in df.groupby('Name'):
    globals()['df_' + str(i)] =  g

print (df_a)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!

Save plot to image file instead of displaying it using Matplotlib

As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don't have a million open figures during the loop:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).

"Missing return statement" within if / for / while

Any how myMethod() should return a String value .what if your condition is false is myMethod return anything? ans is no so you need to define return null or some string value in false condition

public String myMethod() {
    boolean c=true;
    if (conditions) {
        return "d";
    }
    return null;//or some other string value
}

How to get the instance id from within an ec2 instance?

For C++ (using cURL):

    #include <curl/curl.h>

    //// cURL to string
    size_t curl_to_str(void *contents, size_t size, size_t nmemb, void *userp) {
        ((std::string*)userp)->append((char*)contents, size * nmemb);
        return size * nmemb;
    };

    //// Read Instance-id 
    curl_global_init(CURL_GLOBAL_ALL); // Initialize cURL
    CURL *curl; // cURL handler
    CURLcode res_code; // Result
    string response;
    curl = curl_easy_init(); // Initialize handler
    curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-id");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_str);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    res_code = curl_easy_perform(curl); // Perform cURL
    if (res_code != CURLE_OK) { }; // Error
    curl_easy_cleanup(curl); // Cleanup handler
    curl_global_cleanup(); // Cleanup cURL

Decimal or numeric values in regular expression validation

I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:

function isNumber(v) {
  // [0-9]* Zero or more digits between 0 and 9  (This allows .25 to be considered valid.)
  // ()? Matches 0 or 1 things in the parentheses.  (Allows for an optional decimal point)
  // Decimal point escaped with \.
  // If a decimal point does exist, it must be followed by 1 or more digits [0-9]
  // \d and [0-9] are equivalent 
  // ^ and $ anchor the endpoints so tthe whole string must match.
  return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}

Where my trim() method is

String.prototype.trim = function() {
  return this.replace(/(^\s*|\s*$)/g, "");
};

Matthew DesVoigne

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

The solution is running this command:

set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg   

or

set OPENSSL_CONF=[path-to-OpenSSL-install-dir]\bin\openssl.cfg

in the command prompt before using openssl command.

Let openssl know for sure where to find its .cfg file.

Alternatively you could set the same variable OPENSSL_CONF in the Windows environment variables.

NOTE: This can happen when using the OpenSSL binary distribution from Shining Light Productions (a compiled + installer version of the official OpenSSL that is free to download & use). This distribution is "semi-officially" linked from OpenSSL's site as a "service primarily for operating systems where there are no pre-compiled OpenSSL packages".

Why don't self-closing script elements work?

Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml. If you're serving XHTML as text/html, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.

The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.

IE9 and later support XHTML 5 served with application/xhtml+xml.

How to check list A contains any value from list B?

I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.

    public static bool Contain<T>(List<T> a, List<T> b)
    {
        if (a.Count <= 10 && b.Count <= 10)
        {
            return a.Any(b.Contains);
        }

        if (a.Count > b.Count)
        {
            return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
        }
        return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
    }

    public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
    {
        HashSet<T> j = new HashSet<T>(a);
        return b.Any(j.Contains);
    }

The Intersect calls Set that have not check the second size and this is the Intersect's code.

        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in second) set.Add(element);
        foreach (TSource element in first)
            if (set.Remove(element)) yield return element;

The difference in two methods is my method use HashSet and check the count and Intersect use set that is faster than HashSet. We dont warry its performance.

The test :

   static void Main(string[] args)
    {
        var a = Enumerable.Range(0, 100000);
        var b = Enumerable.Range(10000000, 1000);
        var t = new Stopwatch();
        t.Start();
        Repeat(()=> { Contain(a, b); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//490ms

        var a1 = Enumerable.Range(0, 100000).ToList();
        var a2 = b.ToList();
        t.Restart();
        Repeat(()=> { Contain(a1, a2); });
        t.Stop();

        Console.WriteLine(t.ElapsedMilliseconds);//203ms

        t.Restart();
        Repeat(()=>{ a.Intersect(b).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//190ms

        t.Restart();
        Repeat(()=>{ b.Intersect(a).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//497ms

        t.Restart();
        a.Any(b.Contains);
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//600ms

    }

    private static void Repeat(Action a)
    {
        for (int i = 0; i < 100; i++)
        {
            a();
        }
    }

What does MissingManifestResourceException mean and how to fix it?

Also the same error may occur when you put a new class into the source code of a designer created form's class.

This new class may be removed, and placed in a different cs file.

(At least in my case this was the problem...)

Simple check for SELECT query empty result

You can do it in a number of ways.

IF EXISTS(select * from ....)
begin
 -- select * from .... 
end
else
 -- do something 

Or you can use IF NOT EXISTS , @@ROW_COUNT like

select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end

Row count on the Filtered data

While I agree with the results given, they didn't work for me. If your Table has a name this will work:

Public Sub GetCountOfResults(WorkSheetName As String, TableName As String)
    Dim rnData As Range
    Dim rngArea As Range
    Dim lCount As Long
        Set rnData = ThisWorkbook.Worksheets(WorkSheetName).ListObjects(TableName).Range
    With rnData
        For Each rngArea In .SpecialCells(xlCellTypeVisible).Areas
            lCount = lCount + rngArea.Rows.Count
        Next
        MsgBox "Autofilter " & lCount - 1 & " records"
    End With
    Set rnData = Nothing
    lCount = Empty      
End Sub

This is modified to work with ListObjects from an original version I found here:

http://www.ozgrid.com/forum/showthread.php?t=81858

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

How to check if mysql database exists

Here's my way of doing it inside a bash script:

#!/bin/sh

DATABASE_USER=*****
DATABASE_PWD=*****
DATABASE_NAME=my_database

if mysql -u$DATABASE_USER -p$DATABASE_PWD -e "use $DATABASE_NAME";
then
echo "Database $DATABASE_NAME already exists. Exiting."
exit
else
echo Create database
mysql -u$DATABASE_USER -p$DATABASE_PWD -e "CREATE DATABASE $DATABASE_NAME"
fi

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

How to download a file from my server using SSH (using PuTTY on Windows)

You can use the WinSPC program. Its access to any server is pretty easy. The program gives its guide too. I hope it's helpfull.

How to avoid the "divide by zero" error in SQL?

  1. Add a CHECK constraint that forces Divisor to be non-zero
  2. Add a validator to the form so that the user cannot enter zero values into this field.

Add 10 seconds to a Date

The Date() object in javascript is not that smart really.

If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date object you end up in trouble. So I simply fell back to only using the setSeconds() method and converting my data into seconds (which worked fine).

If anyone can demonstrate adding time to a global Date() object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date() object and mixing them leads to a mess.

var vTime = new Date();

var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );

vTime.setSeconds(iSecondsToAdd);

Here is some more documentation that may help:

Python check if list items are integers?

You can use exceptional handling as str.digit will only work for integers and can fail for something like this too:

>>> str.isdigit(' 1')
False

Using a generator function:

def solve(lis):                                        
    for x in lis:
        try:
            yield float(x)
        except ValueError:    
            pass

>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))                                    
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values

or may be you wanted this:

def solve(lis):
    for x in lis:
        try:
            float(x)
            return True
        except:
            return False
...         
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']

or using ast.literal_eval, this will work for all types of numbers:

>>> from ast import literal_eval
>>> def solve(lis):
    for x in lis:
        try:
            literal_eval(x)
            return True
        except ValueError:   
             return False
...         
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]                               
['1', '2', '3', '4', '1.5', '2.6', '1+0j']

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

Where is the Microsoft.IdentityModel dll

For Windows 10:

Right-click the taskbar Windows logo, select 'Programs and Features'.

Click 'Turn Windows Features on or off'

In the dialog box that appears, scroll down or resize the window and check the box next to 'Windows Identity Foundation 3.5'

Click OK.

This activates the required DLLs. Apparently Windows 10 keeps all of those features in the windows installation so that it can activate and deactivate them on demand.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

Import existing Gradle Git project into Eclipse

I use another Eclipse plugin to import existing gradle projects.

You can install the Builship Gradle Gntegration 2.0 using the Eclipse Marketplace client.

Then you choose FIle ? Import ? Existing Gradle Project.

Finially, indicate your project root directory and click finish.

Hidden Features of Java

Use StringBuilder instead of StringBuffer when you don't need synchronized management included in StringBuilder. It will increase the performance of your application.

Improvements for Java 7 would be even better than any hidden Java features:

  • Diamond syntax: Link

Don't use those infinite <> syntax at instanciation:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();
  • Strings in switch: Link

Use String in switch, instead of old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}
  • Automatic Resource Management Link

This old code:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

can now be replaced by this much simpler code:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

Stopping a JavaScript function when a certain condition is met

if(condition){
    // do something
       return false;

}

How to use radio buttons in ReactJS?

Clicking a radio button should trigger an event that either:

  1. calls setState, if you only want the selection knowledge to be local, or
  2. calls a callback that has been passed in from above self.props.selectionChanged(...)

In the first case, the change is state will trigger a re-render and you can do
<td>chosen site name {this.state.chosenSiteName} </td>

in the second case, the source of the callback will update things to ensure that down the line, your SearchResult instance will have chosenSiteName and chosenAddress set in it's props.

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

Spring Boot - How to get the running port

After Spring Boot 2, a lot has changed. The above given answers work prior to Spring Boot 2. Now if you are running your application with runtime arguments for the server port, then you will only get the static value with @Value("${server.port}"), that is mentioned in the application.properties file. Now to get the actual port in which the server is running, use the following method:

    @Autowired
    private ServletWebServerApplicationContext server;

    @GetMapping("/server-port")
    public String serverPort() {

        return "" + server.getWebServer().getPort();
    }

Also, if you are using your applications as Eureka/Discovery Clients with load balanced RestTemplate or WebClient, the above method will return the exact port number.

Javascript to sort contents of select element

Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript.

The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)