Programs & Examples On #Xmpppy

xmpppy is a Python library that provides support for the XMPP protocol (Jabber).

String replace a Backslash

To Replace backslash at particular location:

if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
    stringValue=stringValue.substring(0,location-1);
}

Sending a JSON to server and retrieving a JSON in return, without JQuery

Using new api fetch:

_x000D_
_x000D_
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
_x000D_
_x000D_
_x000D_ You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Move seaborn plot legend to a different position?

Check out the docs here: https://matplotlib.org/users/legend_guide.html#legend-location

adding this simply worked to bring legend out of the plot:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Dump all tables in CSV format using 'mysqldump'

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

"id","login","password","folder","email" "8","mariana","xxxxxxxxxx","mariana","" "3","squaredesign","xxxxxxxxxxxxxxxxx","squaredesign","[email protected]" "4","miedziak","xxxxxxxxxx","miedziak","[email protected]" "5","Sarko","xxxxxxxxx","Sarko","" "6","Logitrans Poland","xxxxxxxxxxxxxx","LogitransPoland","" "7","Amos","xxxxxxxxxxxxxxxxxxxx","Amos","" "9","Annabelle","xxxxxxxxxxxxxxxx","Annabelle","" "11","Brandfathers and Sons","xxxxxxxxxxxxxxxxx","BrandfathersAndSons","" "12","Imagine Group","xxxxxxxxxxxxxxxx","ImagineGroup","" "13","EduSquare.pl","xxxxxxxxxxxxxxxxx","EduSquare.pl","" "101","tmp","xxxxxxxxxxxxxxxxxxxxx","_","[email protected]"

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it's only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

How to download and save an image in Android

Try this

 try
                {
                    Bitmap bmp = null;
                    URL url = new URL("Your_URL");
                    URLConnection conn = url.openConnection();
                    bmp = BitmapFactory.decodeStream(conn.getInputStream());
                    File f = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
                    if(f.exists())
                        f.delete();
                    f.createNewFile();
                    Bitmap bitmap = bmp;
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                    byte[] bitmapdata = bos.toByteArray();
                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write(bitmapdata);
                    fos.flush();
                    fos.close();
                    Log.e(TAG, "imagepath: "+f );
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

How do I make a MySQL database run completely in memory?

"How do I do that? I explored PHPMyAdmin, and I can't find a "change engine" functionality."

In direct response to this part of your question, you can issue an ALTER TABLE tbl engine=InnoDB; and it'll recreate the table in the proper engine.

How can I find matching values in two arrays?

Done as a answer so I can do formatting...

This is the the process you need to go through. Looping through an array for the specifics.

create an empty array
loop through array1, element by element. {
  loop through array2, element by element {
    if array1.element == array2.element {
      add to your new array
    }
  }
}

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

Node.js getaddrinfo ENOTFOUND

  var http=require('http');
   http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', function(res){
        var str = '';
        console.log('Response is '+res.statusCode);

        res.on('data', function (chunk) {
               str += chunk;
         });

        res.on('end', function () {
             console.log(str);
        });

  });

Get last 5 characters in a string

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

How to close a JavaFX application on window close?

For me only following is working:

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {

        Platform.exit();

        Thread start = new Thread(new Runnable() {
            @Override
            public void run() {
                //TODO Auto-generated method stub
                system.exit(0);     
            }
        });

        start.start();
    }
});

Capture keyboardinterrupt in Python without try-except

I know this is an old question but I came here first and then discovered the atexit module. I do not know about its cross-platform track record or a full list of caveats yet, but so far it is exactly what I was looking for in trying to handle post-KeyboardInterrupt cleanup on Linux. Just wanted to throw in another way of approaching the problem.

I want to do post-exit clean-up in the context of Fabric operations, so wrapping everything in try/except wasn't an option for me either. I feel like atexit may be a good fit in such a situation, where your code is not at the top level of control flow.

atexit is very capable and readable out of the box, for example:

import atexit

def goodbye():
    print "You are now leaving the Python sector."

atexit.register(goodbye)

You can also use it as a decorator (as of 2.6; this example is from the docs):

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

If you wanted to make it specific to KeyboardInterrupt only, another person's answer to this question is probably better.

But note that the atexit module is only ~70 lines of code and it would not be hard to create a similar version that treats exceptions differently, for example passing the exceptions as arguments to the callback functions. (The limitation of atexit that would warrant a modified version: currently I can't conceive of a way for the exit-callback-functions to know about the exceptions; the atexit handler catches the exception, calls your callback(s), then re-raises that exception. But you could do this differently.)

For more info see:

Span inside anchor or anchor inside span or doesn't matter?

It is perfectly valid (at least by HTML 4.01 and XHTML 1.0 standards) to nest either a <span> inside an <a> or an <a> inside a <span>.

Just to prove it to yourself, you can always check it out an the W3C MarkUp Validation Service

I tried validating:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
       <p>
         <a href="http://www.google.com/"><span>Google</span></a>
       </p>
    </body>
  </html>

And also the same as above, but with the <a> inside the <span>

i.e.

<span><a href="http://www.google.com">Google</a></span>

with both HTML 4.01 and XHTML 1.0 doctypes, and both passed validation successfully!

Only thing to be aware of is to ensure that you close the tags in the correct order. So if you start with a <span> then an <a>, make sure you close the <a> tag first before closing the <span> and vice-versa.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):

netsh wlan set hostednetwork mode=allow ssid=tests key=tests123

netsh wlan start hostednetwork

Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)

Then right click on the lan connection (internet connection that you are using), properties.

Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"

This done, your connection is ready to use!

difference between css height : 100% vs height : auto

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

Integer division: How do you produce a double?

just use this.

int fxd=1;
double percent= (double)(fxd*40)/100;

Rounding to 2 decimal places in SQL

you may try the TO_CHAR function to convert the result

e.g.

SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL

SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL

Hope it helps

How do I resolve "Run-time error '429': ActiveX component can't create object"?

I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:

       $.ajax({
            traditional: true,
            url: "/Conroller/MethodTest",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify( 
               [
                { id: 1, color: 'yellow' },
                { id: 2, color: 'blue' },
                { id: 3, color: 'red' }
                ]),
            success: function (data) {
                $scope.DisplayError(data.requestStatus);
            }
        });

Controler

public class Thing
{
    public int id { get; set; }
    public string color { get; set; }
}

public JsonResult MethodTest(IEnumerable<Thing> datav)
    {
   //now  datav is having all your values
  }

How to Lock the data in a cell in excel using vba

Let's say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:

Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

In another case if you already have a protected sheet then follow below code:

ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

How can I make an EXE file from a Python program?

py2exe:

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

Android SharedPreferences in Fragment

It is possible to get a context from within a Fragment

Just do

public class YourFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
        // get context here
        Context context = getContext();
        // do as you please with the context


        // if you decide to go with second option
        SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
        Context context = homeViewModel.getContext();
        // do as you please with the context
        return root;
    }
}

You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

public class SomeViewModel extends AndroidViewModel {

    private MutableLiveData<ArrayList<String>> someMutableData;
    Context context;

    public SomeViewModel(Application application) {
        super(application);
        context = getApplication().getApplicationContext();
        someMutableData = new MutableLiveData<>();
        .
        .
     }

     public Context getContext() {
         return context
     }
  }

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Personal preference is to use Ignore over SilentlyContinue here because it's not an error at all. Since we're expecting it to potentially be $false let's prevent it (with Ignore) from being put (albeit silently) in the $Error stack.

You can use:

if (Get-Variable 'foo' -Scope 'Global' -ErrorAction 'Ignore') {
    $true
} else {
    $false
}

More tersely:

[bool](gv foo -s global -ea ig)

Output of either:

False

Alternatively

You can trap the error that is raised when the variable doesn't exist.

try {
    Get-Variable foo -Scope Global -ErrorAction 'Stop'
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Warning $_
}

Outputs:

WARNING: Cannot find a variable with the name 'foo'.

How can I check if a Perl array contains a particular value?

There are two ways you can do this. You can use the throw the values into a hash for a lookup table, as suggested by the other posts. ( I'll add just another idiom. )

my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;

But if it's data of mostly word characters and not too many meta, you can dump it into a regex alternation:

use English qw<$LIST_SEPARATOR>;

my $regex_str = do { 
    local $LIST_SEPARATOR = '|';
    "(?:@bad_params)";
 };

 # $front_delim and $back_delim being any characters that come before and after. 
 my $regex = qr/$front_delim$regex_str$back_delim/;

This solution would have to be tuned for the types of "bad values" you're looking for. And again, it might be totally inappropriate for certain types of strings, so caveat emptor.

Getting an "ambiguous redirect" error

Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}" (using quotes).

(You may also want to consider renaming your variable to ${OUTPUT_RESULTS})

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

How can I add an item to a IEnumerable<T> collection?

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

 items = items.Concat(new[] { "foo" });

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

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

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

cat /proc/driver/nvidia/version

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

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

How to make a dropdown readonly using jquery?

This is what you are looking for:

$('#cf_1268591').attr("style", "pointer-events: none;");

Works like a charm.

Get cart item name, quantity all details woocommerce

Most of the time you want to get the IDs of the products in the cart so that you can make some comparison with some other logic - example settings in the backend.

In such a case you can extend the answer from @Rohil_PHPBeginner and return the IDs in an array as follows :

<?php 

    function njengah_get_ids_of_products_in_cart(){
    
            global $woocommerce;
    
            $productsInCart = array(); 
            
            $items = $woocommerce->cart->get_cart(); 
            
            foreach($items as $item => $values) { 
            
                $_product =  wc_get_product( $values['data']->get_id()); 
                
               /* Display Cart Items Content  */ 
               
                echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
                $price = get_post_meta($values['product_id'] , '_price', true);
                echo "  Price: ".$price."<br>";
                
                /**Get IDs and in put them in an  Array**/ 
                
                $productsInCart_Ids[] =  $_product->get_id();
            }
           
           /** To Display **/ 
              
           print_r($productsInCart_Ids);
           
           /**To Return for Comparision with some Other Logic**/ 
           
           return $productsInCart_Ids; 
    
        }

Redirecting from HTTP to HTTPS with PHP

This is a good way to do it:

<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || 
   $_SERVER['HTTPS'] == 1) ||  
   isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
   $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}
?>

Laravel Update Query

Try doing it like this.

User::where('email', $userEmail)
       ->update([
           'member_type' => $plan
        ]);

How do I make a text go onto the next line if it overflows?

word-wrap: break-word; 

add this to your container that should do the trick

How to combine multiple inline style objects?

To Expand on what @PythonIsGreat said, I create a global function that will do it for me:

var css = function(){
    var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
    return $.extend.apply(null, args);
}

This deeply extends the objects into a new object and allows for a variable number of objects as parameters. This allows you to do something like this:

return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);

var styles = {
  base:{
    //whatever
  },
  first:{
    //whatever
  },
  second:{
    //whatever
  }
}

Convert an array to string

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

What is the best way to declare global variable in Vue.js?

I strongly recommend taking a look at Vuex, it is made for globally accessible data in Vue.

If you only need a few base variables that will never be modified, I would use ES6 imports:

// config.js
export default {
   hostname: 'myhostname'
}

// .vue file
import config from 'config.js'

console.log(config.hostname)

You could also import a json file in the same way, which can be edited by people without code knowledge or imported into SASS.

Changing the highlight color when selecting text in an HTML text input

this is the code.

/*** Works on common browsers ***/
::selection {
    background-color: #352e7e;
    color: #fff;
}

/*** Mozilla based browsers ***/
::-moz-selection {
    background-color: #352e7e;
    color: #fff;
}

/***For Other Browsers ***/
::-o-selection {
    background-color: #352e7e;
    color: #fff;
}

::-ms-selection {
    background-color: #352e7e;
    color: #fff;
}

/*** For Webkit ***/
::-webkit-selection {
    background-color: #352e7e;
    color: #fff;
}

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How do I kill background processes / jobs when my shell script exits?

To be on the safe side I find it better to define a cleanup function and call it from trap:

cleanup() {
        local pids=$(jobs -pr)
        [ -n "$pids" ] && kill $pids
}
trap "cleanup" INT QUIT TERM EXIT [...]

or avoiding the function altogether:

trap '[ -n "$(jobs -pr)" ] && kill $(jobs -pr)' INT QUIT TERM EXIT [...]

Why? Because by simply using trap 'kill $(jobs -pr)' [...] one assumes that there will be background jobs running when the trap condition is signalled. When there are no jobs one will see the following (or similar) message:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

because jobs -pr is empty - I ended in that 'trap' (pun intended).

how to set auto increment column with sql developer

How to do it with Oracle SQL Developer: In the Left pane, under the connections you will find "Sequences", right click and select create a new sequence from the context sensitive pop up. Fill out the details: Schema name, sequence_name, properties(start with value, min value, max value, increment value etc.) and click ok. Assuming that you have a table with a key that uses this auto_increment, while inserting in this table just give "your_sequence_name.nextval" in the field that utilizes this property. I guess this should help! :)

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Toggle input disabled attribute using jQuery

Another simple option that updates on a click of the checkbox.

HTML:

<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>

jQuery:

$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   
    }
});

In action: link

When is the init() function run?

mutil init function in one package execute order:

  1. const and variable defined file init() function execute

  2. init function execute order by the filename asc

Javascript seconds to minutes and seconds

A one liner (doesnt work with hours):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }

JavaScript Array splice vs slice

_x000D_
_x000D_
//splice_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
_x000D_
//slice_x000D_
var array2=[1,2,3,4,5]_x000D_
console.log(array2.slice(2));_x000D_
_x000D_
_x000D_
console.log("----after-----");_x000D_
console.log(array);_x000D_
console.log(array2);
_x000D_
_x000D_
_x000D_

Get absolute path of initially run script

dirname(__FILE__) 

will give the absolute route of the current file from which you are demanding the route, the route of your server directory.

example files :

www/http/html/index.php ; if you place this code inside your index.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/

www/http/html/class/myclass.php ; if you place this code inside your myclass.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/class/

How to use SharedPreferences in Android to store, fetch and edit values

There are many ways people recommend how to use SharedPreferences. I have made a demo project here. Key point in sample is to use ApplicationContext & single sharedpreferences object. This demonstrates how to use SharedPreferences with following features:-

  • Using singelton class to access/update SharedPreferences
  • No need to pass context always for read/write SharedPreferences
  • It uses apply() instead of commit()
  • apply() is asynchronus save, doesn't return anything, it update value in memory first & changes are written to disk later asynchronusly.
  • commit() is synchronus save, it return true/false based on outcome. Changes are written to disk synchronusly
  • works on android 2.3+ versions

Usage example as below:-

MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();

Get source code here & Detailed API's can be found here on developer.android.com

How does the @property decorator work in Python?

This point is been cleared by many people up there but here is a direct point which I was searching. This is what I feel is important to start with the @property decorator. eg:-

class UtilityMixin():
    @property
    def get_config(self):
        return "This is property"

The calling of function "get_config()" will work like this.

util = UtilityMixin()
print(util.get_config)

If you notice I have not used "()" brackets for calling the function. This is the basic thing which I was searching for the @property decorator. So that you can use your function just like a variable.

MySQL SELECT last few days?

You could use a combination of the UNIX_TIMESTAMP() function to do that.

SELECT ... FROM ... WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(thefield) < 259200

C#: how to get first char of a string?

MyString.Remove(1, 2); also works

Why is the GETDATE() an invalid identifier

SYSDATE and GETDATE perform identically.

SYSDATE is compatible with Oracle syntax, and GETDATE is compatible with Microsoft SQL Server syntax.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

Unzipping files in Python

try this :


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

path : unzip file's path

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

editing PATH variable on mac

You could try this:

  1. Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
  2. Type the following: echo 'export PATH=YOURPATHHERE:$PATH' >> ~/.profile, replacing "YOURPATHHERE" with the name of the directory you want to add. Make certain that you use ">>" instead of one ">".
  3. Hit Enter.
  4. Close the Terminal and reopen. Your new Terminal session should now use the new PATH.

-> http://keito.me/tutorials/macosx_path

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Simple 3x3 matrix inverse code (C++)

I have just created a QMatrix class. It uses the built in vector > container. QMatrix.h It uses the Jordan-Gauss method to compute the inverse of a square matrix.

You can use it as follows:

#include "QMatrix.h"
#include <iostream>

int main(){
QMatrix<double> A(3,3,true);
QMatrix<double> Result = A.inverse()*A; //should give the idendity matrix

std::cout<<A.inverse()<<std::endl;
std::cout<<Result<<std::endl; // for checking
return 0;
}

The inverse function is implemented as follows:

Given a class with the following fields:

template<class T> class QMatrix{
public:
int rows, cols;
std::vector<std::vector<T> > A;

the inverse() function:

template<class T> 
QMatrix<T> QMatrix<T>:: inverse(){
Identity<T> Id(rows); //the Identity Matrix as a subclass of QMatrix.
QMatrix<T> Result = *this; // making a copy and transforming it to the Identity matrix
T epsilon = 0.000001;
for(int i=0;i<rows;++i){
    //check if Result(i,i)==0, if true, switch the row with another

    for(int j=i;j<rows;++j){
        if(std::abs(Result(j,j))<epsilon) { //uses Overloading()(int int) to extract element from Result Matrix
            Result.replace_rows(i,j+1); //switches rows i with j+1
        }
        else break;
    }
    // main part, making a triangular matrix
    Id(i)=Id(i)*(1.0/Result(i,i));
    Result(i)=Result(i)*(1.0/Result(i,i));  // Using overloading ()(int) to get a row form the matrix
    for(int j=i+1;j<rows;++j){
        T temp = Result(j,i);
        Result(j) = Result(j) - Result(i)*temp;
        Id(j) = Id(j) - Id(i)*temp; //doing the same operations to the identity matrix
        Result(j,i)=0; //not necessary, but looks nicer than 10^-15
    }
}

// solving a triangular matrix 
for(int i=rows-1;i>0;--i){
    for(int j=i-1;j>=0;--j){
        T temp = Result(j,i);
        Id(j) = Id(j) - temp*Id(i);
        Result(j)=Result(j)-temp*Result(i);
    }
}

return Id;
}

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

How to insert array of data into mysql using php

I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation

DB::create($db, 'YOUR_TABLE_NAME', $dataArray);

where $db is your Database connection.

Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud

Can I use a case/switch statement with two variables?

Languages like scala&python give to you very powerful stuff like patternMatching, unfortunately this is still a missing-feature in Java...

but there is a solution (which I don't like in most of the cases), you can do something like this:

final int s1Value = 0;
final int s2Value = 0;
final String s1 = "a";
final String s2 = "g";

switch (s1 + s2 + s1Value + s2Value){
    case "ag00": return true;
    default: return false;
}

JavaScript: Class.method vs. Class.prototype.method

A. Static Method:

      Class.method = function () { /* code */ }
  1. method() here is a function property added to an another function (here Class).
  2. You can directly access the method() by the class / function name. Class.method();
  3. No need for creating any object/instance (new Class()) for accessing the method(). So you could call it as a static method.

B. Prototype Method (Shared across all the instances):

     Class.prototype.method = function () { /* code using this.values */ }
  1. method() here is a function property added to an another function protype (here Class.prototype).
  2. You can either directly access by class name or by an object/instance (new Class()).
  3. Added advantage - this way of method() definition will create only one copy of method() in the memory and will be shared across all the object's/instance's created from the Class

C. Class Method (Each instance has its own copy):

   function Class () {
      this.method = function () { /* do something with the private members */};
   }
  1. method() here is a method defined inside an another function (here Class).
  2. You can't directly access the method() by the class / function name. Class.method();
  3. You need to create an object/instance (new Class()) for the method() access.
  4. This way of method() definition will create a unique copy of the method() for each and every objects created using the constructor function (new Class()).
  5. Added advantage - Bcos of the method() scope it has the full right to access the local members(also called private members) declared inside the constructor function (here Class)

Example:

    function Class() {
        var str = "Constructor method"; // private variable
        this.method = function () { console.log(str); };
    }
    Class.prototype.method = function() { console.log("Prototype method"); };
    Class.method = function() { console.log("Static method"); };

    new Class().method();     // Constructor method
    // Bcos Constructor method() has more priority over the Prototype method()

    // Bcos of the existence of the Constructor method(), the Prototype method 
    // will not be looked up. But you call it by explicity, if you want.
    // Using instance
    new Class().constructor.prototype.method(); // Prototype method

    // Using class name
    Class.prototype.method(); // Prototype method

    // Access the static method by class name
    Class.method();           // Static method

Disable mouse scroll wheel zoom on embedded Google Maps

Add this to your script:

function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: uluru,
        scrollwheel: false,
        disableDefaultUI: true,
        disableDoubleClickZoom: true
    });
    var marker = new google.maps.Marker({
        position: uluru,
        map: map
});
}

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was doing what doug suggests ("Reset Content and Settings") which works but takes a lot of time and it is really annoying... until I recently found completely accidental another solution that is much quicker and seems to also work so far! Just hit cmd+L on your simulator or go to the simulator menu "Hardware -> Lock", which locks the screen, when you unlock the screen the app works like nothing ever happened :)

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

How to add a second css class with a conditional value in razor MVC 4

I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:

Your answer (assuming this works, I haven't tried this):

<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">

Second option:

@if (Model.Details.Count > 0) {
    <div class="details show">
}
else {
    <div class="details hide">
}

Third option:

<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

docker error: /var/run/docker.sock: no such file or directory

I also got this error. Though, I did not use boot2docker but just installed "plain" docker on Ubuntu (see https://docs.docker.com/installation/ubuntulinux/).

I got the error ("dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?") because the docker daemon was not running, yet.

On Ubuntu, you need to start the service:

sudo service docker start

See also http://blog.arungupta.me/resolve-dial-unix-docker-sock-error-techtip64

How to Implement Custom Table View Section Headers and Footers with Storyboard

Here is @Vitaliy Gozhenko's answer, in Swift.
To summarize you will create a UITableViewHeaderFooterView that contains a UITableViewCell. This UITableViewCell will be "dequeuable" and you can design it in your storyboard.

  1. Create a UITableViewHeaderFooterView class

    class CustomHeaderFooterView: UITableViewHeaderFooterView {
    var cell : UITableViewCell? {
        willSet {
            cell?.removeFromSuperview()
        }
        didSet {
            if let cell = cell {
                cell.frame = self.bounds
                cell.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
                self.contentView.backgroundColor = UIColor .clearColor()
                self.contentView .addSubview(cell)
            }
        }
    }
    
  2. Plug your tableview with this class in your viewDidLoad function:

    self.tableView.registerClass(CustomHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "SECTION_ID")
    
  3. When asking, for a section header, dequeue a CustomHeaderFooterView, and insert a cell into it

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier("SECTION_ID") as! CustomHeaderFooterView
        if view.cell == nil {
            let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell")
            view.cell = cell;
        }
    
        // Fill the cell with data here
    
        return view;
    }
    

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

getting file size in javascript

You can't get the file size of local files with javascript in a standard way using a web browser.

But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver

How to clone ArrayList and also clone its contents?

List<Dog> dogs;
List<Dog> copiedDogs = dogs.stream().map(dog -> SerializationUtils.clone(dog)).Collectors.toList());

This will deep copy each dog

How do I connect to a specific Wi-Fi network in Android programmatically?

I broke my head to understand why your answers for WPA/WPA2 don't work...after hours of tries I found what you are missing:

conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

is REQUIRED for WPA networks!!!!

Now, it works :)

How to get the EXIF data from a file using C#

Getting EXIF data from a JPEG image involves:

  1. Seeking to the JPEG markers which mentions the beginning of the EXIF data,. e.g. normally oxFFE1 is the marker inserted while encoding EXIF data, which is a APPlication segment, where EXIF data goes.
  2. Parse all the data from say 0xFFE1 to 0xFFE2 . This data would be stream of bytes, in the JPEG encoded file.
  3. ASCII equivalent of these bytes would contain various information related to Image Date, Camera Model Name, Exposure etc...

Printing tuple with string formatting in Python

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Delete topic in Kafka 0.8.1.1

bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>

How to get ID of the last updated row in MySQL?

Query :

$sqlQuery = "UPDATE 
            update_table 
        SET 
            set_name = 'value' 
        WHERE 
            where_name = 'name'
        LIMIT 1;";

PHP function:

function updateAndGetId($sqlQuery)
{
    mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
    return mysql_insert_id();
}

It's work for me ;)

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

Should I use px or rem value units in my CSS?

As a reflex answer, I would recommend using rem, because it allows you to change the "zoom level" of the whole document at once, if necessary. In some cases, when you want the size to be relative to the parent element, then use em.

But rem support is spotty, IE8 needs a polyfill, and Webkit is exhibiting a bug. Moreover, sub-pixel calculation can cause things such as one pixel lines to sometimes disappear. The remedy is to code in pixels for such very small elements. That introduces even more complexity.

So, overall, ask yourself whether it's worth it - how important and likely it is that you change the "zoom level" of the whole document within CSS?

For some cases it's yes, for some cases it'll be no.

So, it depends on your needs, and you have to weight pros and cons, because using rem and em introduces some additional considerations in comparison to the "normal" pixel-based workflow.

Keep in mind that it's easy to switch (or rather convert) your CSS from px to rem (JavaScript is another story), because the following two blocks of CSS code would produce the same result:

html {
}

body {
  font-size:14px;
}

.someElement {
  width: 12px;
}

html {
  font-size:1px;
}

body {
  font-size:14rem;
}

.someElement {
  width: 12rem;
}

Can you change what a symlink points to after it is created?

Just in case it helps: there is a way to edit a symlink with midnight commander (mc). The menu command is (in French on my mc interface):

Fichier / Éditer le lien symbolique

which may be translated to:

File / Edit symbolic link

The shortcut is C-x C-s

Maybe it internally uses the ln --force command, I don't know.

Now, I'm trying to find a way to edit a whole lot of symlinks at once (that's how I arrived here).

How would you do a "not in" query with LINQ?

Example using List of int for simplicity.

List<int> list1 = new List<int>();
// fill data
List<int> list2 = new List<int>();
// fill data

var results = from i in list1
              where !list2.Contains(i)
              select i;

foreach (var result in results)
    Console.WriteLine(result.ToString());

Sorting HTML table with JavaScript

I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?

function column_sort() {
    getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();

    comparer = (idx, asc) => (a, b) => ((v1, v2) => 
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    
    table = $(this).closest('table')[0];
    tbody = $(table).find('tbody')[0];

    elm = $(this)[0];
    children = elm.parentNode.children;
    Array.from(tbody.querySelectorAll('tr')).sort( comparer(
        Array.from(children).indexOf(elm), table.asc = !table.asc))
        .forEach(tr => tbody.appendChild(tr) );
}

table.find('thead th').on('click', column_sort);

Format output string, right alignment

You can align it like that:

print('{:>8} {:>8} {:>8}'.format(*words))

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).

How to automatically generate unique id in SQL like UID12345678?

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Getting file names without extensions

As an additional answer (or to compound on the existing answers) you could write an extension method to accomplish this for you within the DirectoryInfo class. Here is a sample that I wrote fairly quickly that could be embellished to provide directory names or other criteria for modification, etc:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DocumentDistributor.Library
{
    public static class myExtensions
    {
        public static string[] GetFileNamesWithoutFileExtensions(this DirectoryInfo di)
        {
            FileInfo[] fi = di.GetFiles();
            List<string> returnValue = new List<string>();

            for (int i = 0; i < fi.Length; i++)
            {
                returnValue.Add(Path.GetFileNameWithoutExtension(fi[i].FullName)); 
            }

            return returnValue.ToArray<string>();
         }
    }
}

Edit: I also think this method could probably be simplified or awesome-ified if it used LINQ to achieve the construction of the array, but I don't have the experience in LINQ to do it quickly enough for a sample of this kind.

Edit 2 (almost 4 years later): Here is the LINQ-ified method I would use:

public static class myExtensions
{
    public static IEnumerable<string> GetFileNamesWithoutExtensions(this DirectoryInfo di)
    {
        return di.GetFiles()
            .Select(x => Path.GetFileNameWithoutExtension(x.FullName));
    }
}

How to download all dependencies and packages to directory

# aptitude clean
# aptitude --download-only install <your_package_here>
# cp /var/cache/apt/archives/*.deb <your_directory_here>

Which ORM should I use for Node.js and MySQL?

One major difference between Sequelize and Persistence.js is that the former supports a STRING datatype, i.e. VARCHAR(255). I felt really uncomfortable making everything TEXT.

SQL Server Insert if not exists

Try below code

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   INSERT INTO EmailsRecebidos (De, Assunto, Data)
   select @_DE, @_ASSUNTO, @_DATA
   EXCEPT
   SELECT De, Assunto, Data from EmailsRecebidos
END

How to install Intellij IDEA on Ubuntu?

JetBrains has a new application called the Toolbox App which quickly and easily installs any JetBrains software you want, assuming you have the license. It also manages your login once to apply across all JetBrains software, a very useful feature.

To use it, download the tar.gz file here, then extract it and run the included executable jetbrains-toolbox. Then sign in, and press install next to IntelliJ IDEA:

enter image description here

If you want to move the executable to /usr/bin/ feel free, however it works fine out of the box wherever you extract it to.

This will also make the appropriate desktop entries upon install.

How to use nan and inf in C?

Here is a simple way to define those constants, and I'm pretty sure it's portable:

const double inf = 1.0/0.0;
const double nan = 0.0/0.0;

When I run this code:

printf("inf  = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan  = %f\n", nan);
printf("-nan = %f\n", -nan);

I get:

inf  = inf
-inf = -inf
nan  = -nan
-nan = nan

How to use MD5 in javascript to transmit a password

In response to jt. You are correct, the HTML with just the password is susceptible to the Man in the middle attack. However, you can seed it with a GUID from the server ...

$.post(
  'includes/login.php', 
  { user: username, pass: $.md5(password + GUID) },
   onLogin, 
  'json' );

This would defeat the Man-In-The middle ... in that the server would generate a new GUID for each attempt.

Benefits of using the conditional ?: (ternary) operator

A really cool usage is:

x = foo ? 1 :
    bar ? 2 :
    baz ? 3 :
          4;

Rendering HTML inside textarea

This is possible with <textarea> the only thing you need to do is use Summernote WYSIWYG editor

it interprets HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>)

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

Plotting histograms from grouped data in a pandas DataFrame

One solution is to use matplotlib histogram directly on each grouped data frame. You can loop through the groups obtained in a loop. Each group is a dataframe. And you can create a histogram for each one.

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')

for group in grouped:
  figure()
  matplotlib.pyplot.hist(group[1].N)
  show()

How to get the type of T from a member of a generic class or method?

If you want to know a property's underlying type, try this:

propInfo.PropertyType.UnderlyingSystemType.GenericTypeArguments[0]

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

Wget output document and headers to STDOUT

Try the following, no extra headers

wget -qO- www.google.com

Note the trailing -. This is part of the normal command argument for -O to cat out to a file, but since we don't use > to direct to a file, it goes out to the shell. You can use -qO- or -qO -.

split string only on first instance of specified character

This should be quite fast

function splitOnFirst (str, sep) {
  const index = str.indexOf(sep);
  return index < 0 ? [str] : [str.slice(0, index), str.slice(index + sep.length)];
}

Programmatically create a UIView with color gradient

Swift 4:

Shows gradient in IB correctly:

@IBDesignable public class GradientView: UIView {

    override open class var layerClass: AnyClass {
        return CAGradientLayer.classForCoder()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureGradientLayer()
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        configureGradientLayer()
    }

    func configureGradientLayer() {
        let gradientLayer = layer as! CAGradientLayer
        gradientLayer.colors = [UIColor(hex: 0x003399).cgColor, UIColor(hex: 0x00297b).cgColor]
    }
}

Convert pandas dataframe to NumPy array

You can use the to_records method, but have to play around a bit with the dtypes if they are not what you want from the get go. In my case, having copied your DF from a string, the index type is string (represented by an object dtype in pandas):

In [102]: df
Out[102]: 
label    A    B    C
ID                  
1      NaN  0.2  NaN
2      NaN  NaN  0.5
3      NaN  0.2  0.5
4      0.1  0.2  NaN
5      0.1  0.2  0.5
6      0.1  NaN  0.5
7      0.1  NaN  NaN

In [103]: df.index.dtype
Out[103]: dtype('object')
In [104]: df.to_records()
Out[104]: 
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
In [106]: df.to_records().dtype
Out[106]: dtype([('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Converting the recarray dtype does not work for me, but one can do this in Pandas already:

In [109]: df.index = df.index.astype('i8')
In [111]: df.to_records().view([('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Out[111]:
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Note that Pandas does not set the name of the index properly (to ID) in the exported record array (a bug?), so we profit from the type conversion to also correct for that.

At the moment Pandas has only 8-byte integers, i8, and floats, f8 (see this issue).

How to read a specific line using the specific line number from a file in Java?

It works for me: I have combined the answer of Reading a simple text file

But instead of return a String I am returning a LinkedList of Strings. Then I can select the line that I want.

public static LinkedList<String> readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
    LinkedList<String>linkedList = new LinkedList<>();
    // do reading, usually loop until end of file reading
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        linkedList.add(mLine);
        sb.append(mLine); // process line
        mLine = reader.readLine();


    }
    reader.close();
    return linkedList;
}

How to send a GET request from PHP?

http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.

$response = http_get("http://www.example.com/file.xml");

Merge PDF files with PHP

i suggest PDFMerger from github.com, so easy like ::

include 'PDFMerger.php';

$pdf = new PDFMerger;

$pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')
    ->addPDF('samplepdfs/two.pdf', '1-2')
    ->addPDF('samplepdfs/three.pdf', 'all')
    ->merge('file', 'samplepdfs/TEST2.pdf'); // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

In git how is fetch different than pull and how is merge different than rebase?

Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.

Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.

I would use git merge when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase is more appropriate. For more details be sure to check out this merge or rebase article.

Convert a negative number to a positive one in JavaScript

My minimal approach

For converting negative number to positive & vice-versa

_x000D_
_x000D_
var num = -24;_x000D_
num -= num*2;_x000D_
console.log(num)_x000D_
// result = 24
_x000D_
_x000D_
_x000D_

Check if a string contains another string

Use the Instr function

Dim pos As Integer

pos = InStr("find the comma, in the string", ",")

will return 15 in pos

If not found it will return 0

If you need to find the comma with an excel formula you can use the =FIND(",";A1) function.

Notice that if you want to use Instr to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare (or just 1 for die-hards).

Dim posOf_A As Integer

posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)

will give you a value of 14.

Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.

Detecting negative numbers

Just multiply the number by -1 and check if the result is positive.

Change output format for MySQL command line results to CSV

I wound up writing my own command-line tool to take care of this. It's similar to cut, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:

$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"

csvmaster on github

Selecting default item from Combobox C#

You can set using SelectedIndex

comboBox1.SelectedIndex= 1;

OR

SelectedItem

comboBox1.SelectedItem = "your value"; // 

The latter won't throw an exception if the value is not available in the combobox

EDIT

If the value to be selected is not specific then you would be better off with this

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

How to get height of Keyboard?

I had to do this. this is a bit of hackery. not suggested.
but i found this very helpful

I made extension and struct

ViewController Extension + Struct

import UIKit
struct viewGlobal{
    static var bottomConstraint : NSLayoutConstraint = NSLayoutConstraint()
}

extension UIViewController{ //keyboardHandler
 func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
 }
 func listenerKeyboard(bottomConstraint: NSLayoutConstraint) {
    viewGlobal.bottomConstraint = bottomConstraint
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
 }
 //Dismiss Keyboard
 @objc func dismissKeyboard() {
    view.endEditing(true)
 }
 @objc func keyboardWillShow(notification:NSNotification) {
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
    UIView.animate(withDuration: 0.5){
        viewGlobal.bottomConstraint.constant = keyboardHeight
    }
 }

 @objc func keyboardWillHide(notification:NSNotification) {
    UIView.animate(withDuration: 0.5){
        viewGlobal.bottomConstraint.constant = 0
    }
 }
}

Usage:
get most bottom constraint

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // default 0

call the function inside viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    hideKeyboardWhenTappedAround()
    listenerKeyboard(bottomConstraint: bottomConstraint)

    // Do any additional setup after loading the view.
}

Hope this help.
-you keyboard will now auto close when user tap outside of textfield and
-it will push all view to above keyboard when keyboard appear.
-you could also used dismissKeyboard() when ever you need it

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

How do you do a limit query in JPQL or HQL?

If can manage a limit in this mode

public List<ExampleModel> listExampleModel() {
    return listExampleModel(null, null);
}

public List<ExampleModel> listExampleModel(Integer first, Integer count) {
    Query tmp = getSession().createQuery("from ExampleModel");

    if (first != null)
        tmp.setFirstResult(first);
    if (count != null)
        tmp.setMaxResults(count);

    return (List<ExampleModel>)tmp.list();
}

This is a really simple code to handle a limit or a list.

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Remove array element based on object property

Using lodash library it is simple as this

_.remove(myArray , { field: 'money' });

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

Remove a specific string from an array of string

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

You'd be better off with a List<String>, e.g. an ArrayList<String>:

List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3

list.remove("apple");
System.out.println(list.size()); // 2

Collections like this are generally much more flexible than working with arrays directly.

EDIT: For removal:

void removeRandomElement(List<?> list, Random random)
{
    int index = random.nextInt(list.size());
    list.remove(index);
}

Linq select object from list depending on objects attribute

Of course!

Use FirstOrDefault() to select the first object which matches the condition:

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Otherwise use Where() to select a subset of your list:

var answers = Answers.Where(a => a.Correct);

Is it possible to declare a public variable in vba and assign a default value?

As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

Here is an example of it:

Public Coordinates(3) as Double
Public Heat as double
Public Weight as double

Sub InitGlobals()
    Coordinates(1)=10.5
    Coordinates(2)=22.54
    Coordinates(3)=-100.5
    Heat=25.5
    Weight=70
End Sub

Sub MyWorkSGoesHere()
    Call InitGlobals
    'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub

Why does my Eclipse keep not responding?

Open your workspace\.metadata\.log file. That will tell you usually what is going wrong.

Convert Pandas Column to DateTime

You can use the DataFrame method .apply() to operate on the values in Mycol:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

Change Screen Orientation programmatically using a Button

Wherever possible, please don't use SCREEN_ORIENTATION_LANDSCAPE or SCREEN_ORIENTATION_PORTRAIT. Instead use:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

These allow the user to orient the device to either landscape orientation, or either portrait orientation, respectively. If you've ever had to play a game with a charging cable being driven into your stomach, then you know exactly why having both orientations available is important to the user.

Note: For phones, at least several that I've checked, it only allows the "right side up" portrait mode, however, SENSOR_PORTRAIT works properly on tablets.

Note: this feature was introduced in API Level 9, so if you must support 8 or lower (not likely at this point), then instead use:

setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

How To limit the number of characters in JTextField?

Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.

This solution will work an any Document, not just a PlainDocument.

This is a more current solution than the one accepted.

ASP.NET Web Site or ASP.NET Web Application?

One of the key differences is that Websites compile dynamically and create on-the-fly assemblies. Web applicaitons compile into one large assembly.

The distinction between the two has been done away with in Visual Studio 2008.

How to hide Soft Keyboard when activity starts

Put this code your java file and pass the argument for object on edittext,

private void setHideSoftKeyboard(EditText editText){
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}

What are the JavaScript KeyCodes?

http://keycodes.atjayjo.com/

This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

How to find whether or not a variable is empty in Bash?

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

How to use QueryPerformanceCounter?

I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;

The example is just as simple:

LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)

where divisor is 10^3, or 10^6 depending on required resolution.

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

subquery in codeigniter active record

I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

$subquery = 'SELECT id_cer FROM revokace';

$this->db->select('*');
$this->db->where_not_in(id, $subquery);
$this->db->from('certs');
$query = $this->db->get();

Delete everything in a MongoDB database

In the mongo shell:

use [database];
db.dropDatabase();

And to remove the users:

db.dropAllUsers();

How do I format a number in Java?

From this thread, there are different ways to do this:

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.

How to Customize a Progress Bar In Android

If you want to do this in code, here is a sample:

pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();

Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.

Create a menu Bar in WPF?

Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):

<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
    <MenuItem Header="_Emulator">
    <MenuItem Header="Load..." Click="MenuItem_Click" />
    <MenuItem Header="Load again" Click="menuEmulLoadLast" />
    <Separator />
    <MenuItem Click="MenuItem_Click">
        <MenuItem.Header>
            <DockPanel>
                <TextBlock>Step</TextBlock>
                <TextBlock Width="10"></TextBlock>
                <TextBlock HorizontalAlignment="Right">F2</TextBlock>
            </DockPanel>
        </MenuItem.Header>
    </MenuItem>
    :

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

Crop image in PHP

imagecopyresampled() will take a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner.

This function can be used to copy regions within the same image. But if the regions overlap, the results will be unpredictable.

- Edit -

If $src_w and $src_h are smaller than $dst_w and $dst_h respectively, thumb image will be zoomed in. Otherwise it will be zoomed out.

<?php
$dst_x = 0;   // X-coordinate of destination point
$dst_y = 0;   // Y-coordinate of destination point
$src_x = 100; // Crop Start X position in original image
$src_y = 100; // Crop Srart Y position in original image
$dst_w = 160; // Thumb width
$dst_h = 120; // Thumb height
$src_w = 260; // Crop end X position in original image
$src_h = 220; // Crop end Y position in original image

// Creating an image with true colors having thumb dimensions (to merge with the original image)
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
// Get original image
$src_image = imagecreatefromjpeg('images/source.jpg');
// Cropping
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
// Saving
imagejpeg($dst_image, 'images/crop.jpg');
?>

How does Facebook Sharer select Images and other metadata when sharing my URL?

This is what worked for me: I placed the desired thumbnail image on the page right after the tag and making it too small to see..

<img src="imagename.jpg" width="1" height="1" />

I have not tested it with height 0 and width 0 but it probably will still work.. This does not guarantee the user will select this image..

ALSO it seems like Facebook caches the thumbnails on your page and doesnt always check it for new ones.. try adding this to another page on your site and you'll see that it works.

How to install php-curl in Ubuntu 16.04

sudo apt-get install php5.6-curl

and restart the web browser.

You can check the modules by running php -m | grep curl

HttpServletRequest - Get query string parameters, no form data

Contrary to what cularis said there can be both in the parameter map.

The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".

Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.

That saves you the parsing and still gives you only URL parameters.

How to import a JSON file in ECMAScript 6?

I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).

Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:

import translationsJSON from './i18n/locale-en';

JavaScript - Use variable in string match

Example. To find number of vowels within the string

var word='Web Development Tutorial';
var vowels='[aeiou]'; 
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);

How to pad a string to a fixed length with spaces in Python?

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str

change type of input field with jQuery

Have you tried using .prop()?

$("#password").prop('type','text');

http://api.jquery.com/prop/

How to redirect the output of a PowerShell to a file during its execution

One possible solution, if your situation allows it:

  1. Rename MyScript.ps1 to TheRealMyScript.ps1
  2. Create a new MyScript.ps1 that looks like:

    .\TheRealMyScript.ps1 > output.txt

What CSS selector can be used to select the first div within another div

The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1> before the <div>s. What I would suggest is that you either add a class to the <div>, like <div class="first"> and then style it that way, or use jQuery if you really can't add a class:

$('#content > div:first')

How to print the values of slices

If you just want to see the values of an array without brackets, you can use a combination of fmt.Sprint() and strings.Trim()

a := []string{"a", "b"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]"))
fmt.Print(a)

Returns:

a b
[a b]

Be aware though that with this solution any leading brackets will be lost from the first value and any trailing brackets will be lost from the last value

a := []string{"[a]", "[b]"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]")
fmt.Print(a)

Returns:

a] [b
[[a] [b]]

For more info see the documentation for strings.Trim()

Setting TIME_WAIT TCP

I have been load testing a server application (on linux) by using a test program with 20 threads.

In 959,000 connect / close cycles I had 44,000 failed connections and many thousands of sockets in TIME_WAIT.

I set SO_LINGER to 0 before the close call and in subsequent runs of the test program had no connect failures and less than 20 sockets in TIME_WAIT.

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{item.name}}
  </option>
</select>

byId(item1: ItemModel, item2: ItemModel) {
  return item1.id === item2.id;
}

Some tutorial here

Python Socket Receive Large Amount of Data

You can use it as: data = recvall(sock)

def recvall(sock):
    BUFF_SIZE = 4096 # 4 KiB
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            # either 0 or end of data
            break
    return data

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

Is string in array?

You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

Nth word in a string variable

STRING=(one two three four)
echo "${STRING[n]}"

Allowed characters in filename

For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.

$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);

Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.

What is the regex for "Any positive integer, excluding 0"

My pattern is complicated, but it covers exactly "Any positive integer, excluding 0" (1 - 2147483647, not long). It's for decimal numbers and doesn't allow leading zeros.

^((1?[1-9][0-9]{0,8})|20[0-9]{8}|(21[0-3][0-9]{7})|(214[0-6][0-9]{6})
|(2147[0-3][0-9]{5})|(21474[0-7][0-9]{4})|(214748[0-2][0-9]{3})
|(2147483[0-5][0-9]{2})|(21474836[0-3][0-9])|(214748364[0-7]))$

Difference between \b and \B in regex

With a different example:

Consider this is the string and pattern to be searched for is 'cat':

text = "catmania thiscat thiscatmaina";

Now definitions,

'\b' finds/matches the pattern at the beginning or end of each word.

'\B' does not find/match the pattern at the beginning or end of each word.

Different Cases:

Case 1: At the beginning of each word

result = text.replace(/\bcat/g, "ct");

Now, result is "ctmania thiscat thiscatmaina"

Case 2: At the end of each word

result = text.replace(/cat\b/g, "ct");

Now, result is "catmania thisct thiscatmaina"

Case 3: Not in the beginning

result = text.replace(/\Bcat/g, "ct");

Now, result is "catmania thisct thisctmaina"

Case 4: Not in the end

result = text.replace(/cat\B/g, "ct");

Now, result is "ctmania thiscat thisctmaina"

Case 5: Neither beginning nor end

result = text.replace(/\Bcat\B/g, "ct");

Now, result is "catmania thiscat thisctmaina"

Hope this helps :)

How to get request URI without context path?

With Spring you can do:

String path = new UrlPathHelper().getPathWithinApplication(request);

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

How can I show a message box with two buttons?

Remember - if you set the buttons to vbOkOnly - it will always return 1.

So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk option.

Assert that a WebElement is not present using Selenium WebDriver with java

For appium 1.6.0 and above

    WebElement button = (new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//XCUIElementTypeButton[@name='your button']"))));
    button.click();

    Assert.assertTrue(!button.isDisplayed());

Reading large text files with streams in C#

You can improve read speed by using a BufferedStream, like this:

using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {

    }
}

March 2013 UPDATE

I recently wrote code for reading and processing (searching for text in) 1 GB-ish text files (much larger than the files involved here) and achieved a significant performance gain by using a producer/consumer pattern. The producer task read in lines of text using the BufferedStream and handed them off to a separate consumer task that did the searching.

I used this as an opportunity to learn TPL Dataflow, which is very well suited for quickly coding this pattern.

Why BufferedStream is faster

A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers improve read and write performance. A buffer can be used for either reading or writing, but never both simultaneously. The Read and Write methods of BufferedStream automatically maintain the buffer.

December 2014 UPDATE: Your Mileage May Vary

Based on the comments, FileStream should be using a BufferedStream internally. At the time this answer was first provided, I measured a significant performance boost by adding a BufferedStream. At the time I was targeting .NET 3.x on a 32-bit platform. Today, targeting .NET 4.5 on a 64-bit platform, I do not see any improvement.

Related

I came across a case where streaming a large, generated CSV file to the Response stream from an ASP.Net MVC action was very slow. Adding a BufferedStream improved performance by 100x in this instance. For more see Unbuffered Output Very Slow

How to center align the ActionBar title in Android?

Best and easiest way, specifically for those who just want text view with gravity center without any xml layout.

AppCompatTextView mTitleTextView = new AppCompatTextView(getApplicationContext());
        mTitleTextView.setSingleLine();
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        actionBar.setCustomView(mTitleTextView, layoutParams);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
        mTitleTextView.setText(text);
        mTitleTextView.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);

Is it possible to decompile a compiled .pyc file into a .py file?

Uncompyle6 works for Python 3.x and 2.7 - recommended option as it's most recent tool, aiming to unify earlier forks and focusing on automated unit testing. The GitHub page has more details.

  • if you use Python 3.7+, you could also try decompile3, a fork of Uncompyle6 focusing on 3.7 and higher.
  • do raise GitHub issues on these projects if needed - both run unit test suites on a range of Python versions

With these tools, you get your code back including variable names and docstrings, but without the comments.

The older Uncompyle2 supports Python 2.7 only. This worked well for me some time ago to decompile the .pyc bytecode into .py, whereas unpyclib crashed with an exception.

What is a NullReferenceException, and how do I fix it?

Another general case where one might receive this exception involves mocking classes during unit testing. Regardless of the mocking framework being used, you must ensure that all appropriate levels of the class hierarchy are properly mocked. In particular, all properties of HttpContext which are referenced by the code under test must be mocked.

See "NullReferenceException thrown when testing custom AuthorizationAttribute" for a somewhat verbose example.

jQuery how to bind onclick event to dynamically added HTML element

It is possible and sometimes necessary to create the click event along with the element. This is for example when selector based binding is not an option. The key part is to avoid the problem that Tobias was talking about by using .replaceWith() on a single element. Note that this is just a proof of concept.

<script>
    // This simulates the object to handle
    var staticObj = [
        { ID: '1', Name: 'Foo' },
        { ID: '2', Name: 'Foo' },
        { ID: '3', Name: 'Foo' }
    ];
    staticObj[1].children = [
        { ID: 'a', Name: 'Bar' },
        { ID: 'b', Name: 'Bar' },
        { ID: 'c', Name: 'Bar' }
    ];
    staticObj[1].children[1].children = [
        { ID: 'x', Name: 'Baz' },
        { ID: 'y', Name: 'Baz' }
    ];

    // This is the object-to-html-element function handler with recursion
    var handleItem = function( item ) {
        var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");

        if(typeof item.children !== 'undefined') {
            ul = $("<ul />");
            for (var i = 0; i < item.children.length; i++) {
                ul.append(handleItem(item.children[i]));
            }
            li.append(ul);
        }

        // This click handler actually does work
        li.click(function(e) {
            alert(item.Name);
            e.stopPropagation();
        });
        return li;
    };

    // Wait for the dom instead of an ajax call or whatever
    $(function() {
        var ul = $("<ul />");

        for (var i = 0; i < staticObj.length; i++) {
            ul.append(handleItem(staticObj[i]));
        }

        // Here; this works.
        $('#something').replaceWith(ul);
    });
</script>
<div id="something">Magical ponies ?</div>

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

You can try openSSL to generate certificates. Take a look at this.

You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.

var https = require('https');
var fs = require('fs');
var express = require('express');

var options = {
    key: fs.readFileSync('/etc/apache2/ssl/server.key'),
    cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
    requestCert: false,
    rejectUnauthorized: false
};


var app = express();

var server = https.createServer(options, app).listen(3000, function(){
    console.log("server started at port 3000");
});

This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.

However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.

If anyone has ever bypassed this error with self signed certificate, please enlighten.

How can I select all children of an element except the last child?

When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).

error_reporting(E_ALL) does not produce error

That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting line, therefore the error reporting settings aren't changed yet.

You cannot change error reporting settings (or really, do anything) in a file with syntax errors.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

my experience tells me that missing persistence.xml,will generate the same exception too.

i caught the same error msg today when i tried to run a jar package packed by ant.

when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.

after I manually repacked the jar file ,the error msg disappered.

so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.

Don't reload application when orientation changes

I dont know if the a best solution, but i describe it here:

First of all, you need certificate with you class Application of your app is in your manifest of this:

<application
    android:name=".App"
    ...

Second, in my class App i did like this:

public class App extends Application {
    public static boolean isOrientationChanged = false;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onConfigurationChanged(@NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ||
                newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            isOrientationChanged = true;
        }
    }

}

Third, you need to set a flag to Orientation Change, in my case, I always set it when the previous activity within the app navigation is called, so only calling once when the later activity is created.

isOrientationChanged = false;

So every time I change the orientation of my screen in that context, I set it every time it changes this setting, it checks if there is a change in orientation, if so, it validates it based on the value of that flag.

Basically, I had to use it whenever I made an asynchronous retrofit request, which he called every moment that changed orientation, constantly crashing the application:

if (!isOrientationChanged) {
    presenter.retrieveAddress(this, idClient, TYPE_ADDRESS);
}

I don't know if it's the most elegant and beautiful solution, but at least here it's functional :)

Replace the single quote (') character from a string

You can escape the apostrophe with a \ character as well:

mystring.replace('\'', '')

Windows service start failure: Cannot start service from the command line or debugger

To install your service manually

To install or uninstall windows service manually (which was created using .NET Framework) use utility InstallUtil.exe. This tool can be found in the following path (use appropriate framework version number).

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

To install

installutil yourproject.exe

To uninstall

installutil /u yourproject.exe

See: How to: Install and Uninstall Services (Microsoft)

Install service programmatically

To install service programmatically using C# see the following class ServiceInstaller (c-sharpcorner).

Swift Open Link in Safari

Swift 5

Swift 5: Check using canOpneURL if valid then it's open.

guard let url = URL(string: "https://iosdevcenters.blogspot.com/") else {
     return
}

if UIApplication.shared.canOpenURL(url) {
     UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

How do I use a custom Serializer with Jackson?

I wrote an example for a custom Timestamp.class serialization/deserialization, but you could use it for what ever you want.

When creating the object mapper do something like this:

public class JsonUtils {

    public static ObjectMapper objectMapper = null;

    static {
        objectMapper = new ObjectMapper();
        SimpleModule s = new SimpleModule();
        s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
        s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
        objectMapper.registerModule(s);
    };
}

for example in java ee you could initialize it with this:

import java.time.LocalDateTime;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {

    private final ObjectMapper objectMapper;

    public JacksonConfig() {
        objectMapper = new ObjectMapper();
        SimpleModule s = new SimpleModule();
        s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
        s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
        objectMapper.registerModule(s);
    };

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return objectMapper;
    }
}

where the serializer should be something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampSerializerTypeHandler extends JsonSerializer<Timestamp> {

    @Override
    public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        String stringValue = value.toString();
        if(stringValue != null && !stringValue.isEmpty() && !stringValue.equals("null")) {
            jgen.writeString(stringValue);
        } else {
            jgen.writeNull();
        }
    }

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}

and deserializer something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampDeserializerTypeHandler extends JsonDeserializer<Timestamp> {

    @Override
    public Timestamp deserialize(JsonParser jp, DeserializationContext ds) throws IOException, JsonProcessingException {
        SqlTimestampConverter s = new SqlTimestampConverter();
        String value = jp.getValueAsString();
        if(value != null && !value.isEmpty() && !value.equals("null"))
            return (Timestamp) s.convert(Timestamp.class, value);
        return null;
    }

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}