Programs & Examples On #Wordperfect

Regular expression search replace in Sublime Text 2

By the way, in the question above:

For:

Hello, my name is bob

Find part:

my name is (\w)+

With replace part:

my name used to be \1

Would return:

Hello, my name used to be b

Change find part to:

my name is (\w+)

And replace will be what you expect:

Hello, my name used to be bob

While (\w)+ will match "bob", it is not the grouping you want for replacement.

Remove characters after specific character in string, then remove substring?

Request.QueryString helps you to get the parameters and values included within the URL

example

string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();

so the customername variable should be equal to dave

regards

How to Install pip for python 3.7 on Ubuntu 18?

I installed pip3 using

python3.7 -m pip install pip

But upon using pip3 to install other dependencies, it was using python3.6.
You can check the by typing pip3 --version

Hence, I used pip3 like this (stated in one of the above answers):

python3.7 -m pip install <module>

or use it like this:

python3.7 -m pip install -r requirements.txt

I made a bash alias for later use in ~/.bashrc file as alias pip3='python3.7 -m pip'. If you use alias, don't forget to source ~/.bashrc after making the changes and saving it.

String.Replace ignoring case

Extensions make our lives easier:

static public class StringExtensions
{
    static public string ReplaceInsensitive(this string str, string from, string to)
    {
        str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
        return str;
    }
}

Jaxb, Class has two properties of the same name

I did trial and error and got the conclusion that, you only have to use either of both @XMLElement or @XmlAccessorType(XmlAccessType.FIELD).

When to use which?

case 1 : If your field names and element name you want to use in xml file are different then you have to use @XMLElement(name="elementName"). As this will bind fields with that element name and display in XML file.

case 2 : If fields names and respective element name in xml both are same then you can simply use @XmlAccessorType(XmlAccessType.FIELD)

DLL and LIB files - what and why?

One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

Find closest previous element jQuery

var link = $("#me").closest(":has(h3 span b)").find('h3 span b');

Example: http://jsfiddle.net/e27r8/

This uses the closest()[docs] method to get the first ancestor that has a nested h3 span b, then does a .find().

Of course you could have multiple matches.


Otherwise, you're looking at doing a more direct traversal.

var link = $("#me").closest("h3 + div").prev().find('span b');

edit: This one works with your updated HTML.

Example: http://jsfiddle.net/e27r8/2/


EDIT: Updated to deal with updated question.

var link = $("#me").closest("h3 + *").prev().find('span b');

This makes the targeted element for .closest() generic, so that even if there is no parent, it will still work.

Example: http://jsfiddle.net/e27r8/4/

What is the PostgreSQL equivalent for ISNULL()

Try:

SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name

How to verify a Text present in the loaded page through WebDriver

Driver.getPageSource() is a bad way to verify text present. Suppose you say, driver.getPageSource().contains("input"); That doesn't verify "input" is present on the screen, only that "input" is present in the html, like an input tag.

I usually verify text on an element by using xpath:

boolean textFound = false;  
try {
    driver.findElement(By.xpath("//*[contains(text(),'someText')]"));
    textFound = true;
} catch (Exception e) {
    textFound = false;
}

If you want an exact text match, just remove the contains function:

driver.findElement(By.xpath("//*[text()='someText']));

Insert/Update Many to Many Entity Framework . How do I do it?

I use the following way to handle the many-to-many relationship where only foreign keys are involved.

So for inserting:

public void InsertStudentClass (long studentId, long classId)
{
    using (var context = new DatabaseContext())
    {
        Student student = new Student { StudentID = studentId };
        context.Students.Add(student);
        context.Students.Attach(student);

        Class class = new Class { ClassID = classId };
        context.Classes.Add(class);
        context.Classes.Attach(class);

        student.Classes = new List<Class>();
        student.Classes.Add(class);

        context.SaveChanges();
    }
}

For deleting,

public void DeleteStudentClass(long studentId, long classId)
{
    Student student = context.Students.Include(x => x.Classes).Single(x => x.StudentID == studentId);

    using (var context = new DatabaseContext())
    {
        context.Students.Attach(student);
        Class classToDelete = student.Classes.Find(x => x.ClassID == classId);
        if (classToDelete != null)
        {
            student.Classes.Remove(classToDelete);
            context.SaveChanges();
        }
    }
}

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

What is a "callback" in C and how are they implemented?

Usually this can be done by using a function pointer, that is a special variable that points to the memory location of a function. You can then use this to call the function with specific arguments. So there will probably be a function that sets the callback function. This will accept a function pointer and then store that address somewhere where it can be used. After that when the specified event is triggered, it will call that function.

rails generate model

The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.

The normal way to get there from scratch is:

$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
    name:string \ 
    description:text \
    price:decimal \
    seller_id:integer \
    email:string img_url:string

MongoDB and "joins"

If you use mongoose, you can just use(assuming you're using subdocuments and population):

Profile.findById profileId
  .select 'friends'
  .exec (err, profile) ->
    if err or not profile
      handleError err, profile, res
    else
      Status.find { profile: { $in: profile.friends } }, (err, statuses) ->
        if err
          handleErr err, statuses, res
        else
          res.json createJSON statuses

It retrieves Statuses which belong to one of Profile (profileId) friends. Friends is array of references to other Profiles. Profile schema with friends defined:

schema = new mongoose.Schema
  # ...

  friends: [
    type: mongoose.Schema.Types.ObjectId
    ref: 'Profile'
    unique: true
    index: true
  ]

How to convert string to double with proper cultureinfo

I have this function in my toolbelt since years ago (all the function and variable names are messy and mixing Spanish and English, sorry for that).

It lets the user use , and . to separate the decimals and will try to do the best if both symbols are used.

    Public Shared Function TryCDec(ByVal texto As String, Optional ByVal DefaultValue As Decimal = 0) As Decimal

        If String.IsNullOrEmpty(texto) Then
            Return DefaultValue
        End If

        Dim CurAsTexto As String = texto.Trim.Replace("$", "").Replace(" ", "")

        ''// You can probably use a more modern way to find out the
        ''// System current locale, this function was done long time ago
        Dim SepDecimal As String, SepMiles As String
        If CDbl("3,24") = 324 Then
            SepDecimal = "."
            SepMiles = ","
        Else
            SepDecimal = ","
            SepMiles = "."
        End If

        If InStr(CurAsTexto, SepDecimal) > 0 Then
            If InStr(CurAsTexto, SepMiles) > 0 Then
                ''//both symbols was used find out what was correct
                If InStr(CurAsTexto, SepDecimal) > InStr(CurAsTexto, SepMiles) Then
                    ''// The usage was correct, but get rid of thousand separator
                    CurAsTexto = Replace(CurAsTexto, SepMiles, "")
                Else
                    ''// The usage was incorrect, but get rid of decimal separator and then replace it
                    CurAsTexto = Replace(CurAsTexto, SepDecimal, "")
                    CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
                End If
            End If
        Else
            CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
        End If
        ''// At last we try to tryParse, just in case
        Dim retval As Decimal = DefaultValue
        Decimal.TryParse(CurAsTexto, retval)
        Return retval
    End Function

Pass a datetime from javascript to c# (Controller)

var Ihours = Math.floor(TotMin / 60);          

var Iminutes = TotMin % 60; var TotalTime = Ihours+":"+Iminutes+':00';

   $.ajax({
            url: ../..,
            cache: false,
            type: "POST",                
            data: JSON.stringify({objRoot: TotalTime}) ,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {

            },
            error: function (er) {
                console.log(er);
            }
        });

Rails DB Migration - How To Drop a Table?

Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end

How do I escape the wildcard/asterisk character in bash?

I'll add a bit to this old thread.

Usually you would use

$ echo "$FOO"

However, I've had problems even with this syntax. Consider the following script.

#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"

The * needs to be passed verbatim to curl, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*. You also can't quote $curl_opts because it will be recognized as a single (invalid) option to curl.

curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

Therefore I would recommend the use of the bash variable $GLOBIGNORE to prevent filename expansion altogether if applied to the global pattern, or use the set -f built-in flag.

#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"  ## no filename expansion

Applying to your original example:

me$ FOO="BAR * BAR"

me$ echo $FOO
BAR file1 file2 file3 file4 BAR

me$ set -f
me$ echo $FOO
BAR * BAR

me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR

displaying a string on the textview when clicking a button in android

This is because you DON'T associated the OnClickListener() on the button retrieve from the XML layout.

You don't need to create object because they are already created by the Android system when you inflate XML file (with the Activity.setContentLayout( int resourceLayoutId ) method).

Just retrieve them with the findViewById(...) method.

How do I convert a javascript object array to a string array of the object attribute I want?

Use the map() function native on JavaScript arrays:

var yourArray = [ {
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}];

var newArray = yourArray.map( function( el ){ 
                                return el.name; 
                               });

Sending cookies with postman

Chrome apps including Postman are being deprecated as mentioned here. Now the recommendation is to go for native apps which are not detached from the sandboxed environment of the browser.

Quoting from the feature page:

FEATURES EXCLUSIVE TO THE NATIVE APPS:

COOKIES: The native apps let you work with cookies directly. Unlike the Chrome app, no separate extension (Interceptor) is needed.

BUILT-IN PROXY: The native apps come with a built-in proxy that you can use to capture network traffic.

RESTRICTED HEADERS: The latest version of the native apps let you send headers like Origin and User-Agent. These are restricted in the Chrome app. DON'T FOLLOW

REDIRECTS OPTION: This option exists in the native apps to prevent requests that return a 300-series response from being automatically redirected. Previously, users needed to use the Interceptor extension to do this in the Chrome app.

MENU BAR: The native apps are not restricted by the Chrome standards for the menu bar.

POSTMAN CONSOLE: The latest version of the native apps has a built-in console, which allows you to view the network request details for API calls.

So once you install the native Postman app from here you don't have to go looking for additional prerequisites like interceptor app just to check your cookies. I didn't have to change a single setting after installing the native postman app and all my cookies were visible in Cookies tab as shown below:

enter image description here

Select all text inside EditText when it gets focus

Managed it by calling focus and selection on program

{
editabletext.requestFocus();
editabletext.selectAll();
}

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

Trying to get property of non-object MySQLi result

I have been working on to write a custom module in Drupal 7 and got the same error:

Notice: Trying to get property of non-object

My code is something like this:

function example_node_access($node, $op, $account) {
  if ($node->type == 'page' && $op == 'update') {
    drupal_set_message('This poll has been published, you may not make changes to it.','error');
    return NODE_ACCESS_DENY;    
  }
}

Solution: I just added a condition if (is_object($sqlResult)), and everything went fine.

Here is my final code:

function mediaten_node_access($node, $op, $account) {

    if (is_object($node)){

     if ($node->type == 'page' && $op == 'update') {
       drupal_set_message('This poll has been published, you may not make changes.','error');
       return NODE_ACCESS_DENY;    
      }

    }

}

jQuery append() vs appendChild()

append is a jQuery method to append some content or HTML to an element.

$('#example').append('Some text or HTML');

appendChild is a pure DOM method for adding a child element.

document.getElementById('example').appendChild(newElement);

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

  • validate: validates the schema, no change happens to the database.
  • update: updates the schema with current execute query.
  • create: creates new schema every time, and destroys previous data.
  • create-drop: drops the schema when the application is stopped or SessionFactory is closed explicitly.

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

Multiple variables in a 'with' statement?

Since Python 3.3, you can use the class ExitStack from the contextlib module.

It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.

The canonical use-case that is mentioned in the documentation is managing a dynamic number of files.

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

Here is a generic example:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(stack._exit_callbacks)
    nums = [stack.enter_context(x) for x in xs]
    print(stack._exit_callbacks)
print(stack._exit_callbacks)
print(nums)

Output:

deque([])
enter X1
enter X2
enter X3
deque([<function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86158>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f861e0>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86268>])
exit X3
exit X2
exit X1
deque([])
[1, 2, 3]

What to return if Spring MVC controller method doesn't return value?

you can return void, then you have to mark the method with @ResponseStatus(value = HttpStatus.OK) you don't need @ResponseBody

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

Only get methods return a 200 status code implicity, all others you have do one of three things:

  • Return void and mark the method with @ResponseStatus(value = HttpStatus.OK)
  • Return An object and mark it with @ResponseBody
  • Return an HttpEntity instance

How to add anchor tags dynamically to a div in Javascript?

here's a pure Javascript alternative:

var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);

How do I check if an element is really visible with JavaScript?

I don't think checking the element's own visibility and display properties is good enough for requirement #1, even if you use currentStyle/getComputedStyle. You also have to check the element's ancestors. If an ancestor is hidden, so is the element.

What is the difference between "is None" and "== None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

How to pass the password to su/sudo/ssh without overriding the TTY?

For ssh you can use sshpass: sshpass -p yourpassphrase ssh user@host.

You just need to download sshpass first :)

$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server

How to install the JDK on Ubuntu Linux

Note: WebUpd8 team's PPA has been discontinued with effective from April 16, 2019. Thus this PPA doesn't have any Java files. More information can be found on PPA's page on Launchpad. Hence the below method no longer works and exists because of historical reasons.

If you want to install the latest JDK 1.8, use the webupd8team PPA.

Add the repository in your system:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

You can now install Oracle Java 8 using the following command:

sudo apt-get install oracle-java8-installer

This ppa repository also provides a package to set environment variables automatically. Just type:

sudo apt-get install oracle-java8-set-default

How can I truncate a datetime in SQL Server?

This query should give you result equivalent to trunc(sysdate) in Oracle.

SELECT  * 
FROM    your_table
WHERE   CONVERT(varchar(12), your_column_name, 101)
      = CONVERT(varchar(12), GETDATE(), 101)

Hope this helps!

not-null property references a null or transient value

Every InvoiceItem must have an Invoice attached to it because of the not-null="true" in the many-to-one mapping.

So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems method. I do NOT see an addInvoiceItem method. When you set items, you need to loop through the set and call item.setInvoice(this) on all of the items. If you implement an addItem method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem in the collection.

What is the difference between visibility:hidden and display:none?

They are not synonyms.

display:none removes the element from the normal flow of the page, allowing other elements to fill in.

visibility:hidden leaves the element in the normal flow of the page such that is still occupies space.

Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like display:none.

Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like visibility:hidden.

Finding child element of parent pure javascript

Just adding another idea you could use a child selector to get immediate children

document.querySelectorAll(".parent > .child1");

should return all the immediate children with class .child1

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

Batch files: List all files in a directory with relative paths

This answer will not work correctly with root paths containing equal signs (=). (Thanks @dbenham for pointing that out.)


EDITED: Fixed the issue with paths containing !, again spotted by @dbenham (thanks!).

Alternatively to calculating the length and extracting substrings you could use a different approach:

  • store the root path;

  • clear the root path from the file paths.

Here's my attempt (which worked for me):

@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
  SET "p=%%F"
  SETLOCAL EnableDelayedExpansion
  ECHO(!p:%r%=!
  ENDLOCAL
)

The r variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \, which we amend by appending the character. (No longer the case, as the script now reads the __CD__ variable, whose value always ends with \ (thanks @jeb!), instead of CD.)

In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.

Storing money in a decimal column - what precision and scale?

A late answer here, but I've used

DECIMAL(13,2)

which I'm right in thinking should allow upto 99,999,999,999.99.

Non-Static method cannot be referenced from a static context with methods and variables

Merely for the purposes of making your program work, take the contents of your main() method and put them in a constructor:

public BookStoreApp2()
{
   // Put contents of main method here
}

Then, in your main() method. Do this:

public void main( String[] args )
{
  new BookStoreApp2();
}

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

Batch file to split .csv file

Try this out:

@echo off
setLocal EnableDelayedExpansion

set limit=20000
set file=export.csv
set lineCounter=1
set filenameCounter=1

set name=
set extension=
for %%a in (%file%) do (
    set "name=%%~na"
    set "extension=%%~xa"
)

for /f "tokens=*" %%a in (%file%) do (
    set splitFile=!name!-part!filenameCounter!!extension!
    if !lineCounter! gtr !limit! (
        set /a filenameCounter=!filenameCounter! + 1
        set lineCounter=1
        echo Created !splitFile!.
    )
    echo %%a>> !splitFile!

    set /a lineCounter=!lineCounter! + 1
)

As shown in the code above, it will split the original csv file into multiple csv file with a limit of 20 000 lines. All you have to do is to change the !file! and !limit! variable accordingly. Hope it helps.

Add a space (" ") after an element using :after

I needed this instead of using padding because I used inline-block containers to display a series of individual events in a workflow timeline. The last event in the timeline needed no arrow after it.

Ended up with something like:

.transaction-tile:after {
  content: "\f105";
}

.transaction-tile:last-child:after {
  content: "\00a0";
}

Used fontawesome for the gt (chevron) character. For whatever reason "content: none;" was producing alignment issues on the last tile.

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

MessageBox Buttons?

Check this:

                     if (
 MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //YES ---> Ok IM ALRIGHHT
                    }
                    else
                   {
                   //NO --->NO IM STUCK
                    }

Regards

How to get row count in sqlite using Android?

Once you get the cursor you can do

Cursor.getCount()

How do I implement JQuery.noConflict() ?

Today i have this issue because i have implemented "bootstrap menu" that uses a jQuery version along with "fancybox image gallery". Of course one plugin works and the other not due to jQuery conflict but i have overcome it as follow:

First i have added the "bootstrap menu" Js in the script footer as the menu is presented allover the website pages:

<!-- Top Menu Javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var jq171 = jQuery.noConflict(true);
</script>

And in the "fancybox" image gallery page as follow:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="fancybox/js/libs/jquery-1.7.1.min.js"><\/script>')</script>

And the good thing is both working like a charm :)

Give it a try :)

How to send and retrieve parameters using $state.go toParams and $stateParams?

And in my case of a parent/child state. all the parameters declared in child state has to be known by the parent state

        .state('full', {
            url: '/full',
            templateUrl: 'js/content/templates/FullReadView.html',
            params: { opmlFeed:null, source:null },
            controller: 'FullReadCtrl'
        })
        .state('full.readFeed', {
            url: '/readFeed',
            views: {
                'full': {
                    templateUrl: 'js/content/templates/ReadFeedView.html',
                    params: { opmlFeed:null, source:null },
                    controller: 'ReadFeedCtrl'
                }
            }
        })

scikit-learn random state in splitting dataset

when random_state set to an integer, train_test_split will return same results for each execution.

when random_state set to an None, train_test_split will return different results for each execution.

see below example:

from sklearn.model_selection import train_test_split

X_data = range(10)
y_data = range(10)

for i in range(5):
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = 0) # zero or any other integer
    print(y_test)

print("*"*30)

for i in range(5): 
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = None)
    print(y_test)

Output:

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]


[4, 7, 6]

[4, 3, 7]

[8, 1, 4]

[9, 5, 8]

[6, 4, 5]

Add new value to an existing array in JavaScript

Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.

There are number of different possibilities, so, use the one which mostly targets your needs.

Creating array with values:

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

Adding values to the end

var array = [];
array.push("value1");
array.push("value2");
array.push("value3");

Adding values to the begin:

var array = [];
array.unshift("value1");
array.unshift("value2");
array.unshift("value3");

Adding values at some index:

var array = [];
array[index] = "value1";

or by using splice

array.splice(index, 0, "value1", "value2", "value3");

Choose one you need.

How to draw a line in android

There are two main ways you can draw a line, by using a Canvas or by using a View.

Drawing a Line with Canvas

From the documentation we see that we need to use the following method:

drawLine (float startX, float startY, float stopX, float stopY, Paint paint)

Here is a picture:

canvas.drawLine

The Paint object just tells Canvas what color to paint the line, how wide it should be, and so on.

Here is some sample code:

private Paint paint = new Paint();
....

private void init() {
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(1f);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    startX = 20;
    startY = 100;
    stopX = 140;
    stopY = 30;

    canvas.drawLine(startX, startY, stopX, stopY, paint);
}

Drawing a Line with View

If you only need a straight horizontal or vertical line, then the easiest way may be to just use a View in your xml layout file. You would do something like this:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

Here is a picture with two lines (one horizontal and one vertical) to show what it would look like:

drawing a line with a view in xml layout

And here is the complete xml layout for that:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView1 in vertical linear layout" />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView2 in vertical linear layout" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView3 in horizontal linear layout" />

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@android:color/black" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView4 in horizontal linear layout" />
</LinearLayout>

</LinearLayout>

Remove HTML Tags from an NSString on the iPhone

Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

How to automatically start a service when running a docker container?

Here is how I automatically start the MySQL service whenever the docker container runs.

On my case, I need to run not just MySQL but also PHP, Nginx and Memcached

I have the following lines in Dockerfile

RUN echo "daemon off;" >> /etc/nginx/nginx.conf
EXPOSE 80
EXPOSE 3306
CMD service mysql start && service php-fpm start && nginx -g 'daemon off;' && service memcached start && bash

Adding && bash would keep Nginx, MySQL, PHP and Memcached running within the container.

How can I get the index from a JSON object with value?

In all previous solutions, you must know the name of the attribute or field. A more generic solution for any attribute is this:

let data = 
[{
    "name": "placeHolder",
    "section": "right"
}, {
    "name": "Overview",
    "section": "left"
}, {
    "name": "ByFunction",
    "section": "left"
}, {
    "name": "Time",
    "section": "left"
}, {
    "name": "allFit",
    "section": "left"
}, {
    "name": "allbMatches",
    "section": "left"
}, {
    "name": "allOffers",
    "section": "left"
}, {
    "name": "allInterests",
    "section": "left"
}, {
    "name": "allResponses",
    "section": "left"
}, {
    "name": "divChanged",
    "section": "right"
}]    

function findByKey(key, value) {
    return (item, i) => item[key] === value
}

let findParams = findByKey('name', 'allOffers')
let index = data.findIndex(findParams)

PHP: How to handle <![CDATA[ with SimpleXMLElement?

When to use LIBXML_NOCDATA ?

I add the issue when transforming XML to JSON.

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo json_encode($xml, true); 
/* prints
   {
     "content": {}
   }
 */

When accessing the SimpleXMLElement object, It gets the CDATA :

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo $xml->content; 
/* prints
   Hello, world!
*/

I makes sense to use LIBXML_NOCDATA because json_encode don't access the SimpleXMLElement to trigger the string casting feature, I'm guessing a __toString() equivalent.

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>", null, LIBXML_NOCDATA);
echo json_encode($xml);
/*
 {
   "content": "Hello, world!"
 }
*/

How to enter command with password for git pull?

Using the credentials helper command-line option:

git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin

How to check if a std::string is set or not?

You can't; at least not the same way you can test whether a pointer is NULL.

A std::string object is always initialized and always contains a string; its contents by default are an empty string ("").

You can test for emptiness (using s.size() == 0 or s.empty()).

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

How to compare strings

In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect:

if (string == "add") { ... }

When used properly, operator overloading is an excellent C++ feature.

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

Checking for duplicate strings in JavaScript array

   var elems = ['f', 'a','b','f', 'c','d','e','f','c'];

    elems.sort();

    elems.forEach(function (value, index, arr){

        let first_index = arr.indexOf(value);
        let last_index = arr.lastIndexOf(value);

         if(first_index !== last_index){

         console.log('Duplicate item in array ' + value);

         }else{

         console.log('unique items in array ' + value);

         }

    });

The executable was signed with invalid entitlements

I had not agreed to the new updated licensed agreement from apple.

Briefly : Please log in to your developer's account -> profile's -> review -> read the agreement or get your lawyer read it for you -> agree (at your own will) -> and again click profile's to check the status of your profile.

In my scenario the valid code signing entity was not showing up. When i followed the above procedure it was visible and i was able to run the app on the device and/or create the iPA file without much difficulty.

How to use custom packages

another solution:
add src/myproject to $GOPATH.

Then import "mylib" will compile.

Dynamically select data frame columns using $ and a character value

Using dplyr provides an easy syntax for sorting the data frames

library(dplyr)
mtcars %>% arrange(gear, desc(mpg))

It might be useful to use the NSE version as shown here to allow dynamically building the sort list

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)

How to use adb command to push a file on device without sd card

Try this to push in Internal storage.

adb push my-file.apk ./storage/emulated/0/

Works in One plus device, without SD card.

Rails where condition using NOT NIL

With Rails 4 it's easy:

 Foo.includes(:bar).where.not(bars: {id: nil})

See also: http://guides.rubyonrails.org/active_record_querying.html#not-conditions

Include PHP inside JavaScript (.js) files

Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Initialising an array of fixed size in python

Why don't these questions get answered with the obvious answer?

a = numpy.empty(n, dtype=object)

This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's

Object[] a = new Object[n];

If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.

How to change value of object which is inside an array using JavaScript or jQuery?

You can use map function --

const answers = this.state.answers.map(answer => {
  if(answer.id === id) return { id: id, value: e.target.value }
  return answer
})

this.setState({ answers: answers })

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.

  1. Open Android Studio and click cancel/ignore for error prompts on missing SDK for each project.
  2. Close all your open projects. You can do this by File > Close Project.
  3. After you do step 1 for all projects, the Welcome screen appears.
  4. The welcome screen will detect you are missing the SDK and give you options to fix the problem, i.e., install the SDKs for you.

When does a process get SIGABRT (signal 6)?

There's another simple cause in case of c++.

std::thread::~thread{
    if((joinable ())
        std::terminate ();
}

i.e. scope of thread ended but you forgot to call either

thread::join();

or

thread::detach();

this.getClass().getClassLoader().getResource("...") and NullPointerException

One other thing to look at that solved it for me :

In an Eclipse / Maven project, I had Java classes in src/test/java in which I was using the this.getClass().getResource("someFile.ext"); pattern to look for resources in src/test/resources where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.

Right click on the src/test/resources source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext to make sure my files weren't getting scrubbed; my tests now can find their resource files.

How to change the text of a label?

Try this:

$('[id$=lblVessel]').text("NewText");

The id$= will match the elements that end with that text, which is how ASP.NET auto-generates IDs. You can make it safer using span[id=$=lblVessel] but usually this isn't necessary.

How to compile Tensorflow with SSE4.2 and AVX instructions?

I have recently installed it from source and bellow are all the steps needed to install it from source with the mentioned instructions available.

Other answers already describe why those messages are shown. My answer gives a step-by-step on how to isnstall, which may help people struglling on the actual installation as I did.

  1. Install Bazel

Download it from one of their available releases, for example 0.5.2. Extract it, go into the directory and configure it: bash ./compile.sh. Copy the executable to /usr/local/bin: sudo cp ./output/bazel /usr/local/bin

  1. Install Tensorflow

Clone tensorflow: git clone https://github.com/tensorflow/tensorflow.git Go to the cloned directory to configure it: ./configure

It will prompt you with several questions, bellow I have suggested the response to each of the questions, you can, of course, choose your own responses upon as you prefer:

Using python library path: /usr/local/lib/python2.7/dist-packages
Do you wish to build TensorFlow with MKL support? [y/N] y
MKL support will be enabled for TensorFlow
Do you wish to download MKL LIB from the web? [Y/n] Y
Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: 
Do you wish to use jemalloc as the malloc implementation? [Y/n] n
jemalloc disabled
Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N
No Google Cloud Platform support will be enabled for TensorFlow
Do you wish to build TensorFlow with Hadoop File System support? [y/N] N
No Hadoop File System support will be enabled for TensorFlow
Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] N
No XLA JIT support will be enabled for TensorFlow
Do you wish to build TensorFlow with VERBS support? [y/N] N
No VERBS support will be enabled for TensorFlow
Do you wish to build TensorFlow with OpenCL support? [y/N] N
No OpenCL support will be enabled for TensorFlow
Do you wish to build TensorFlow with CUDA support? [y/N] N
No CUDA support will be enabled for TensorFlow
  1. The pip package. To build it you have to describe which instructions you want (you know, those Tensorflow informed you are missing).

Build pip script: bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.1 --copt=-msse4.2 -k //tensorflow/tools/pip_package:build_pip_package

Build pip package: bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

Install Tensorflow pip package you just built: sudo pip install /tmp/tensorflow_pkg/tensorflow-1.2.1-cp27-cp27mu-linux_x86_64.whl

Now next time you start up Tensorflow it will not complain anymore about missing instructions.

C# equivalent of C++ vector, with contiguous memory?

C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap

How to extract the substring between two markers?

With sed it is possible to do something like this with a string:

echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"

And this will give me 1234 as a result.

You could do the same with re.sub function using the same regex.

>>> re.sub(r'.*AAA(.*)ZZZ.*', r'\1', 'gfgfdAAA1234ZZZuijjk')
'1234'

In basic sed, capturing group are represented by \(..\), but in python it was represented by (..).

AngularJS - get element attributes values

You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB

_x000D_
_x000D_
function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
_x000D_
  console.log(x);_x000D_
  console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Convert Array to Object

Quick and dirty #2:

var i = 0
  , s = {}
  , a = ['A', 'B', 'C'];

while( i < a.length ) { s[i] = a[i++] };

"for" vs "each" in Ruby

As far as I know, using blocks instead of in-language control structures is more idiomatic.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

You should import the the project

https://issuetracker.google.com/issues/37008041

This error shows up when there is a module in your project whose .iml file does not contain: external.system.id="GRADLE" Can you please check your .iml files? Also, instead of opening the project, import it, that will completely rewrite your .iml files and you won't see that error again.

C++ int float casting

he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float

 (float)(a.y - b.y) / (a.x - b.x);

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

You shouldn't just turn off verification. Rather you should download a certificate bundle, perhaps the curl bundle will do?

Then you just need to put it on your web server, giving the user that runs php permission to read the file. Then this code should work for you:

$arrContextOptions= [
    'ssl' => [
        'cafile' => '/path/to/bundle/cacert.pem',
        'verify_peer'=> true,
        'verify_peer_name'=> true,
    ],
];

$response = file_get_contents(
    'https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json',
    false,
    stream_context_create($arrContextOptions)
);

Hopefully, the root certificate of the site you are trying to access is in the curl bundle. If it isn't, this still won't work until you get the root certificate of the site and put it into your certificate file.

How to print a dictionary's key?

The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.

Is this how you define a function in jQuery?

First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.

Here's an example:

$(document).ready( function () {

    var MyBlah = function($blah) { alert($blah);  };

    MyBlah("Hello this works") // Inside the anonymous function we are cool.

 });

MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)

This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.

Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.

Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).

Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:

$('div#message').myBlah("hello")

See also: http://www.re-cycledair.com/creating-jquery-plugins

Retrieve a Fragment from a ViewPager

In order to get current Visible fragment from ViewPager. I am using this simple statement and it's working fine.

      public Fragment getFragmentFromViewpager()  
      {
         return ((Fragment) (mAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem())));
      }

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

How to create .ipa file using Xcode?

In Xcode-11.2.1

You might be see different pattern for uploading IPA
Steps:-

i) Add your apple developer id in xcode preference -> account

ii)Clean Build Folder :-

enter image description here

iii) Archive

enter image description here

iv) Tap on Distribute App

enter image description here

v) Choose Ad-hoc to distribute on designated device

enter image description here

6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)

enter image description here

enter image description here

7)Click on export and you get ipa.

enter image description here

8)Visit https://www.diawi.com/ & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)

git remove merge commit from history

Starting with the repo in the original state

Original repo history

To remove the merge commit and squash the branch into a single commit in the mainline

Squashed commits, no merge commit

Use these commands (replacing 5 and 1 with the SHAs of the corresponding commits):

git checkout 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git rebase HEAD master

To retain a merge commit but squash the branch commits into one:

Squashed commits, retained merge commit

Use these commands (replacing 5, 1 and C with the SHAs of the corresponding commits):

git checkout -b tempbranch 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git checkout C
git merge --no-ff tempbranch
git rebase HEAD master

To remove the merge commit and replace it with individual commits from the branch

Branch moved into mainline, no merge commit

Just do (replacing 5 with the SHA of the corresponding commit):

git rebase 5 master

And finally, to remove the branch entirely

Branch removed entirely

Use this command (replacing C and D with the SHAs of the corresponding commits):

git rebase --onto C D~ master

C++ Boost: undefined reference to boost::system::generic_category()

I searched for a solution as well, and none of the answers I encountered solved the error, Until I found the answer of "ViRuSTriNiTy" to this thread: Undefined reference to 'boost::system::generic_category()'?

according to that answer, try to add these lines to your cmake file:

find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(... ${Boost_INCLUDE_DIRS})
link_directories(... ${Boost_LIBRARY_DIRS})
target_link_libraries(... ${Boost_LIBRARIES})

In PHP how can you clear a WSDL cache?

I recommend using a cache-buster in the wsdl url.

In our apps we use a SVN Revision id in the wsdl url so the client immediately knows of changing structures. This works on our app because, everytime we change the server-side, we also need to adjust the client accordingly.

$client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');

This requires svn to be configured properly. Not on all repositories this is enabled by default.

In case you are not responsible for both components (server,client) or you don't use SVN you may find another indicator which can be utilised as a cache-buster in your wsdl url.

String.Format not work in TypeScript

FIDDLE: https://jsfiddle.net/1ytxfcwx/

NPM: https://www.npmjs.com/package/typescript-string-operations

GITHUB: https://github.com/sevensc/typescript-string-operations

I implemented a class for String. Its not perfect but it works for me.

use it i.e. like this:

var getFullName = function(salutation, lastname, firstname) {
    return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}

export class String {
    public static Empty: string = "";

    public static isNullOrWhiteSpace(value: string): boolean {
        try {
            if (value == null || value == 'undefined')
                return false;

            return value.replace(/\s/g, '').length < 1;
        }
        catch (e) {
            return false;
        }
    }

    public static Format(value, ...args): string {
        try {
            return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
                var s = match.split(':');
                if (s.length > 1) {
                    i = i[0];
                    match = s[1].replace('}', '');
                }

                var arg = String.formatPattern(match, args[i]);
                return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
            });
        }
        catch (e) {
            return String.Empty;
        }
    }

    private static formatPattern(match, arg): string {
        switch (match) {
            case 'L':
                arg = arg.toLowerCase();
                break;
            case 'U':
                arg = arg.toUpperCase();
                break;
            default:
                break;
        }

        return arg;
    }
}

EDIT:

I extended the class and created a repository on github. It would be great if you can help to improve it!

https://github.com/sevensc/typescript-string-operations

or download the npm package

https://www.npmjs.com/package/typescript-string-operations

How to check if a number is a power of 2

bool IsPowerOfTwo(ulong x)
{
    return x > 0 && (x & (x - 1)) == 0;
}

what is the difference between OLE DB and ODBC data sources?

ODBC works only for relational databases, it can't works with non-relational databases such as Ms Excel files. Where Olebd can do everything.

Resize on div element

You can change your text or Content or Attribute depend on Screen size: HTML:

<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>

Javascript:

<script>
const changeText = document.querySelector('.change');
function resize() {
  if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
    changeText.textContent="FAQ";
  } else {
    changeText.textContent="Frequently Asked Questions (FAQ)";
  }
}
window.onresize = resize;
</script>

Integrating the ZXing library directly into my Android application

Have you seen the wiki pages on the zxing website? It seems you might find GettingStarted, DeveloperNotes and ScanningViaIntent helpful.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

How to go up a level in the src path of a URL in HTML?

In Chrome when you load a website from some HTTP server both absolute paths (e.g. /images/sth.png) and relative paths to some upper level directory (e.g. ../images/sth.png) work.

But!

When you load (in Chrome!) a HTML document from local filesystem you cannot access directories above current directory. I.e. you cannot access ../something/something.sth and changing relative path to absolute or anything else won't help.

Add an index (numeric ID) column to large data frame

Well, if I understand you correctly. You can do something like the following.

To show it, I first create a data.frame with your example

df <- 
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")

df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")  

You can then run one of the following lines to add a column (at the end of the data.frame) with the row number as the generated user id. The second lines simply adds leading zeros.

df$generated_uid  <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))

If you absolutely want the generated user id to be the first column, you can add the column like so:

df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)

or simply rearrage the columns.

In Java, how do I parse XML as a String instead of a file?

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

How to change TextBox's Background color?

It is txtName.BackColor = System.Drawing.Color.Red;

one can also use txtName.BackColor = Color.Aqua; which is the same as txtName.BackColor = System.Color.Aqua;

Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;

Multiple left-hand assignment with JavaScript

Try this:

var var1=42;
var var2;

alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.

Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.

It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.

How to retrieve checkboxes values in jQuery

Thanks altCognito, your solution helped. We can also do this by using name of the checkboxes:

function updateTextArea() {         
   var allVals = [];
   $('[name=chkbox]:checked').each(function() {
      allVals.push($(this).val());
   });
   $('#t').val(allVals)
} 
$(function() { 
    $('#c_b input').click(updateTextArea);
    updateTextArea();
});

What is the difference between a deep copy and a shallow copy?

Breadth vs Depth; think in terms of a tree of references with your object as the root node.

Shallow:

Before Copy Shallow Copying Shallow Done

The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.

Deep:

Before Copy Deep Copying Deep Done

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

How can I expand and collapse a <div> using javascript?

If you used the data-role collapsible e.g.

    <div id="selector" data-role="collapsible" data-collapsed="true">
    html......
    </div>

then it will close the the expanded div

    $("#selector").collapsible().collapsible("collapse");   

Download a file from NodeJS Server using Express

There are several ways to do it This is the better way

res.download('/report-12345.pdf')

or in your case this might be

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});

Know More

how to merge 200 csv files in Python

If the merged CSV is going to be used in Python then just use glob to get a list of the files to pass to fileinput.input() via the files argument, then use the csv module to read it all in one go.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

What Does This Mean in PHP -> or =>

The double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();

How can I change the color of AlertDialog title and the color of the line under it

    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);

    String title = context.getString(R.string.agreement_popup_message);
    SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
    ssBuilder.setSpan(
            foregroundColorSpan,
            0,
            title.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );

AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)

How to make a ssh connection with python?

Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/

The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.

Setting Up a Custom SSH Server

The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.

Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.

Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

Example 10-1. sshserver.py

from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os

class SSHDemoProtocol(recvline.HistoricRecvLine):
    def __init__(self, user):
        self.user = user

    def connectionMade(self) : 
     recvline.HistoricRecvLine.connectionMade(self)
        self.terminal.write("Welcome to my test SSH server.")
        self.terminal.nextLine() 
        self.do_help()
        self.showPrompt()

    def showPrompt(self): 
        self.terminal.write("$ ")

    def getCommandFunc(self, cmd):
        return getattr(self, ‘do_’ + cmd, None)

    def lineReceived(self, line):
        line = line.strip()
        if line: 
            cmdAndArgs = line.split()
            cmd = cmdAndArgs[0]
            args = cmdAndArgs[1:]
            func = self.getCommandFunc(cmd)
            if func: 
               try:
                   func(*args)
               except Exception, e: 
                   self.terminal.write("Error: %s" % e)
                   self.terminal.nextLine()
            else:
               self.terminal.write("No such command.")
               self.terminal.nextLine()
        self.showPrompt()

    def do_help(self, cmd=”):
        "Get help on a command. Usage: help command"
        if cmd: 
            func = self.getCommandFunc(cmd)
            if func:
                self.terminal.write(func.__doc__)
                self.terminal.nextLine()
                return

        publicMethods = filter(
            lambda funcname: funcname.startswith(‘do_’), dir(self)) 
        commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods] 
        self.terminal.write("Commands: " + " ".join(commands))
        self.terminal.nextLine()

    def do_echo(self, *args):
        "Echo a string. Usage: echo my line of text"
        self.terminal.write(" ".join(args)) 
        self.terminal.nextLine()

    def do_whoami(self):
        "Prints your user name. Usage: whoami"
        self.terminal.write(self.user.username)
        self.terminal.nextLine()

    def do_quit(self):
        "Ends your session. Usage: quit" 
        self.terminal.write("Thanks for playing!")
        self.terminal.nextLine() 
        self.terminal.loseConnection()

    def do_clear(self):
        "Clears the screen. Usage: clear" 
        self.terminal.reset()

class SSHDemoAvatar(avatar.ConchUser): 
    implements(conchinterfaces.ISession)

    def __init__(self, username): 
        avatar.ConchUser.__init__(self) 
        self.username = username 
        self.channelLookup.update({‘session’:session.SSHSession})

    def openShell(self, protocol): 
        serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))

    def getPty(self, terminal, windowSize, attrs):
        return None

    def execCommand(self, protocol, cmd): 
        raise NotImplementedError

    def closed(self):
        pass

class SSHDemoRealm:
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if conchinterfaces.IConchUser in interfaces:
            return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
        else:
            raise Exception, "No supported interfaces found."

def getRSAKeys():
    if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
        # generate a RSA keypair
        print "Generating RSA keypair…" 
        from Crypto.PublicKey import RSA 
        KEY_LENGTH = 1024
        rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
        publicKeyString = keys.makePublicKeyString(rsaKey) 
        privateKeyString = keys.makePrivateKeyString(rsaKey)
        # save keys for next time
        file(‘public.key’, ‘w+b’).write(publicKeyString)
        file(‘private.key’, ‘w+b’).write(privateKeyString)
        print "done."
    else:
        publicKeyString = file(‘public.key’).read()
        privateKeyString = file(‘private.key’).read() 
    return publicKeyString, privateKeyString

if __name__ == "__main__":
    sshFactory = factory.SSHFactory() 
    sshFactory.portal = portal.Portal(SSHDemoRealm())
    users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
    sshFactory.portal.registerChecker(
 checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

    pubKeyString, privKeyString =
getRSAKeys()
    sshFactory.publicKeys = {
        ‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
    sshFactory.privateKeys = {
        ‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor 
    reactor.listenTCP(2222, sshFactory) 
    reactor.run()

{mospagebreak title=Setting Up a Custom SSH Server continued}

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:

$ ssh admin@localhost -p 2222 
admin@localhost’s password: aaa

>>> Welcome to my test SSH server.  
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit

Connection to localhost closed.

How do I get the title of the current active window using c#?

you can use process class it's very easy. use this namespace

using System.Diagnostics;

if you want to make a button to get active window.

private void button1_Click(object sender, EventArgs e)
    {            
       Process currentp = Process.GetCurrentProcess();
       TextBox1.Text = currentp.MainWindowTitle;  //this textbox will be filled with active window.
    }

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

Adding system header search path to Xcode

Though this question has an answer, I resolved it differently when I had the same issue. I had this issue when I copied folders with the option Create Folder references; then the above solution of adding the folder to the build_path worked. But when the folder was added using the Create groups for any added folder option, the headers were picked up automatically.

Differences between Oracle JDK and OpenJDK

A key difference going forward is the release schedule and support policy.

OpenJDK

OpenJDK will have a feature release every 6 months which is only supported until the next feature release. It's essentially a continuous stream of releases targeted to developers.

Oracle JDK

The Oracle JDK is targeted more towards an enterprise audience which values stability. It's based on one of the OpenJDK releases but is then given long term support (LTS). The Oracle JDK has releases planned every 3 years.

enter image description here

Source: https://www.oracle.com/java/java9-screencasts.html?bcid=5582439790001&playerType=single-social&size=events

X close button only using css

-- Simple HTML Solution --

Final result of easy to resize icon:

two close X buttons with different thickness.

JSfiddle demo: https://jsfiddle.net/allenski/yr5gk3cm/

The simple HTML:

<a href="#" class="close" tabindex="0" role="button">close</a>

Note:

  • tabindex attribute is there to help accessibility focus of iOS touch devices.
  • role attribute is to let screen readers users know this is a button.
  • The word close is also intended for screen readers to mention.

The CSS code:

.close {
    position: absolute;
    top: 0;
    right: 0;
    display: block;
    width: 50px;
    height: 50px;
    font-size: 0;
}
.close:before, 
.close:after {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 20px;
    background-color: #F0F0F0;
    transform: rotate(45deg) translate(-50%, -50%);
    transform-origin: top left;
    content: '';
}
.close:after {
    transform: rotate(-45deg) translate(-50%, -50%);
}

To adjust thickness of close X icon, change the width property. Example for thinner icon:

.close:before, 
.close:after {
    width: 2px;
}

To adjust length of close X icon, change the height property. Example:

.close:before, 
.close:after {
    height: 33px;
}

How to remove CocoaPods from a project?

Removing CocoaPods from a project is possible, but not currently automated by the CLI. First thing, if the only issue you have is not being able to use an xcworkspace you can use CocoaPods with just xcodeprojs by using the --no-integrate flag which will produce the Pods.xcodeproj but not a workspace. Then you can add this xcodeproj as a subproject to your main xcodeproj.

If you really want to remove all CocoaPods integration you need to do a few things:

NOTE editing some of these things if done incorrectly could break your main project. I strongly encourage you to check your projects into source control just in case. Also these instructions are for CocoaPods version 0.39.0, they could change with new versions.

  1. Delete the standalone files (Podfile Podfile.lock and your Pods directory)
  2. Delete the generated xcworkspace
  3. Open your xcodeproj file, delete the references to Pods.xcconfig and libPods.a (in the Frameworks group)
  4. Under your Build Phases delete the Copy Pods Resources, Embed Pods Frameworks and Check Pods Manifest.lock phases.
  5. This may seem obvious but you'll need to integrate the 3rd party libraries some other way or remove references to them from your code.

After those steps you should be set with a single xcodeproj that existed before you integrated CocoaPods. If I missed anything let me know and I will edit this.

Also we're always looking for suggestions for how to improve CocoaPods so if you have an issues please submit them in our issue tracker so we can come up with a way to fix them!

EDIT

As shown by Jack Wu in the comments there is a third party CocoaPods plugin that can automate these steps for you. It can be found here. Note that it is a third party plugin and might not always be updated when CocoaPods is. Also note that it is made by a CocoaPods core team member so that problem won't be a problem.

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

How to SHUTDOWN Tomcat in Ubuntu?

For a more graceful way, try the following:

Caveat: I'm running Debian 7, not Ubuntu, though it is a Debian derivative

If you're running Tomcat as a service, you can get a list of all running services by typing:

sudo service --status-all

I'm running Tomcat 7, which is displayed as tomcat7 in said list. Then, to shut it down just type:

sudo service tomcat7 stop

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.

mysql said: Cannot connect: invalid settings. xampp

if you are using google chrome you can fix the problem via , trying any one of the steps mentioned on this page but you need to clear your whole browsing history .... clear all the data that chrome saved onto your computer by pressing ctrl+h and the clearing all the browsing data select all the fields now restart php my admin and all will work

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

Yes, you can. But if you have non-unique entries on your table, it will fail. Here is the how to add unique constraint on your table. If you're using PostgreSQL 9.x you can follow below instruction.

CREATE UNIQUE INDEX constraint_name ON table_name (columns);

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

Converting a String array into an int Array in java

This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.

What is the => assignment in C# in a property signature

For the following statement shared by Alex Booker in their answer

When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:

Please see the following screenshot, it shows how this statement (using SharpLab link)

public string APIBasePath => Configuration.ToolsAPIBasePath;

converts to

public string APIBasePath
{
    get
    {
        return Configuration.ToolsAPIBasePath;
    }
}

Screenshot: enter image description here

What does CultureInfo.InvariantCulture mean?

For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.

A appropriate way to do this would be set it at the culture level (for German) like this:

Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;

Properties order in Margin

<object Margin="left,top,right,bottom"/>
- or - 
<object Margin="left,top"/>
- or - 
<object Margin="thicknessReference"/>

See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx

jQuery calculate sum of values in all text fields

$(".price").each(function(){ 
total_price += parseFloat($(this).val()); 
}); 

please try like this...

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Basically this happened with me, when i tried to change the package name of the app.

So, in emulator, same app was installed before. When i tried to install app after changing package name, it said, authority already used by older application in device.

Simply after uninstalling the application, it solved my problem.

Also, Authority name should always be : your.package.name.UNIQUENAME;

example :

  <provider
        android:name="com.aviary.android.feather.cds.AviaryCdsProvider"
        android:authorities="your.package.name.AviaryCdsProvider"
       />

Getting command-line password input in Python

Here is my code based off the code offered by @Ahmed ALaa

Features:

  • Works for passwords up to 64 characters
  • Accepts backspace input
  • Outputs * character (DEC: 42 ; HEX: 0x2A) instead of the input character

Demerits:

  • Works on Windows only

The function secure_password_input() returns the password as a string when called. It accepts a Password Prompt string, which will be displayed to the user to type the password

def secure_password_input(prompt=''):
    p_s = ''
    proxy_string = [' '] * 64
    while True:
        sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
        c = msvcrt.getch()
        if c == b'\r':
            break
        elif c == b'\x08':
            p_s = p_s[:-1]
            proxy_string[len(p_s)] = " "
        else:
            proxy_string[len(p_s)] = "*"
            p_s += c.decode()

    sys.stdout.write('\n')
    return p_s

How to use code to open a modal in Angular 2?

Here is my full implementation of modal bootstrap angular2 component:

I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

  <script src="assets/js/jquery-2.1.1.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

modal.component.ts:

import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';

declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    @Input() title:string;
    @Input() showClose:boolean = true;
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    modalEl = null;
    id: string = uniqueId('modal_');

    constructor(private _rootNode: ElementRef) {}

    open() {
        this.modalEl.modal('show');
    }

    close() {
        this.modalEl.modal('hide');
    }

    closeInternal() { // close modal when click on times button in up-right corner
        this.onClose.next(null); // emit event
        this.close();
    }

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    has(selector) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}

let modal_id: number = 0;
export function uniqueId(prefix: string): string {
    return prefix + ++modal_id;
}

modal.html:

<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <ng-content select="mhead"></ng-content>
                <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
            </div>
            <div class="modal-body">
                <ng-content></ng-content>
            </div>

            <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                <ng-content select="mfoot"></ng-content>
            </div>
        </div>
    </div>
</div>

And example of usage in client Editor component: client-edit-component.ts:

import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';

@Component({
  selector: 'client-edit',
  directives: [ Modal ],
  templateUrl: './client-edit.html',
  providers: [ ClientService ]
})
export class ClientEdit {

    _modal = null;

    constructor(private _ClientService: ClientService) {}

    bindModal(modal) {this._modal=modal;}

    open(client) {
        this._modal.open();
        console.log({client});
    }

    close() {
        this._modal.close();
    }

}

client-edit.html:

<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
    <mhead>Som non-standart title</mhead>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

Ofcourse title, showClose, mhead and mfoot ar optional parameters.

Using NotNull Annotation in method argument

As mentioned above @NotNull does nothing on its own. A good way of using @NotNull would be using it with Objects.requireNonNull

public class Foo {
    private final Bar bar;

    public Foo(@NotNull Bar bar) {
        this.bar = Objects.requireNonNull(bar, "bar must not be null");
    }
}

C++ static virtual members?

No, this is not possible, because static member functions lack a this pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.

virtual functions in a class needs the this pointer, and is very coupled to the class, hence they can't be static.

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

Replace invalid values with None in Pandas DataFrame

I prefer the solution using replace with a dict because of its simplicity and elegance:

df.replace({'-': None})

You can also have more replacements:

df.replace({'-': None, 'None': None})

And even for larger replacements, it is always obvious and clear what is replaced by what - which is way harder for long lists, in my opinion.

What does Visual Studio mean by normalize inconsistent line endings?

Some lines end with \n.

Some other lines end with \r\n.

Visual Studio suggests you to make all lines end the same.

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

2 "style" inline css img tags?

You should use :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="25"/>

That should work!!

If you want to create class then :

.size {
width:100px;
height:100px;
}

and then apply it like :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" class="size" alt="25"/>

by creating a class you can use it at multiple places.

If you want to use only at one place then use inline CSS. Also Inline CSS overrides other CSS.

Create local maven repository

If maven is not creating Local Repository i.e .m2/repository folder then try below step.

In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close

No ConcurrentList<T> in .Net 4.0?

With all due respect to the great answers provided already, there are times that I simply want a thread-safe IList. Nothing advanced or fancy. Performance is important in many cases but at times that just isn't a concern. Yes, there are always going to be challenges without methods like "TryGetValue" etc, but most cases I just want something that I can enumerate without needing to worry about putting locks around everything. And yes, somebody can probably find some "bug" in my implementation that might lead to a deadlock or something (I suppose) but lets be honest: When it comes to multi-threading, if you don't write your code correctly, it is going deadlock anyway. With that in mind I decided to make a simple ConcurrentList implementation that provides these basic needs.

And for what its worth: I did a basic test of adding 10,000,000 items to regular List and ConcurrentList and the results were:

List finished in: 7793 milliseconds. Concurrent finished in: 8064 milliseconds.

public class ConcurrentList<T> : IList<T>, IDisposable
{
    #region Fields
    private readonly List<T> _list;
    private readonly ReaderWriterLockSlim _lock;
    #endregion

    #region Constructors
    public ConcurrentList()
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>();
    }

    public ConcurrentList(int capacity)
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>(capacity);
    }

    public ConcurrentList(IEnumerable<T> items)
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>(items);
    }
    #endregion

    #region Methods
    public void Add(T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Add(item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public void Insert(int index, T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Insert(index, item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public bool Remove(T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            return this._list.Remove(item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public void RemoveAt(int index)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.RemoveAt(index);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public int IndexOf(T item)
    {
        try
        {
            this._lock.EnterReadLock();
            return this._list.IndexOf(item);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public void Clear()
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Clear();
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public bool Contains(T item)
    {
        try
        {
            this._lock.EnterReadLock();
            return this._list.Contains(item);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        try
        {
            this._lock.EnterReadLock();
            this._list.CopyTo(array, arrayIndex);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new ConcurrentEnumerator<T>(this._list, this._lock);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new ConcurrentEnumerator<T>(this._list, this._lock);
    }

    ~ConcurrentList()
    {
        this.Dispose(false);
    }

    public void Dispose()
    {
        this.Dispose(true);
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
            GC.SuppressFinalize(this);

        this._lock.Dispose();
    }
    #endregion

    #region Properties
    public T this[int index]
    {
        get
        {
            try
            {
                this._lock.EnterReadLock();
                return this._list[index];
            }
            finally
            {
                this._lock.ExitReadLock();
            }
        }
        set
        {
            try
            {
                this._lock.EnterWriteLock();
                this._list[index] = value;
            }
            finally
            {
                this._lock.ExitWriteLock();
            }
        }
    }

    public int Count
    {
        get
        {
            try
            {
                this._lock.EnterReadLock();
                return this._list.Count;
            }
            finally
            {
                this._lock.ExitReadLock();
            }
        }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }
    #endregion
}

    public class ConcurrentEnumerator<T> : IEnumerator<T>
{
    #region Fields
    private readonly IEnumerator<T> _inner;
    private readonly ReaderWriterLockSlim _lock;
    #endregion

    #region Constructor
    public ConcurrentEnumerator(IEnumerable<T> inner, ReaderWriterLockSlim @lock)
    {
        this._lock = @lock;
        this._lock.EnterReadLock();
        this._inner = inner.GetEnumerator();
    }
    #endregion

    #region Methods
    public bool MoveNext()
    {
        return _inner.MoveNext();
    }

    public void Reset()
    {
        _inner.Reset();
    }

    public void Dispose()
    {
        this._lock.ExitReadLock();
    }
    #endregion

    #region Properties
    public T Current
    {
        get { return _inner.Current; }
    }

    object IEnumerator.Current
    {
        get { return _inner.Current; }
    }
    #endregion
}

Check if a file exists or not in Windows PowerShell?

cls

$exactadminfile = "C:\temp\files\admin" #First folder to check the file

$userfile = "C:\temp\files\user" #Second folder to check the file

$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations

foreach ($filename in $filenames) {
  if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
    Write-Warning "$filename absent from both locations"
  } else {
    Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
  }
}

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

Is it possible to have SSL certificate for IP address, not domain name?

The answer is yes. In short, it is a subject alternative name (SAN) certificate that contains IPs where you would typically see DNS entries. The certificate type is not limited to Public IPs - that restriction is only imposed by a signing authority rather than the technology. I just wanted to clarify that point. I suspect you really just want to get rid of that pesky insecure prompt on your internal websites and devices without the cost and hassle of giving them DNS names then paying for a CA to issue a cert every year or two. You should NOT be trying to convince the world that your IP address is a reputable website and folks should feel comfortable providing their payment information. Now that we have established why no reputable organization wants to issue this type of certificate, lets just do it ourselves with a self signed SAN certificate. Internally I have a trusted certificate that is deployed to all of our hosts, then I sign this type of certificate with it and all devices become trusted. Doing that here is beyond the scope of the question but I think it relevant to the discussion as the question and solution go hand in hand. To be concise, here is how to generate an individual self signed SAN certificate with IP addresses. Expand the IP list to include your entire subnet and use one cert for everything.

#!/bin/bash
#using: OpenSSL 1.1.1c FIPS  28 May 2019 / CentOS Linux release 8.2.2004

C=US ; ST=Confusion ; L=Anywhere ; O=Private\ Subnet ; [email protected]
BITS=2048
CN=RFC1918
DOM=company.com
SUBJ="/C=$C/ST=$ST/L=$L/O=$O/CN=$CN.$DOM"

openssl genrsa -out ip.key $BITS

SAN='\n[SAN]\nsubjectAltName=IP:192.168.1.0,IP:192.168.1.1,IP:192.168.1.2,IP:192.168.1.3,IP:192.168.1.4,IP:192.168.1.5,IP:192.168.1.6,IP:192.168.1.7,IP:192.168.1.8,IP:192.168.1.9,IP:192.168.1.10'

cp /etc/pki/tls/openssl.cnf /tmp/openssl.cnf
echo -e "$SAN" >> /tmp/openssl.cnf

openssl req -subj "$SUBJ" -new -x509 -days 10950 \
    -key ip.key -out ip.crt -batch \
    -set_serial 168933982 \
    -config /tmp/openssl.cnf \
    -extensions SAN

openssl x509 -in ip.crt -noout -text

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

Get Current date in epoch from Unix shell script

The Unix Date command will display in epoch time

the command is

date +"%s"

https://linux.die.net/man/1/date

Edit: Some people have observed you asked for days, so it's the result of that command divided by 86,400

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Build project into a JAR automatically in Eclipse

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.

  1. Right click on your project
  2. Choose Export > Java > JAR file
  3. Choose included files and name output JAR, then click Next
  4. Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file

Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

How to change an image on click using CSS alone?

No, you will need scripting to place a click Event handler on the Element that does what you want.

Counting number of lines, words, and characters in a text file

I agree with @Cthulhu answer. In your code you can reset your Scanner object (in).

in.reset();

This will reset your in object at the first line of your file.

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DATA_TYPE();

For you problem:

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DECIMAL(Precision, Scale); 

SQL Server: Filter output of sp_who2

Slight improvement to Astander's answer. I like to put my criteria at top, and make it easier to reuse day to day:

DECLARE @Spid INT, @Status VARCHAR(MAX), @Login VARCHAR(MAX), @HostName VARCHAR(MAX), @BlkBy VARCHAR(MAX), @DBName VARCHAR(MAX), @Command VARCHAR(MAX), @CPUTime INT, @DiskIO INT, @LastBatch VARCHAR(MAX), @ProgramName VARCHAR(MAX), @SPID_1 INT, @REQUESTID INT

    --SET @SPID = 10
    --SET @Status = 'BACKGROUND'
    --SET @LOGIN = 'sa'
    --SET @HostName = 'MSSQL-1'
    --SET @BlkBy = 0
    --SET @DBName = 'master'
    --SET @Command = 'SELECT INTO'
    --SET @CPUTime = 1000
    --SET @DiskIO = 1000
    --SET @LastBatch = '10/24 10:00:00'
    --SET @ProgramName = 'Microsoft SQL Server Management Studio - Query'
    --SET @SPID_1 = 10
    --SET @REQUESTID = 0

    SET NOCOUNT ON 
    DECLARE @Table TABLE(
            SPID INT,
            Status VARCHAR(MAX),
            LOGIN VARCHAR(MAX),
            HostName VARCHAR(MAX),
            BlkBy VARCHAR(MAX),
            DBName VARCHAR(MAX),
            Command VARCHAR(MAX),
            CPUTime INT,
            DiskIO INT,
            LastBatch VARCHAR(MAX),
            ProgramName VARCHAR(MAX),
            SPID_1 INT,
            REQUESTID INT
    )
    INSERT INTO @Table EXEC sp_who2
    SET NOCOUNT OFF
    SELECT  *
    FROM    @Table
    WHERE
    (@Spid IS NULL OR SPID = @Spid)
    AND (@Status IS NULL OR Status = @Status)
    AND (@Login IS NULL OR Login = @Login)
    AND (@HostName IS NULL OR HostName = @HostName)
    AND (@BlkBy IS NULL OR BlkBy = @BlkBy)
    AND (@DBName IS NULL OR DBName = @DBName)
    AND (@Command IS NULL OR Command = @Command)
    AND (@CPUTime IS NULL OR CPUTime >= @CPUTime)
    AND (@DiskIO IS NULL OR DiskIO >= @DiskIO)
    AND (@LastBatch IS NULL OR LastBatch >= @LastBatch)
    AND (@ProgramName IS NULL OR ProgramName = @ProgramName)
    AND (@SPID_1 IS NULL OR SPID_1 = @SPID_1)
    AND (@REQUESTID IS NULL OR REQUESTID = @REQUESTID)

How do you remove all the options of a select box and then add one option and select it with jQuery?

Another way:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

Under this link, there are good practices https://api.jquery.com/select/

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

Solutions for INSERT OR UPDATE on SQL Server

See my detailed answer to a very similar previous question

@Beau Crawford's is a good way in SQL 2005 and below, though if you're granting rep it should go to the first guy to SO it. The only problem is that for inserts it's still two IO operations.

MS Sql2008 introduces merge from the SQL:2003 standard:

merge tablename with(HOLDLOCK) as target
using (values ('new value', 'different value'))
    as source (field1, field2)
    on target.idfield = 7
when matched then
    update
    set field1 = source.field1,
        field2 = source.field2,
        ...
when not matched then
    insert ( idfield, field1, field2, ... )
    values ( 7,  source.field1, source.field2, ... )

Now it's really just one IO operation, but awful code :-(

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables. It's done via "non standard" options. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

How to create a sub array from another array in Java?

The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:

java -version

I'm guessing that you are not running 1.6

What is the difference between And and AndAlso in VB.NET?

AndAlso is much like And, except it works like && in C#, C++, etc.

The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".

This is sometimes very useful, e.g. in an expression such as:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.

find a minimum value in an array of floats

If you want to use numpy, you must define darr to be a numpy array, not a list:

import numpy as np
darr = np.array([1, 3.14159, 1e100, -2.71828])
print(darr.min())

darr.argmin() will give you the index corresponding to the minimum.

The reason you were getting an error is because argmin is a method understood by numpy arrays, but not by Python lists.

Python check if website exists

from urllib2 import Request, urlopen, HTTPError, URLError

user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
        page_open = urlopen(req)
except HTTPError, e:
        print e.code
except URLError, e:
        print e.reason
else:
        print 'ok'

To answer the comment of unutbu:

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source

Return HTTP status code 201 in flask

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

return {"data": {"username": "test","id":"fdsf345"}}, 201

Note the postfixed number is the status code returned.

Alternatively, you may want to send a message to the client such as:

return {"msg": "Created Successfully"}, 201

Select by partial string from a pandas DataFrame

Should you need to do a case insensitive search for a string in a pandas dataframe column:

df[df['A'].str.contains("hello", case=False)]

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

Introduction

When using JPA and Hibernate, an entity can be in one of the following 4 states:

  • New - A newly created object that hasn’t ever been associated with a Hibernate Session (a.k.a Persistence Context) and is not mapped to any database table row is considered to be in the New or Transient state.

To become persisted we need to either explicitly call the persist method or make use of the transitive persistence mechanism.

  • Persistent - A persistent entity has been associated with a database table row and it’s being managed by the currently running Persistence Context.

Any change made to such an entity is going to be detected and propagated to the database (during the Session flush-time).

  • Detached - Once the currently running Persistence Context is closed all the previously managed entities become detached. Successive changes will no longer be tracked and no automatic database synchronization is going to happen.

  • Removed - Although JPA demands that managed entities only are allowed to be removed, Hibernate can also delete detached entities (but only through a remove method call).

Entity state transitions

To move an entity from one state to the other, you can use the persist, remove or merge methods.

JPA entity states

Fixing the problem

The issue you are describing in your question:

object references an unsaved transient instance - save the transient instance before flushing

is caused by associating an entity in the state of New to an entity that's in the state of Managed.

This can happen when you are associating a child entity to a one-to-many collection in the parent entity, and the collection does not cascade the entity state transitions.

So, you can fix this by adding cascade to the entity association that triggered this failure, as follows:

The @OneToOne association

@OneToOne(
    mappedBy = "post",
    orphanRemoval = true,
    cascade = CascadeType.ALL)
private PostDetails details;

Notice the CascadeType.ALL value we added for the cascade attribute.

The @OneToMany association

@OneToMany(
    mappedBy = "post", 
    orphanRemoval = true,
    cascade = CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();

Again, the CascadeType.ALL is suitable for the bidirectional @OneToMany associations.

Now, in order for the cascade to work properly in a bidirectional, you also need to make sure that the parent and child associations are in sync.

The @ManyToMany association

@ManyToMany(
    mappedBy = "authors",
    cascade = {
        CascadeType.PERSIST, 
        CascadeType.MERGE
    }
)
private List<Book> books = new ArrayList<>();

In a @ManyToMany association, you cannot use CascadeType.ALL or orphanRemoval as this will propagate the delete entity state transition from one parent to another parent entity.

Therefore, for @ManyToMany associations, you usually cascade the CascadeType.PERSIST or CascadeType.MERGE operations. Alternatively, you can expand that to DETACH or REFRESH.

How to use JUnit to test asynchronous processes

I prefer use wait and notify. It is simple and clear.

@Test
public void test() throws Throwable {
    final boolean[] asyncExecuted = {false};
    final Throwable[] asyncThrowable= {null};

    // do anything async
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // Put your test here.
                fail(); 
            }
            // lets inform the test thread that there is an error.
            catch (Throwable throwable){
                asyncThrowable[0] = throwable;
            }
            // ensure to release asyncExecuted in case of error.
            finally {
                synchronized (asyncExecuted){
                    asyncExecuted[0] = true;
                    asyncExecuted.notify();
                }
            }
        }
    }).start();

    // Waiting for the test is complete
    synchronized (asyncExecuted){
        while(!asyncExecuted[0]){
            asyncExecuted.wait();
        }
    }

    // get any async error, including exceptions and assertationErrors
    if(asyncThrowable[0] != null){
        throw asyncThrowable[0];
    }
}

Basically, we need to create a final Array reference, to be used inside of anonymous inner class. I would rather create a boolean[], because I can put a value to control if we need to wait(). When everything is done, we just release the asyncExecuted.

Run .jar from batch-file

There is a solution to this that does not require to specify the path of the jar file inside the .bat. This means the jar can be moved around in the filesystem with no changes, as long as the .bat file is always located in the same directory as the jar. The .bat code is:

java -jar %~dp0myjarfile.jar %*

Basically %0 would expand to the .bat full path, and %~dp0 expands to the .bat full path except the filename. So %~dp0myjarfile.jar is the full path of the myjarfile.jar colocated with the .bat file. %* will take all the arguments given to the .bat and pass it to the Java program. (see: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true )

Django set field value after a form is initialized

If you've already initialized the form, you can use the initial property of the field. For example,

form = CustomForm()
form.fields["Email"].initial = GetEmailString()

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

Return positions of a regex match() in Javascript?

var str = "The rain in SPAIN stays mainly in the plain";

function searchIndex(str, searchValue, isCaseSensitive) {
  var modifiers = isCaseSensitive ? 'gi' : 'g';
  var regExpValue = new RegExp(searchValue, modifiers);
  var matches = [];
  var startIndex = 0;
  var arr = str.match(regExpValue);

  [].forEach.call(arr, function(element) {
    startIndex = str.indexOf(element, startIndex);
    matches.push(startIndex++);
  });

  return matches;
}

console.log(searchIndex(str, 'ain', true));

Mocking member variables of a class using Mockito

Lots of others have already advised you to rethink your code to make it more testable - good advice and usually simpler than what I'm about to suggest.

If you can't change the code to make it more testable, PowerMock: https://code.google.com/p/powermock/

PowerMock extends Mockito (so you don't have to learn a new mock framework), providing additional functionality. This includes the ability to have a constructor return a mock. Powerful, but a little complicated - so use it judiciously.

You use a different Mock runner. And you need to prepare the class that is going to invoke the constructor. (Note that this is a common gotcha - prepare the class that calls the constructor, not the constructed class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class})

Then in your test set-up, you can use the whenNew method to have the constructor return a mock

whenNew(Second.class).withAnyArguments().thenReturn(mock(Second.class));

How do I stop a program when an exception is raised in Python?

import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiing with a non zero value is better for returning from an error

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

how to convert a string date into datetime format in python?

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I did below modifications and I am able to start the Hive Shell without any errors:

1. ~/.bashrc

Inside bashrc file add the below environment variables at End Of File : sudo gedit ~/.bashrc

#Java Home directory configuration
export JAVA_HOME="/usr/lib/jvm/java-9-oracle"
export PATH="$PATH:$JAVA_HOME/bin"

# Hadoop home directory configuration
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin

export HIVE_HOME=/usr/lib/hive
export PATH=$PATH:$HIVE_HOME/bin

2. hive-site.xml

You have to create this file(hive-site.xml) in conf directory of Hive and add the below details

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
</property>


<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>root</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>root</value>
</property>

<property>
  <name>datanucleus.autoCreateSchema</name>
  <value>true</value>
</property>

<property>
  <name>datanucleus.fixedDatastore</name>
  <value>true</value>
</property>

<property>
 <name>datanucleus.autoCreateTables</name>
 <value>True</value>
 </property>

</configuration>

3. You also need to put the jar file(mysql-connector-java-5.1.28.jar) in the lib directory of Hive

4. Below installations required on your Ubuntu to Start the Hive Shell:

  1. MySql
  2. Hadoop
  3. Hive
  4. Java

5. Execution Part:

  1. Start all services of Hadoop: start-all.sh

  2. Enter the jps command to check whether all Hadoop services are up and running: jps

  3. Enter the hive command to enter into hive shell: hive

How do I create a nice-looking DMG for Mac OS X using command-line tools?

After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference:

  1. Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4).

  2. Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG:

    hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \
          -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg
    
  3. Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation):

    device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \
             egrep '^/dev/' | sed 1q | awk '{print $1}')
    
  4. Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable.

  5. Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed):

    echo '
       tell application "Finder"
         tell disk "'${title}'"
               open
               set current view of container window to icon view
               set toolbar visible of container window to false
               set statusbar visible of container window to false
               set the bounds of container window to {400, 100, 885, 430}
               set theViewOptions to the icon view options of container window
               set arrangement of theViewOptions to not arranged
               set icon size of theViewOptions to 72
               set background picture of theViewOptions to file ".background:'${backgroundPictureName}'"
               make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
               set position of item "'${applicationName}'" of container window to {100, 100}
               set position of item "Applications" of container window to {375, 100}
               update without registering applications
               delay 5
               close
         end tell
       end tell
    ' | osascript
    
  6. Finialize the DMG by setting permissions properly, compressing and releasing it:

    chmod -Rf go-w /Volumes/"${title}"
    sync
    sync
    hdiutil detach ${device}
    hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}"
    rm -f /pack.temp.dmg 
    

On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.:

..
set position of item "'${applicationName}'" of container window to {100, 100}
set position of item "Applications" of container window to {375, 100}
close
open

How can I make a ComboBox non-editable in .NET?

To add a Visual Studio GUI reference, you can find the DropDownStyle options under the Properties of the selected ComboBox:

enter image description here

Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent(), like so:

this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

How can I sort a std::map first by value, then by key?

EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.

"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"

The most obvious approach is to loop through twice. On the first pass, order the values:

if(current_value > examined_value)
{
    current_value = examined_value
    (and then swap them, however you like)
}

Then on the second pass, alphabetize the words, but only if their values match.

if(current_value == examined_value)
{
    (alphabetize the two)
}

Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.

There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.

How to execute UNION without sorting? (SQL)

select T.Col1, T.Col2, T.Sort
from 
    (
      select T.Col1,
             T.Col2,
             T.Sort,
             rank() over(partition by T.Col1, T.Col2 order by T.Sort) as rn
      from
          (
            select Col1, Col2, 1 as Sort
            from Table1
            union all
            select Col1, Col2, 2
            from Table2
          ) as T
    ) as T
where T.rn = 1    
order by T.Sort

Vim delete blank lines

I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?

Here's the easiest one that I found that works on Vim in Windows 7:

:v/\S/d

Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

How to change an application icon programmatically in Android?

Programatically, you may want to publish the application launcher yourself :

Note: this method no longer works starting with Android 8.0 - Oreo

In your AndroidManifest.xml, add :

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

Then you need create your app launcher intent:

Intent myLauncherIntent = new Intent();
myLauncherIntent.setClassName("your.package.name", "YourLauncherActivityName");
myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Create an install shortcut intent with your app launcher and custom icon:

Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myLauncherIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Application Name");
intent.putExtra
       (
        Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
        Intent.ShortcutIconResource.fromContext
                                    (
                                         getApplicationContext(), 
                                         R.drawable.app_icon
                                    )
       );
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

And finally launch the broadcast intent:

getApplicationContext().sendBroadcast(intent);

Pass variables to Ruby script via command line

tl;dr

I know this is old, but getoptlong wasn't mentioned here and it's probably the best way to parse command line arguments today.


Parsing command line arguments

I strongly recommend getoptlong. It's pretty easy to use and works like a charm. Here is an example extracted from the link above

require 'getoptlong'

opts = GetoptLong.new(
    [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
    [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
    case opt
        when '--help'
            puts <<-EOF
hello [OPTION] ... DIR

-h, --help:
     show help

--repeat x, -n x:
     repeat x times

--name [name]:
     greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
            EOF
        when '--repeat'
            repetitions = arg.to_i
        when '--name'
            if arg == ''
                name = 'John'
            else
                name = arg
            end
    end
end

if ARGV.length != 1
    puts "Missing dir argument (try --help)"
    exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
    print "Hello"
    if name
        print ", #{name}"
    end
    puts
end

You can call it like this ruby hello.rb -n 6 --name -- /tmp

What OP is trying to do

In this case I think the best option is to use YAML files as suggested in this answer