Programs & Examples On #Hash code uniqueness

Android, How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

how to set textbox value in jquery

Note that the .value attribute is a JavaScript feature. If you want to use jQuery, use:

$('#pid').val()

to get the value, and:

$('#pid').val('value')

to set it.

http://api.jquery.com/val/

Regarding your second issue, I have never tried automatically setting the HTML value using the load method. For sure, you can do something like this:

$('#subtotal').load( 'compz.php?prodid=' + x + '&qbuys=' + y, function(response){ $('#subtotal').val(response);
});

Note that the code above is untested.

http://api.jquery.com/load/

JUnit tests pass in Eclipse but fail in Maven Surefire

I had this problem today testing a method that converted an object that contained a Map to a JSON string. I assume Eclipse and the Maven surefire plugin were using different JREs which had different implementations of HashMap ordering or something, which caused the tests run through Eclipse to pass and the tests run through surefire to fail (assertEquals failed). The easiest solution was to use an implementation of Map that had reliable ordering.

Use a URL to link to a Google map with a marker on it

If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker

GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z" 

GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en"  'route ?hl=en

OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"

OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"

python global name 'self' is not defined

The self name is used as the instance reference in class instances. It is only used in class method definitions. Don't use it in functions.

You also cannot reference local variables from other functions or methods with it. You can only reference instance or class attributes using it.

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

Execute PowerShell Script from C# with Commandline Arguments

Try creating scriptfile as a separate command:

Command myCommand = new Command(scriptfile);

then you can add parameters with

CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);

and finally

pipeline.Commands.Add(myCommand);

Here is the complete, edited code:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);

pipeline.Commands.Add(myCommand);

// Execute PowerShell script
results = pipeline.Invoke();

javascript filter array of objects

For those who want to filter from an array of objects using any key:

_x000D_
_x000D_
function filterItems(items, searchVal) {_x000D_
  return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
}_x000D_
let data = [_x000D_
  { "name": "apple", "type": "fruit", "id": 123234 },_x000D_
  { "name": "cat", "type": "animal", "id": 98989 },_x000D_
  { "name": "something", "type": "other", "id": 656565 }]_x000D_
_x000D_
_x000D_
console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
console.log("Filtered by id: ", filterItems(data, 656565));
_x000D_
_x000D_
_x000D_

filter from an array of the JSON objects:**

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

bootstrap multiselect get selected values

In your Html page please add

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test the multiselect with ajax</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <!-- Bootstrap multiselect -->
    <link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
      <br>

      <form method="post" id="myForm">

        <!-- Build your select: -->
        <select name="categories[]" id="example-getting-started" multiple="multiple" class="col-md-12">
          <option value="A">Cheese</option>
          <option value="B">Tomatoes</option>
          <option value="C">Mozzarella</option>
          <option value="D">Mushrooms</option>
          <option value="E">Pepperoni</option>
          <option value="F">Onions</option>
          <option value="G">10</option>
          <option value="H">11</option>
          <option value="I">12</option>
        </select>
        <br><br>
        <button type="button" class="btnSubmit"> Send </button>

      </form>

      <br><br>
      <div id="result">result</div>
    </div><!--container-->

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <!-- Bootstrap multiselect -->
    <script src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>

    <!-- Bootstrap multiselect -->
    <script src="ajax.js"></script>

    <!-- Initialize the plugin: -->
    <script type="text/javascript">
      $(document).ready(function() {

        $('#example-getting-started').multiselect();

      });
    </script>

  </body>
</html>

In your ajax.js page please add

$(document).ready(function () {
  $(".btnSubmit").on('click',(function(event) {
    var formData = new FormData($('#myForm')[0]);
    $.ajax({
      url: "action.php",
      type: "POST",
      data: formData,
      contentType: false,
      cache: false,
      processData:false,
      success: function(data)
      {
        $("#result").html(data);

        // To clear the selected options
        var select = $("#example-getting-started");
        select.children().remove();
        if (data.d) {
          $(data.d).each(function(key,value) {
            $("#example-getting-started").append($("<option></option>").val(value.State_id).html(value.State_name));
          });
        }
        $('#example-getting-started').multiselect({includeSelectAllOption: true});
        $("#example-getting-started").multiselect('refresh');

      },
      error: function()
      {
        console.log("failed to send the data");
      }
    });
  }));
});

In your action.php page add

  echo "<b>You selected :</b>";

  for($i=0;$i<=count($_POST['categories']);$i++){

    echo $_POST['categories'][$i]."<br>";

  }

MySQL Workbench: How to keep the connection alive

I had a similar problem where CREATE FULLTEXT timed out after 30 seconds:

error

Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:

fix error

Also, I did not have to restart mysql workbench for this to work.

SQL Server add auto increment primary key to existing table

alter table /** paste the tabal's name **/ add id int IDENTITY(1,1)

delete from /** paste the tabal's name **/ where id in

(

select a.id FROM /** paste the tabal's name / as a LEFT OUTER JOIN ( SELECT MIN(id) as id FROM / paste the tabal's name / GROUP BY / paste the columns c1,c2 .... **/

) as t1 
ON a.id = t1.id

WHERE t1.id IS NULL

)

alter table /** paste the tabal's name **/ DROP COLUMN id

ImageView rounded corners

Your MainActivity.java is like this:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);

You should to first get your image from Resource as Bitmap or Drawable.

If get as Bitmap:

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);

Or if get as Drawable:

Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);

Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:

package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:[email protected]
public class Newreza{
    int a,x,y;
    float bmr;
    public Bitmap setEffect(Bitmap bm,float radius,int color){
        bm=bm.copy(Bitmap.Config.ARGB_8888,true);
        bmr=radius*bm.getWidth();
        for(y=0;y<bmr;y++){
            a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=0;y<bmr;y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        return bm;
    }
    public Drawable setEffect(Drawable d,float radius,int color){
        return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
    }
}

Just notice that replace your package name with first line in the code.

It %100 works, because is written in details :)

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

Rebuild all indexes in a Database

Daniel's script appears to be a good all encompassing solution, but even he admitted that his laptop ran out of memory. Here is an option I came up with. I based my procedure off of Mohammad Nizamuddin's post on TechNet. I added an initial cursor loop that pulls all the database names into a temporary table and then uses that to pull all the base table names from each of those databases.

You can optionally pass the fill factor you would prefer and specify a target database if you do not want to re-index all databases.


--===============================================================
-- Name:  sp_RebuildAllIndexes
-- Arguements:  [Fill Factor], [Target Database name]
-- Purpose:  Loop through all the databases on a server and
--           compile a list of all the table within them.
--           This list is then used to rebuild indexes for
--           all the tables in all the database.  Optionally,
--           you may pass a specific database name if you only
--           want to reindex that target database.
--================================================================
CREATE PROCEDURE sp_RebuildAllIndexes(
    @FillFactor     INT = 90,
    @TargetDatabase NVARCHAR(100) = NULL)
AS
    BEGIN
        DECLARE @TablesToReIndex TABLE (
            TableName VARCHAR(200)
        );
        DECLARE @DbName VARCHAR(50);
        DECLARE @TableSelect VARCHAR(MAX);
        DECLARE @DatabasesToIndex CURSOR;

        IF ISNULL( @TargetDatabase, '' ) = ''
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
        ELSE
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
              WHERE  NAME = @TargetDatabase

        OPEN DatabasesToIndex

        FETCH NEXT FROM DatabasesToIndex INTO @DbName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @TableSelect = 'INSERT INTO @TablesToReIndex SELECT CONCAT(TABLE_CATALOG, ''.'', TABLE_SCHEMA, ''.'', TABLE_NAME) AS TableName FROM '
                                   + @DbName
                                   + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''base table''';

                EXEC sp_executesql
                    @TableSelect;

                FETCH NEXT FROM DatabasesToIndex INTO @DbName
            END

        CLOSE DatabasesToIndex

        DEALLOCATE DatabasesToIndex

        DECLARE @TableName VARCHAR(255)
        DECLARE TableCursor CURSOR FOR
            SELECT TableName
            FROM   @TablesToReIndex

        OPEN TableCursor

        FETCH NEXT FROM TableCursor INTO @TableName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                DBCC DBREINDEX(@TableName, ' ', @FillFactor)

                FETCH NEXT FROM TableCursor INTO @TableName
            END

        CLOSE TableCursor

        DEALLOCATE TableCursor
    END 

C# - What does the Assert() method do? Is it still useful?

Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.

An important feature is that they mustn't produce side-effects, for example you can handle an exception or take a different course of action with an if statement(defensive programming).

Assertions are used to check the pre/post conditions of the contract, the client/supplier relationship - the client must ensure that the pre-conditions of the supplier are met eg. sends £5 and the supplier must ensure the post-conditions are met eg. delivers 12 roses. (Just simple explanation of client/supplier - can accept less and deliver more, but about Assertions). C# also introduces Trace.Assert(), which can be used for release code.

To answer the question yes they still useful, but can add complexity+readability to code and time+difficultly to maintain. Should we still use them? Yes, Will we all use them? Probably not, or not to the extent of how Meyer describes.

(Even the OU Java course that I learnt this technique on only showed simple examples and the rest of there code didn't enforce the DbC assertion rules on most of code, but was assumed to be used to assure program correctness!)

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

HTML5 form validation pattern alphanumeric with spaces?

It's quite an old question, but in case it could be useful for anyone, starting from a combination of good responses found here, I've ended using this pattern:

pattern="([^\s][A-z0-9À-ž\s]+)"

It will require at least two characters, making sure it does not start with an empty space but allowing spaces between words, and also allowing special characters such as a, ó, ä, ö.

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

sometimes something wrong in the syntax of the code inside the function throws this error. Check your function correctly. In my case it happened when I was trying to assign Json fields with values and was using colon : to make the assignment instead of equal sign = ...

Detect WebBrowser complete page loading

You can use the event ProgressChanged ; the last time it is raised will indicate that the document is fully rendered:

this.webBrowser.ProgressChanged += new
WebBrowserProgressChangedEventHandler(webBrowser_ProgressChanged);

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

@Raphael your solution does work. I encountered the same problem and solved it by increasing the maximum execution time to 180. There is an easier way to do it though:

  1. Open the Xampp control panel

  2. Click on 'config' behind 'Apache'

  3. Select 'PHP (php.ini)' from the dropdown -> A file should now open in your text editor

  4. Press ctrl+f and search for 'max_execution_time', you should fine a line which only says

    max_execution_time=30

  5. Change 30 to a bigger number (180 worked for me), like this:

    max_execution_time=180

  6. Save the file

  7. 'Stop' Apache server

  8. Close Xampp

  9. Restart Xampp

  10. 'Start' Apache server

  11. Update Wordpress from the Admin dashboard

  12. Enjoy ;)

MySQL query to get column names?

function get_col_names(){  
    $sql = "SHOW COLUMNS FROM tableName";  
    $result = mysql_query($sql);     
    while($record = mysql_fetch_array($result)){  
     $fields[] = $record['0'];  
    }
    foreach ($fields as $value){  
      echo 'column name is : '.$value.'-';  
}  
 }  

return get_col_names();

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

From what I understand, You have to save a user's input locally to a text file.

Check this link. See if this helps.

Saving user input to a text file locally

How to get folder directory from HTML input type "file" or any other way?

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:

https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

How to include a quote in a raw Python string

Since I stumbled on this answer, and it greatly helped me, but I found a minor syntactic issue, I felt I should save others possible frustration. The triple quoted string works for this scenario as described, but note that if the " you want in the string occurs at the end of the string itself:

somestr = """This is a string with a special need to have a " in it at the end""""

You will hit an error at execution because the """" (4) quotes in a row confuses the string reader, as it thinks it has hit the end of the string already and then finds a random " out there. You can validate this by inserting a space into the 4 quotes like so: " """ and it will not have the error.

In this special case you will need to either use:

somestr = 'This.....at the end"'

or use the method described above of building multiple strings with mixed " and ' and then concatenating them after the fact.

Get parent directory of running script

Fugly, but this will do it:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

Why can't I center with margin: 0 auto?

An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.

This is how it works for me:

#content {
display: block;
margin: 0 auto;
}

Disable same origin policy in Chrome

I use this sometimes, for posting a localhost front-end site to a localhost back-end API (e.g. React to an old .NET API). I created a separate shortcut on my Windows 10 desktop, so that it never is used for normal browsing, only for debugging locally. I did the following:-

  1. Right click on desktop, add new shortcut
  2. Add the target as "[PATH_TO_CHROME]\chrome.exe" --disable-web-security
  3. Click OK.

You will get a warning on load of this browser, that it is not secure, just take care with what you browser on it. I tend to rename this new shortcut on the desktop, something in capital, and move it away from my other icons, so it can't be confused for normal Chrome.

Hope this helps!

Running JAR file on Windows

Making a start.bat was the only thing that worked for me.

open a text document and enter. java -jar whatever yours is called .jar

save as start.bat in the same folder as the .jar file you want to execute. and then run the. bat

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

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

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?

How to Scroll Down - JQuery

I mostly use following code to scroll down

$('html, body').animate({ scrollTop:  $(SELECTOR).offset().top - 50 }, 'slow');

Bootstrap 4, How do I center-align a button?

What worked for me was (adapt "css/style.css" to your css path):

Head HTML:

 <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />

Body HTML:

 <div class="container">
  <div class="row">
    <div class="mycentered-text">
      <button class="btn btn-default"> Login </button>
    </div>
  </div>
</div>

Css:

.mycentered-text {
    text-align:center
}

Adding event listeners to dynamically added elements using jQuery

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

DISABLE the Horizontal Scroll

I just had to deal with it myself. After all I found this method most easy and useful. Just add

overflow-x: hidden;

To your outer parent. In my case it looks like this:

<body style="overflow-x: hidden;">

You have to use overflow-x because if you use simply use overflow you disable the vertical scrolling too, namely overflow-y

If the vertical scrolling is still disabled you can enable it explicitly with:

overflow-y: scroll;

I know its somewhat not a proper way because if everything was setup well one would not have to use this quick and dirty method.

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

Dynamic function name in javascript?

I had better luck in combining Darren's answer and kyernetikos's answer.

_x000D_
_x000D_
const nameFunction = function (fn, name) {_x000D_
  return Object.defineProperty(fn, 'name', {value: name, configurable: true});_x000D_
};_x000D_
_x000D_
/* __________________________________________________________________________ */_x000D_
_x000D_
let myFunc = function oldName () {};_x000D_
_x000D_
console.log(myFunc.name); // oldName_x000D_
_x000D_
myFunc = nameFunction(myFunc, 'newName');_x000D_
_x000D_
console.log(myFunc.name); // newName
_x000D_
_x000D_
_x000D_

Note: configurable is set to true to match the standard ES2015 spec for Function.name1

This especially helped in getting around an error in Webpack similar to this one.

Update: I was thinking of publishing this as an npm package, but this package from sindresorhus does exactly the same thing.

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

How to remove new line characters from a string?

You can use Trim if you want to remove from start and end.

string stringWithoutNewLine = "\n\nHello\n\n".Trim();

Val and Var in Kotlin

val property is similar to final property in Java. You are allowed to assign it a value only for one time. When you try to reassign it with a value for second time you will get a compilation error. Whereas var property is mutable which you are free to reassign it when you wish and for any times you want.

What is the difference between sscanf or atoi to convert a string to an integer?

If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

Dynamically add data to a javascript map

Javascript now has a specific built in object called Map, you can call as follows :

   var myMap = new Map()

You can update it with .set :

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

'setInterval' vs 'setTimeout'

setInterval()

setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

if you want to loop code for animations or clocks Then use setInterval.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.

How do you remove an array element in a foreach loop?

As has already been mentioned, you’d want to do a foreach with the key, and unset using the key – but note that mutating an array during iteration is in general a bad idea, though I’m not sure on PHP’s rules on this offhand.

How to install Python MySQLdb module using pip?

It's easy to do, but hard to remember the correct spelling:

pip install mysqlclient

If you need 1.2.x versions (legacy Python only), use pip install MySQL-python

Note: Some dependencies might have to be in place when running the above command. Some hints on how to install these on various platforms:

Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie)

sudo apt-get install python-pip python-dev libmysqlclient-dev

Fedora 24:

sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc

Mac OS

brew install mysql-connector-c

if that fails, try

brew install mysql

What does the term "canonical form" or "canonical representation" in Java mean?

A good example for understanding "canonical form/representation" is to look at the XML schema datatype definition of "boolean":

  • the "lexical representation" of boolean can be one of: {true, false, 1, 0} whereas
  • the "canonical representation" can only be one of {true, false}

This, in essence, means that

  • "true" and "1" get mapped to the canonical repr. "true" and
  • "false" and "0" get mapped to the canoncial repr. "false"

see the w3 XML schema datatype definition for boolean

Responding with a JSON object in Node.js (converting object/array to JSON string)

in express there may be application-scoped JSON formatters.

after looking at express\lib\response.js, I'm using this routine:

function writeJsonPToRes(app, req, res, obj) {
    var replacer = app.get('json replacer');
    var spaces = app.get('json spaces');
    res.set('Content-Type', 'application/json');
    var partOfResponse = JSON.stringify(obj, replacer, spaces)
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029');
    var callback = req.query[app.get('jsonp callback name')];
    if (callback) {
        if (Array.isArray(callback)) callback = callback[0];
        res.set('Content-Type', 'text/javascript');
        var cb = callback.replace(/[^\[\]\w$.]/g, '');
        partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
    }
    res.write(partOfResponse);
}

Cannot connect to repo with TortoiseSVN

SVN is case-sensitive. Make sure that you're spelling it properly. If it got renamed, you can relocate the working folder to the new URL. See https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html

What's the maximum value for an int in PHP?

Although PHP_INT_* constants exist for a very long time, the same MIN / MAX values could be found programmatically by left shifting until reaching the negative number:

$x = 1;
while ($x > 0 && $x <<= 1);
echo "MIN: ", $x;
echo PHP_EOL;
echo "MAX: ", ~$x;

CentOS: Enabling GD Support in PHP Installation

CentOs 6.5+ & PHP 5.6:

sudo yum install php56-gd

service httpd restart

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

How do I revert an SVN commit?

It is impossible to "uncommit" a revision, but you can revert your working copy to version 1943 and commit that as version 1945. The versions 1943 and 1945 will be identical, effectively reverting the changes.

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

How to initialize a nested struct?

Define your Proxy struct separately, outside of Configuration, like this:

type Proxy struct {
    Address string
    Port    string
}

type Configuration struct {
    Val string
    P   Proxy
}

c := &Configuration{
    Val: "test",
    P: Proxy{
        Address: "addr",
        Port:    "80",
    },
}

See http://play.golang.org/p/7PELCVsQIc

How to keep :active css style after click a button

In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.

You should be able to add this code:

<script>
 $( ".et-pb-icon" ).click(function() {
 $( this ).toggleClass( "active" );
 });
</script>

into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.

Then, you should be able to style your class to what ever you need.

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

StringIO in Python3

Roman Shapovalov's code should work in Python 3.x as well as Python 2.6/2.7. Here it is again with the complete example:

import io
import numpy
x = "1 3\n 4.5 8"
numpy.genfromtxt(io.BytesIO(x.encode()))

Output:

array([[ 1. ,  3. ],
       [ 4.5,  8. ]])

Explanation for Python 3.x:

  • numpy.genfromtxt takes a byte stream (a file-like object interpreted as bytes instead of Unicode).
  • io.BytesIO takes a byte string and returns a byte stream. io.StringIO, on the other hand, would take a Unicode string and and return a Unicode stream.
  • x gets assigned a string literal, which in Python 3.x is a Unicode string.
  • encode() takes the Unicode string x and makes a byte string out of it, thus giving io.BytesIO a valid argument.

The only difference for Python 2.6/2.7 is that x is a byte string (assuming from __future__ import unicode_literals is not used), and then encode() takes the byte string x and still makes the same byte string out of it. So the result is the same.


Since this is one of SO's most popular questions regarding StringIO, here's some more explanation on the import statements and different Python versions.

Here are the classes which take a string and return a stream:

  • io.BytesIO (Python 2.6, 2.7, and 3.x) - Takes a byte string. Returns a byte stream.
  • io.StringIO (Python 2.6, 2.7, and 3.x) - Takes a Unicode string. Returns a Unicode stream.
  • StringIO.StringIO (Python 2.x) - Takes a byte string or Unicode string. If byte string, returns a byte stream. If Unicode string, returns a Unicode stream.
  • cStringIO.StringIO (Python 2.x) - Faster version of StringIO.StringIO, but can't take Unicode strings which contain non-ASCII characters.

Note that StringIO.StringIO is imported as from StringIO import StringIO, then used as StringIO(...). Either that, or you do import StringIO and then use StringIO.StringIO(...). The module name and class name just happen to be the same. It's similar to datetime that way.

What to use, depending on your supported Python versions:

  • If you only support Python 3.x: Just use io.BytesIO or io.StringIO depending on what kind of data you're working with.

  • If you support both Python 2.6/2.7 and 3.x, or are trying to transition your code from 2.6/2.7 to 3.x: The easiest option is still to use io.BytesIO or io.StringIO. Although StringIO.StringIO is flexible and thus seems preferred for 2.6/2.7, that flexibility could mask bugs that will manifest in 3.x. For example, I had some code which used StringIO.StringIO or io.StringIO depending on Python version, but I was actually passing a byte string, so when I got around to testing it in Python 3.x it failed and had to be fixed.

    Another advantage of using io.StringIO is the support for universal newlines. If you pass the keyword argument newline='' into io.StringIO, it will be able to split lines on any of \n, \r\n, or \r. I found that StringIO.StringIO would trip up on \r in particular.

    Note that if you import BytesIO or StringIO from six, you get StringIO.StringIO in Python 2.x and the appropriate class from io in Python 3.x. If you agree with my previous paragraphs' assessment, this is actually one case where you should avoid six and just import from io instead.

  • If you support Python 2.5 or lower and 3.x: You'll need StringIO.StringIO for 2.5 or lower, so you might as well use six. But realize that it's generally very difficult to support both 2.5 and 3.x, so you should consider bumping your lowest supported version to 2.6 if at all possible.

How to install toolbox for MATLAB

For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.

Is it possible to modify a registry entry via a .bat/.cmd script?

This is how you can modify registry, without yes or no prompt and don't forget to run as administrator

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\etc\etc   /v Valuename /t REG_SZ /d valuedata  /f 

Below is a real example to set internet explorer as my default browser

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice   /v ProgId /t REG_SZ /d IE.HTTPS  /f 

/f Force: Force an update without prompting "Value exists, overwrite Y/N"

/d Data : The actual data to store as a "String", integer etc

/v Value : The value name eg ProgId

/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from here

Simplest way to restart service on a remote computer

This is what I do when I have restart a service remotely with different account

Open a CMD with different login

runas /noprofile /user:DOMAIN\USERNAME cmd

Use SC to stop and start

sc \\SERVERNAME query Tomcat8
sc \\SERVERNAME stop Tomcat8
sc \\SERVERNAME start Tomcat8

Is there a Sleep/Pause/Wait function in JavaScript?

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

JavaScript function in href vs. onclick

 <hr>
            <h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
            <button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
            <div class="pull-right">
                <button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
            </div>
        </div>
            <script type="text/javascript">
                $(document).ready(function(){
                $('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
                });
            </script>   
            <script type="text/javascript">
                $(document).ready(function(){
                $('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
                });
            </script>   

nodejs get file name from absolute path?

For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.html');

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

In a bug I was investigating there was a Response.Redirect() and it was executing in an unexpected location (read: inappropriate location - inside a member property getter method).

If you're debugging a problem and experience the "Unable to evaluate expression..." exception:

  1. Perform a search for Response.Redirect() and either make the second parameter endResponse = false, or
  2. Temporarily disable the redirect call.

This was frustrating as it would appear to execute the Redirect call before the "step through" on the debugger had reached that location.

How can I change the user on Git Bash?

Check what git remote -v returns: the account used to push to an http url is usually embedded into the remote url itself.

https://[email protected]/...

If that is the case, put an url which will force Git to ask for the account to use when pushing:

git remote set-url origin https://github.com/<user>/<repo>

Or one to use the Fre1234 account:

git remote set-url origin https://[email protected]/<user>/<repo>

Also check if you installed your Git For Windows with or without a credential helper as in this question.


The OP Fre1234 adds in the comments:

I finally found the solution.
Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github,
Click on them and click "Remove".

That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper output (it should be manager)

VB.NET Switch Statement GoTo Case

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here.
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select

Is there a reason for the goto? If it doesn't meet the if criterion, it will simply not perform the function and go to the next case.

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

Using jQuery, Restricting File Size Before Uploading

I encountered the same issue. You have to use ActiveX or Flash (or Java). The good thing is that it doesn't have to be invasive. I have a simple ActiveX method that will return the size of the to-be-uploaded file.

If you go with Flash, you can even do some fancy js/css to cusomize the uploading experience--only using Flash (as a 1x1 "movie") to access it's file uploading features.

How can I pass a reference to a function, with parameters?

You can also overload the Function prototype:

// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
    var func = this;
    var slice = Array.prototype.slice;
    var appliedArgs = slice.call( arguments, 0 );

    return function( ) {
        var leftoverArgs = slice.call( arguments, 0 );
        return func.apply( this, appliedArgs.concat( leftoverArgs ) );
    };
};

// can do other fancy things:

// flips the first two arguments of a function
Function.prototype.flip = function( ) {
    var func = this;
    return function( ) {
        var first = arguments[0];
        var second = arguments[1];
        var rest = Array.prototype.slice.call( arguments, 2 );
        var newArgs = [second, first].concat( rest );

        return func.apply( this, newArgs );
    };
};

/*
e.g.

var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey

var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/

True and False for && logic and || Logic table

You probably mean a truth table for the boolean operators, which displays the result of the usual boolean operations (&&, ||). This table is not language-specific, but can be found e.g. here.

How to "test" NoneType in python?

Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.

if type(author) == type(None):
     my if body
else:
    my else body

Author can be any variable in this case, and None can be any type that you are checking for.

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

Clear Cache in Android Application programmatically

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

setContentView(R.layout.main); error

This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml

sql searching multiple words in a string

Oracle SQL :

select * 
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles    database')
  • company - is the database column name.
  • results - this SQL will show you if company column rows contain one of those companies (OR phrase) please note that : no wild characters are needed, it's built in.

more info at : http://www.techonthenet.com/oracle/regexp_like.php

Java: Local variable mi defined in an enclosing scope must be final or effectively final

Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Change Volley timeout duration

/**
 * @param request
 * @param <T>
 */
public <T> void addToRequestQueue(Request<T> request) {

    request.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    getRequestQueue().add(request);
}

How do I instantiate a JAXBElement<String> object?

I don't know why you think there's no constructor. See the API.

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

My Custom Toolbar XML

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

How do we update URL or query strings using javascript/jQuery without reloading the page?

Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.

var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

CAST to DECIMAL in MySQL

An alternative, I think for your purpose, is to use the round() function:

select round((10 * 1.5),2) // prints 15.00

You can try it here:

How to check if JavaScript object is JSON

I'd check the constructor attribute.

e.g.

var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.

How to read attribute value from XmlNode in C#?

Yet another solution:

string s = "??"; // or whatever

if (chldNode.Attributes.Cast<XmlAttribute>()
                       .Select(x => x.Value)
                       .Contains(attributeName))   
   s =  xe.Attributes[attributeName].Value;

It also avoids the exception when the expected attribute attributeName actually doesn't exist.

UL or DIV vertical scrollbar

You need to define height of ul or your div and set overflow equals to auto as below:

<ul style="width: 300px; height: 200px; overflow: auto">
  <li>text</li>
  <li>text</li>

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


How to check permissions of a specific directory?

You can also use the stat command if you want detailed information on a file/directory. (I precise this as you say you are learning ^^)

How do I make a request using HTTP basic authentication with PHP curl?

If the authorization type is Basic auth and data posted is json then do like this

<?php

$data = array("username" => "test"); // data u want to post                                                                   
$data_string = json_encode($data);                                                                                   
 $api_key = "your_api_key";   
 $password = "xxxxxx";                                                                                                                 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");    
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_POST, true);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
    'Accept: application/json',
    'Content-Type: application/json')                                                           
);             

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}                                                                                                      
$errors = curl_error($ch);                                                                                                            
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);  
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));

How to import a single table in to mysql database using command line

To import a table into database, if table is already exist then add this line in your sql file DROP TABLE IF EXIST 'table_name' and run command mysql -u username -p database_name < import_sql_file.sql. Please verify the sql file path before execute the command.

How to go to a URL using jQuery?

why not using?

location.href='http://www.example.com';

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function goToURL() {_x000D_
      location.href = 'http://google.it';_x000D_
_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="javascript:void(0)" onclick="goToURL(); return false;">Go To URL</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How do I compute the intersection point of two lines?

Here is a solution using the Shapely library. Shapely is often used for GIS work, but is built to be useful for computational geometry. I changed your inputs from lists to tuples.

Problem

# Given these endpoints
#line 1
A = (X, Y)
B = (X, Y)

#line 2
C = (X, Y)
D = (X, Y)

# Compute this:
point_of_intersection = (X, Y)

Solution

import shapely
from shapely.geometry import LineString, Point

line1 = LineString([A, B])
line2 = LineString([C, D])

int_pt = line1.intersection(line2)
point_of_intersection = int_pt.x, int_pt.y

print(point_of_intersection)

How to read multiple Integer values from a single line of input in Java?

Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.

import java.util.Scanner; // imports class so we can use Scanner object

public class Test
{
    public static void main( String[] args )
    {
        Scanner keyboard = new Scanner( System.in );
        System.out.print("Enter numbers: ");

        // This inputs the numbers and stores as one whole string value
        // (e.g. if user entered 1 2 3, input = "1 2 3").
        String input = keyboard.nextLine();

        // This splits up the string every at every space and stores these
        // values in an array called numbersStr. (e.g. if the input variable is 
        // "1 2 3", numbersStr would be {"1", "2", "3"} )
        String[] numbersStr = input.split(" ");

        // This makes an int[] array the same length as our string array
        // called numbers. This is how we will store each number as an integer 
        // instead of a string when we have the values.
        int[] numbers = new int[ numbersStr.length ];

        // Starts a for loop which iterates through the whole array of the
        // numbers as strings.
        for ( int i = 0; i < numbersStr.length; i++ )
        {
            // Turns every value in the numbersStr array into an integer 
            // and puts it into the numbers array.
            numbers[i] = Integer.parseInt( numbersStr[i] );
            // OPTIONAL: Prints out each value in the numbers array.
            System.out.print( numbers[i] + ", " );
        }
        System.out.println();
    }
}

AngularJS - Create a directive that uses ng-model

I wouldn't set the ngmodel via an attribute, you can specify it right in the template:

template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',

plunker: http://plnkr.co/edit/9vtmnw?p=preview

PHP if not statements

Your logic is slightly off. The second || should be &&:

if ((!isset($action)) || ($action != "add" && $action != "delete"))

You can see why your original line fails by trying out a sample value. Let's say $action is "delete". Here's how the condition reduces down step by step:

// $action == "delete"
if ((!isset($action)) || ($action != "add" || $action != "delete"))
if ((!true) || ($action != "add" || $action != "delete"))
if (false || ($action != "add" || $action != "delete"))
if ($action != "add" || $action != "delete")
if (true || $action != "delete")
if (true || false)
if (true)

Oops! The condition just succeeded and printed "error", but it was supposed to fail. In fact, if you think about it, no matter what the value of $action is, one of the two != tests will return true. Switch the || to && and then the second to last line becomes if (true && false), which properly reduces to if (false).

There is a way to use || and have the test work, by the way. You have to negate everything else using De Morgan's law, i.e.:

if ((!isset($action)) || !($action == "add" || $action == "delete"))

You can read that in English as "if action is not (either add or remove), then".

Is there a way to get the XPath in Google Chrome?

First open your Google Chrome

and open any website

and inspect that

Why is "cursor:pointer" effect in CSS not working

Also add cursor:hand. Some browsers need that instead.

How to convert int to QString?

Just for completeness, you can use the standard library and do QString qstr = QString::fromStdString(std::to_string(42));

How to read lines of a file in Ruby

Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal. See "Why slurping a file is bad".

File.open('file_path', 'rb') do |io|
  while chunk = io.read(16 * 1024) do
    something_with_the chunk
    # like stream it across a network
    # or write it to another file:
    # other_io.write chunk
  end
end

Recyclerview and handling different type of row inflation

According to Gil great answer I solved by Overriding the getItemViewType as explained by Gil. His answer is great and have to be marked as correct. In any case, I add the code to reach the score:

In your recycler adapter:

@Override
public int getItemViewType(int position) {
    int viewType = 0;
    // add here your booleans or switch() to set viewType at your needed
    // I.E if (position == 0) viewType = 1; etc. etc.
    return viewType;
}

@Override
public FileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == 0) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout_for_first_row, parent, false));
    }

    return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_other_rows, parent, false));
}

By doing this, you can set whatever custom layout for whatever row!

Matplotlib - global legend and title aside subplots

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

MySQL table is marked as crashed and last (automatic?) repair failed

If this happend to your XAMPP installation, just copy global_priv.MAD and global_priv.MAI files from ./xampp/mysql/backup/mysql/ to ./xampp/mysql/data/mysql/.

How to rotate a 3D object on axis three.js?

I needed the rotateAroundWorldAxis function but the above code doesn't work with the newest release (r52). It looks like getRotationFromMatrix() was replaced by setEulerFromRotationMatrix()

function rotateAroundWorldAxis( object, axis, radians ) {

    var rotationMatrix = new THREE.Matrix4();

    rotationMatrix.makeRotationAxis( axis.normalize(), radians );
    rotationMatrix.multiplySelf( object.matrix );                       // pre-multiply
    object.matrix = rotationMatrix;
    object.rotation.setEulerFromRotationMatrix( object.matrix );
}

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

How can I read user input from the console?

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);
    

Using JAXB to unmarshal/marshal a List<String>

This can be done MUCH easier using wonderful XStream library. No wrappers, no annotations.

Target XML

<Strings>
  <String>a</String>
  <String>b</String>
</Strings>

Serialization

(String alias can be avoided by using lowercase string tag, but I used OP's code)

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");

XStream xStream = new XStream();
xStream.alias("Strings", List.class);
xStream.alias("String", String.class);
String result = xStream.toXML(list);

Deserialization

Deserialization into ArrayList

XStream xStream = new XStream();
xStream.alias("Strings", ArrayList.class);
xStream.alias("String", String.class);
xStream.addImplicitArray(ArrayList.class, "elementData");
List <String> result = (List <String>)xStream.fromXML(file);

Deserialization into String[]

XStream xStream = new XStream();
xStream.alias("Strings", String[].class);
xStream.alias("String", String.class);
String[] result = (String[])xStream.fromXML(file);

Note, that XStream instance is thread-safe and can be pre-configured, shrinking code amount to one-liners.

XStream can also be used as a default serialization mechanism for JAX-RS service. Example of plugging XStream in Jersey can be found here

Why does configure say no C compiler found when GCC is installed?

Install GCC in Ubuntu Debian Base

sudo apt-get install build-essential

How can I get the DateTime for the start of the week?

Ugly but it at least gives the right dates back

With start of week set by system:

    public static DateTime FirstDateInWeek(this DateTime dt)
    {
        while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
            dt = dt.AddDays(-1);
        return dt;
    }

Without:

    public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
    {
        while (dt.DayOfWeek != weekStartDay)
            dt = dt.AddDays(-1);
        return dt;
    }

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

WampServer orange icon

  • go to C:\wamp\bin\mysql\mysql5.6.17
  • look for "my.ini"; right click to edit it
    • use your favorite editor (notepad++, jedit…)
  • look for 3306 and change it to 3307
  • restart all the services and it should work :)

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

What does the @Valid annotation indicate in Spring?

Another handy aspect of @Valid not mentioned above is that (ie: using Postman to test an endpoint) @Valid will format the output of an incorrect REST call into formatted JSON instead of a blob of barely readable text. This is very useful if you are creating a commercially consumable API for your users.

fail to change placeholder color with Bootstrap 3

Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:

.form-control::-moz-placeholder {
  color: #999999;
  opacity: 1;
}
.form-control:-ms-input-placeholder {
  color: #999999;
}
.form-control::-webkit-input-placeholder {
  color: #999999;
}

Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:

form .form-control::-moz-placeholder {
  color: #fff;
  opacity: 1;
}
form .form-control:-ms-input-placeholder {
  color: #fff;
}
form .form-control::-webkit-input-placeholder {
  color: #fff;
}

Voila that will override bootstrap's CSS.

Android: How to handle right to left swipe gestures

You don't need complicated calculations. It can be done just by using OnGestureListener interface from GestureDetector class.

Inside onFling method you can detect all four directions like this:

MyGestureListener.java:

import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class MyGestureListener implements GestureDetector.OnGestureListener{

    private static final long VELOCITY_THRESHOLD = 3000;

    @Override
    public boolean onDown(final MotionEvent e){ return false; }

    @Override
    public void onShowPress(final MotionEvent e){ }

    @Override
    public boolean onSingleTapUp(final MotionEvent e){ return false; }

    @Override
    public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
                        final float distanceY){ return false; }

    @Override
    public void onLongPress(final MotionEvent e){ }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
                       final float velocityX,
                       final float velocityY){

        if(Math.abs(velocityX) < VELOCITY_THRESHOLD 
                    && Math.abs(velocityY) < VELOCITY_THRESHOLD){
            return false;//if the fling is not fast enough then it's just like drag
        }

        //if velocity in X direction is higher than velocity in Y direction,
        //then the fling is horizontal, else->vertical
        if(Math.abs(velocityX) > Math.abs(velocityY)){
            if(velocityX >= 0){
                Log.i("TAG", "swipe right");
            }else{//if velocityX is negative, then it's towards left
                Log.i("TAG", "swipe left");
            }
        }else{
            if(velocityY >= 0){
                Log.i("TAG", "swipe down");
            }else{
                Log.i("TAG", "swipe up");
            }
        }

        return true;
    }
}

usage:

GestureDetector mDetector = new GestureDetector(MainActivity.this, new MyGestureListener());

view.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(final View v, final MotionEvent event){
        return mDetector.onTouchEvent(event);
    }
});

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.

In LL(1)

  • First L stands for scanning input from Left to Right. Second L stands for Left Most Derivation. 1 stands for using one input symbol at each step.

For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).

Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I ran into this same issue. Someone had logged onto my computer and used their TFS credentials. I'm running VS2012, Windows 7, and the network admins have Credential Manager disabled.

Run this command from a command window with the same user your running visual studio as.

rundll32.exe keymgr.dll,KRShowKeyMgr

You'll see a popup with all your stored credentials. Remove the one for your TFS server.

Note: You will need to restart visual studio because it caches the tfs credentials.

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is the way.

It returns true if string1 is equals to string2 in value. Else, it will return false.

equals reference

Select top 1 result using JPA

Try like this

String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();

It should work

UPDATE*

You can also try like this

query.setMaxResults(1).getResultList();

Dealing with HTTP content in HTTPS pages

The accepted answer helped me update this both to PHP as well as CORS, so I thought I would include the solution for others:

pure PHP/HTML:

<?php // (the originating page, where you want to show the image)
// set your image location in whatever manner you need
$imageLocation = "http://example.com/exampleImage.png";

// set the location of your 'imageserve' program
$imageserveLocation = "https://example.com/imageserve.php";

// we'll look at the imageLocation and if it is already https, don't do anything, but if it is http, then run it through imageserve.php
$imageURL = (strstr("https://",$imageLocation)?"": $imageserveLocation . "?image=") . $imageLocation;

?>
<!-- this is the HTML image -->
<img src="<?php echo $imageURL ?>" />

javascript/jQuery:

<img id="theImage" src="" />
<script>
    var imageLocation = "http://example.com/exampleImage.png";
    var imageserveLocation = "https://example.com/imageserve.php";
    var imageURL = ((imageLocation.indexOf("https://") !== -1) ? "" : imageserveLocation + "?image=") + imageLocation;
    // I'm using jQuery, but you can use just javascript...        
    $("#theImage").prop('src',imageURL);
</script>

imageserve.php see http://stackoverflow.com/questions/8719276/cors-with-php-headers?noredirect=1&lq=1 for more on CORS

<?php
// set your secure site URL here (where you are showing the images)
$mySecureSite = "https://example.com";

// here, you can set what kinds of images you will accept
$supported_images = array('png','jpeg','jpg','gif','ico');

// this is an ultra-minimal CORS - sending trusted data to yourself 
header("Access-Control-Allow-Origin: $mySecureSite");

$parts = pathinfo($_GET['image']);
$extension = $parts['extension'];
if(in_array($extension,$supported_images)) {
    header("Content-Type: image/$extension");
    $image = file_get_contents($_GET['image']);
    echo $image;
}

Stop Excel from automatically converting certain text values to dates

While creating the string to be written to my CSV file in C# I had to format it this way:

"=\"" + myVariable + "\""

Printing an array in C++?

May I suggest using the fish bone operator?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(Can you spot it?)

Sorting A ListView By Column

I sort using column name to set any sorting specifics that may need to be handled based on data type stored in the column and or if the column has already been sorted on(asc/desc). Here's a snippet from my ColumnClick event handler.

private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListViewItemComparer sorter = GetListViewSorter(e.Column);

        listView.ListViewItemSorter = sorter;
        listView.Sort();
    }

    private ListViewItemComparer GetListViewSorter(int columnIndex)
    {
        ListViewItemComparer sorter = (ListViewItemComparer)listView.ListViewItemSorter;
        if (sorter == null)
        {
            sorter = new ListViewItemComparer();
        }

        sorter.ColumnIndex = columnIndex;

        string columnName = packagedEstimateListView.Columns[columnIndex].Name;
        switch (columnName)
        {
            case ApplicationModel.DisplayColumns.DateCreated:
            case ApplicationModel.DisplayColumns.DateUpdated:
                sorter.ColumnType = ColumnDataType.DateTime;
                break;
            case ApplicationModel.DisplayColumns.NetTotal:
            case ApplicationModel.DisplayColumns.GrossTotal:
                sorter.ColumnType = ColumnDataType.Decimal;
                break;
            default:
                sorter.ColumnType = ColumnDataType.String;
                break;
        }

        if (sorter.SortDirection == SortOrder.Ascending)
        {
            sorter.SortDirection = SortOrder.Descending;
        }
        else
        {
            sorter.SortDirection = SortOrder.Ascending;
        }

        return sorter;
    }

Below is my ListViewItemComparer

public class ListViewItemComparer : IComparer
{
    private int _columnIndex;
    public int ColumnIndex
    {
        get
        {
            return _columnIndex;
        }
        set
        {
            _columnIndex = value;
        }
    }

    private SortOrder _sortDirection;
    public SortOrder SortDirection
    {
        get
        {
            return _sortDirection;
        }
        set
        {
            _sortDirection = value;
        }
    }

    private ColumnDataType _columnType;
    public ColumnDataType ColumnType
    {
        get
        {
            return _columnType;
        }
        set
        {
            _columnType = value;
        }
    }


    public ListViewItemComparer()
    {
        _sortDirection = SortOrder.None;
    }

    public int Compare(object x, object y)
    {
        ListViewItem lviX = x as ListViewItem;
        ListViewItem lviY = y as ListViewItem;

        int result;

        if (lviX == null && lviY == null)
        {
            result = 0;
        }
        else if (lviX == null)
        {
            result = -1;
        }

        else if (lviY == null)
        {
            result = 1;
        }

        switch (ColumnType)
        {
            case ColumnDataType.DateTime:
                DateTime xDt = DataParseUtility.ParseDate(lviX.SubItems[ColumnIndex].Text);
                DateTime yDt = DataParseUtility.ParseDate(lviY.SubItems[ColumnIndex].Text);
                result = DateTime.Compare(xDt, yDt);
                break;

            case ColumnDataType.Decimal:
                Decimal xD = DataParseUtility.ParseDecimal(lviX.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                Decimal yD = DataParseUtility.ParseDecimal(lviY.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                result = Decimal.Compare(xD, yD);
                break;
            case ColumnDataType.Short:
                short xShort = DataParseUtility.ParseShort(lviX.SubItems[ColumnIndex].Text);
                short yShort = DataParseUtility.ParseShort(lviY.SubItems[ColumnIndex].Text);
                result = xShort.CompareTo(yShort);
                break;
            case ColumnDataType.Int:
                int xInt = DataParseUtility.ParseInt(lviX.SubItems[ColumnIndex].Text);
                int yInt = DataParseUtility.ParseInt(lviY.SubItems[ColumnIndex].Text);
                return xInt.CompareTo(yInt);
                break;
            case ColumnDataType.Long:
                long xLong = DataParseUtility.ParseLong(lviX.SubItems[ColumnIndex].Text);
                long yLong = DataParseUtility.ParseLong(lviY.SubItems[ColumnIndex].Text);
                return xLong.CompareTo(yLong);
                break;
            default:

                result = string.Compare(
                    lviX.SubItems[ColumnIndex].Text,
                    lviY.SubItems[ColumnIndex].Text,
                    false);

                break;
        }

        if (SortDirection == SortOrder.Descending)
        {
            return -result;
        }
        else
        {
            return result;
        }
    }
}

deleted object would be re-saved by cascade (remove deleted object from associations)

I also ran into this error on a badly designed database, where there was a Person table with a one2many relationship with a Code table and an Organization table with a one2many relationship with the same Code table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.

What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.

Display PDF within web browser

You can also have this simple GoogleDoc approach.

<a  style="color: green;" href="http://docs.google.com/gview?url=http://domain//docs/<?php echo $row['docname'] ;?>" target="_blank">View</a>

This would create a new page for you to view the doc without distorting your flow.

Inline JavaScript onclick function

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

SELECT DISTINCT on one column

Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():

SELECT  *
FROM    (SELECT ID, SKU, Product,
                ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
         FROM   MyTable
         WHERE  SKU LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

Calculate mean and standard deviation from a vector of samples in C++ using Boost

If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.

Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)

double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m =  sum / v.size();

double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
    accum += (d - m) * (d - m);
});

double stdev = sqrt(accum / (v.size()-1));

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

How to add target="_blank" to JavaScript window.location?

I have created a function that allows me to obtain this feature:

function redirect_blank(url) {
  var a = document.createElement('a');
  a.target="_blank";
  a.href=url;
  a.click();
}

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

Vertical Text Direction

rotation, like you did, is the way to go - but note that not all browsers support that. if you wan't to get a cross-browser solution, you'll have to generate pictures for that.

Styling input buttons for iPad and iPhone

I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css

p-button {
   -webkit-appearance: none !important;
}

i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)

button {
  -webkit-appearance: button;

}

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Creating a zero-filled pandas data frame

If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:

df_zeros = df * 0

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

ReactJS: setTimeout() not working?

Do

setTimeout(
    function() {
        this.setState({ position: 1 });
    }
    .bind(this),
    3000
);

Otherwise, you are passing the result of setState to setTimeout.

You can also use ES6 arrow functions to avoid the use of this keyword:

setTimeout(
  () => this.setState({ position: 1 }), 
  3000
);

ASP.NET postback with JavaScript

Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference

(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)

Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):

function RefreshGrid() {
    <%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}

Eclipse Indigo - Cannot install Android ADT Plugin

Execute eclipse with root level

$sudo /opt/eclipse/eclipse

Is calculating an MD5 hash less CPU intensive than SHA family functions?

MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

How can I position my jQuery dialog to center?

I'm pretty sure you shouldn't need to set a position:

$("#dialog").dialog();

should center by default.

I did have a look at the article, and also checked what it says on the official jquery-ui site about positioning a dialog : and in it were discussed 2 states of: initialise and after initialise.

Code examples - (taken from jQuery UI 2009-12-03)

Initialize a dialog with the position option specified.

$('.selector').dialog({ position: 'top' });

Get or set the position option, after init.

//getter
var position = $('.selector').dialog('option', 'position');
//setter
$('.selector').dialog('option', 'position', 'top');

I think that if you were to remove the position attribute you would find it centers by itself else try the second setter option where you define 3 elements of "option" "position" and "center".

How to convert a Map to List in Java?

a list of what ?

Assuming map is your instance of Map

  • map.values() will return a Collection containing all of the map's values.
  • map.keySet() will return a Set containing all of the map's keys.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

For Maven based projects you need a dependency.

<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
</dependency>

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Android Studio AVD - Emulator: Process finished with exit code 1

I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.

In android studio ,

Help Menu -> Show log in explorer.

It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"

  1. Try to run emulator from command prompt ,
  • Go to folder ~\Android\Sdk\emulator

  • Run this command:

    emulator.exe -netdelay none -netspeed full -avd <virtual device name> 
    
    ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
    

    You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt

  1. If you get error about vcruntime140 ,
  • Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator

  • Try step 1

  • If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1

  1. If you get error about msvcp140.dll
  • Search and download the appropriate msvcp140.dll file for your system from the internet (32 / 64 bit version)
  • Replace the file in the folder C:\Windows\System32 with file msvcp140.dll
  • Try step 1

If it runs , you can run it from Android Studio also.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png and drag in to the project.

Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:

enter image description here

I tested on Xcode 5 and an app was submitted without the missing retina icon warning.

Zero an array in C code

Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));

Vue.js data-bind style backgroundImage not working

The accepted answer didn't seem to solve the problem for me, but this did

Ensure your backgroundImage declarations are wrapped in url( and quotes so the style works correctly, no matter the file name.

ES2015 Style:

<div :style="{ backgroundImage: `url('${image}')` }"></div>

Or without ES2015:

<div :style="{ backgroundImage: 'url(\'' + image + '\')' }"></div>

Source: vuejs/vue-loader issue #646

Fast way to concatenate strings in nodeJS/JavaScript

The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.

Tested with the following code:

function a(){
    var s = "hello";
    var p = "world";
    s = s + p;
    return s;
}

function b(){
    var s = new Buffer("hello");
    var p = new Buffer("world");
    s = Buffer.concat([s,p]);
    return s;
}

var times = 100000;

var t1 = new Date();
for( var i = 0; i < times; i++){
    a();
}

var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
    b();
}

var t3 = new Date();

console.log("Buffer took: " + (t3-t2) + " ms.");

Output:

Normal took: 4 ms.
Buffer took: 458 ms.

SQL Server FOR EACH Loop

Off course an old question. But I have a simple solution where no need of Looping, CTE, Table variables etc.

DECLARE @MyVar datetime = '1/1/2010'    
SELECT @MyVar

SELECT DATEADD (DD,NUMBER,@MyVar) 
FROM master.dbo.spt_values 
WHERE TYPE='P' AND NUMBER BETWEEN 0 AND 4 
ORDER BY NUMBER

Note : spt_values is a Mircrosoft's undocumented table. It has numbers for every type. Its not suggestible to use as it can be removed in any new versions of sql server without prior information, since it is undocumented. But we can use it as quick workaround in some scenario's like above.

How can I run another application within a panel of my C# program?

I notice that all the prior answers use older Win32 User library functions to accomplish this. I think this will work in most cases, but will work less reliably over time.

Now, not having done this, I can't tell you how well it will work, but I do know that a current Windows technology might be a better solution: the Desktop Windows Manager API.

DWM is the same technology that lets you see live thumbnail previews of apps using the taskbar and task switcher UI. I believe it is closely related to Remote Terminal services.

I think that a probable problem that might happen when you force an app to be a child of a parent window that is not the desktop window is that some application developers will make assumptions about the device context (DC), pointer (mouse) position, screen widths, etc., which may cause erratic or problematic behavior when it is "embedded" in the main window.

I suspect that you can largely eliminate these problems by relying on DWM to help you manage the translations necessary to have an application's windows reliably be presented and interacted with inside another application's container window.

The documentation assumes C++ programming, but I found one person who has produced what he claims is an open source C# wrapper library: https://bytes.com/topic/c-sharp/answers/823547-desktop-window-manager-wrapper. The post is old, and the source is not on a big repository like GitHub, bitbucket, or sourceforge, so I don't know how current it is.

parse html string with jquery

MarvinS.-

Try:

$.ajax({  
        url: uri+'?js',  
        success: function(data) {  
                var imgAttr = $("img", data).attr('src'); 
                var htmlCode = $(data).html();
                $('#imgSrc').html(imgAttr);
                $('#fullHtmlOutput').html(htmlCode);
        }  
    });

This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

How do I add to the Windows PATH variable using setx? Having weird problems

I was having such trouble managing my computer labs when the %PATH% environment variable approached 1024 characters that I wrote a Powershell script to fix it.

You can download the code here: https://gallery.technet.microsoft.com/scriptcenter/Edit-and-shorten-PATH-37ef3189

You can also use it as a simple way to safely add, remove and parse PATH entries. Enjoy.

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

Centering in CSS Grid

I know this question is a couple years old, but I am surprised to find that no one suggested:

   text-align: center;

this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):

=TEXT(A1,"mm-yyyy")

Or this formula (it's more strict, it will return #VALUE error if A1 is not date):

=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)

How to programmatically click a button in WPF?

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

How to do this in Laravel, subquery where in

Consider this code:

Products::whereIn('id', function($query){
    $query->select('paper_type_id')
    ->from(with(new ProductCategory)->getTable())
    ->whereIn('category_id', ['223', '15'])
    ->where('active', 1);
})->get();

simple Jquery hover enlarge

If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:

$(document).ready(function() {
    $("[id^=content]").hover(function() {
        $(this).addClass('transition');
    }, function() {
        $(this).removeClass('transition');
    });
});

Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.

Get startup type of Windows service using PowerShell

You can also use the sc tool to set it.

You can also call it from PowerShell and add additional checks if needed. The advantage of this tool vs. PowerShell is that the sc tool can also set the start type to auto delayed.

# Get Service status
$Service = "Wecsvc"
sc.exe qc $Service

# Set Service status
$Service = "Wecsvc"
sc.exe config $Service start= delayed-auto

Catching errors in Angular HttpClient

Following @acdcjunior answer, this is how I implemented it

service:

  get(url, params): Promise<Object> {

            return this.sendRequest(this.baseUrl + url, 'get', null, params)
                .map((res) => {
                    return res as Object
                }).catch((e) => {
                    return Observable.of(e);
                })
                .toPromise();
        }

caller:

this.dataService.get(baseUrl, params)
            .then((object) => {
                if(object['name'] === 'HttpErrorResponse') {
                            this.error = true;
                           //or any handle
                } else {
                    this.myObj = object as MyClass 
                }
           });

Get user's current location

You may want to take a look at GeoIP Country Whois Locator found at PHPClasses.

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.

Javascript negative number

This is an old question but it has a lot of views so I think that is important to update it.

ECMAScript 6 brought the function Math.sign(), which returns the sign of a number (1 if it's positive, -1 if it's negative) or NaN if it is not a number. Reference

You could use it as:

var number = 1;

if(Math.sign(number) === 1){
    alert("I'm positive");
}else if(Math.sign(number) === -1){
    alert("I'm negative");
}else{
    alert("I'm not a number");
}

Call a url from javascript

You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.

$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.

Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

Testing javascript with Mocha - how can I use console.log to debug a test?

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

AngularJS does not send hidden field value

I had facing the same problem, I really need to send a key from my jsp to java script, It spend around 4h or more of my day to solve it.

I include this tag on my JavaScript/JSP:

_x000D_
_x000D_
 $scope.sucessMessage = function (){  _x000D_
     var message =     ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);_x000D_
     $scope.inforMessage = message;_x000D_
     alert(message);  _x000D_
}_x000D_
 _x000D_
_x000D_
String.prototype.format = function() {_x000D_
    var formatted = this;_x000D_
    for( var arg in arguments ) {_x000D_
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);_x000D_
    }_x000D_
    return formatted;_x000D_
};
_x000D_
<!-- Messages definition -->_x000D_
<input type="hidden"  name="sucess"   ng-init="messages.sucess='<fmt:message  key='portfolio.create.sucessMessage' />'" >_x000D_
_x000D_
<!-- Message showed affter insert -->_x000D_
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">_x000D_
    {{inforMessage}}_x000D_
</div>_x000D_
_x000D_
<!-- properties_x000D_
  portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
_x000D_
_x000D_
_x000D_

The result was: Portfólio 1 criado com sucesso! ID=3.

Best Regards

gitignore all files of extension in directory

I have tried opening the .gitignore file in my vscode, windows 10. There you can see, some previously added ignore files (if any).

To create a new rule to ignore a file with (.js) extension, append the extension of the file like this:

*.js

This will ignore all .js files in your git repository.

To exclude certain type of file from a particular directory, you can add this:

**/foo/*.js

This will ignore all .js files inside only /foo/ directory.

For a detailed learning you can visit: about git-ignore

Retrieving JSON Object Literal from HttpServletRequest

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);

What is the difference between properties and attributes in HTML?

When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element:

<input type="text" value="Name:">

has 2 attributes (type and value).

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:

<input id="the-input" type="text" value="Name:">

the corresponding DOM node will have id,type, and value properties (among others):

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn't modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn't reflect the value attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
    

    The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

    So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue property, which is a pure reflection of the value attribute:

    theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
    

There are several properties that directly reflect their attribute (rel, id), some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. The spec covers the various kinds of reflection.

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

How to implement a FSM - Finite State Machine in Java

Hmm, I would suggest that you use Flyweight to implement the states. Purpose: Avoid the memory overhead of a large number of small objects. State machines can get very, very big.

http://en.wikipedia.org/wiki/Flyweight_pattern

I'm not sure that I see the need to use design pattern State to implement the nodes. The nodes in a state machine are stateless. They just match the current input symbol to the available transitions from the current state. That is, unless I have entirely forgotten how they work (which is a definite possiblilty).

If I were coding it, I would do something like this:

interface FsmNode {
  public boolean canConsume(Symbol sym);
  public FsmNode consume(Symbol sym);
  // Other methods here to identify the state we are in
}

  List<Symbol> input = getSymbols();
  FsmNode current = getStartState();
  for (final Symbol sym : input) {
    if (!current.canConsume(sym)) {
      throw new RuntimeException("FSM node " + current + " can't consume symbol " + sym);
    }
    current = current.consume(sym);
  }
  System.out.println("FSM consumed all input, end state is " + current);

What would Flyweight do in this case? Well, underneath the FsmNode there would probably be something like this:

Map<Integer, Map<Symbol, Integer>> fsm; // A state is an Integer, the transitions are from symbol to state number
FsmState makeState(int stateNum) {
  return new FsmState() {
    public FsmState consume(final Symbol sym) {
      final Map<Symbol, Integer> transitions = fsm.get(stateNum);
      if (transisions == null) {
        throw new RuntimeException("Illegal state number " + stateNum);
      }
      final Integer nextState = transitions.get(sym);  // May be null if no transition
      return nextState;
    }
    public boolean canConsume(final Symbol sym) {
      return consume(sym) != null;
    }
  }
}

This creates the State objects on a need-to-use basis, It allows you to use a much more efficient underlying mechanism to store the actual state machine. The one I use here (Map(Integer, Map(Symbol, Integer))) is not particulary efficient.

Note that the Wikipedia page focuses on the cases where many somewhat similar objects share the similar data, as is the case in the String implementation in Java. In my opinion, Flyweight is a tad more general, and covers any on-demand creation of objects with a short life span (use more CPU to save on a more efficient underlying data structure).

Zooming MKMapView to fit annotation pins?

For iOS 7 and above (Referring MKMapView.h) :

// Position the map such that the provided array of annotations are all visible to the fullest extent possible.          

- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

remark from – Abhishek Bedi

You just call:

 [yourMapView showAnnotations:@[yourAnnotation] animated:YES];

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

Rock, Paper, Scissors Game Java

Why not check for what the user entered and then ask the user to enter correct input again?

eg:

//Get player's play from input-- note that this is 
// stored as a string 
System.out.println("Enter your play: "); 
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
  personPlay = response;
}else{
  System.out.println("Invaild Input")
}

for the other modifications, please check my total code at pastebin

Reduce left and right margins in matplotlib plot

For me, the answers above did not work with matplotlib.__version__ = 1.4.3 on Win7. So, if we are only interested in the image itself (i.e., if we don't need annotations, axis, ticks, title, ylabel etc), then it's better to simply save the numpy array as image instead of savefig.

from pylab import *

ax = subplot(111)
ax.imshow(some_image_numpyarray)
imsave('test.tif', some_image_numpyarray)

# or, if the image came from tiff or png etc
RGBbuffer = ax.get_images()[0].get_array()
imsave('test.tif', RGBbuffer)

Also, using opencv drawing functions (cv2.line, cv2.polylines), we can do some drawings directly on the numpy array. http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

Change event on select with knockout binding, how can I know if it is a real change?

use this:

this.permissionChanged = function (obj, event) {

    if (event.type != "load") {

    } 
}

How to send post request with x-www-form-urlencoded body

For HttpEntity, the below answer works

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

For reference: How to POST form data with Spring RestTemplate?

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

$(window).width() not the same as media query

if you want to check the width screen in the device every 1 second you can do

 setInterval(function() {
        if (window.matchMedia('(max-width: 767px)').matches) {
            alert('here')
        } else {
            alert('i am ')
        }
    }, 1000);

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

I had the same problem, i.e. all privileges granted for root:

SHOW GRANTS FOR 'root'@'localhost'\G
*************************** 1. row ***************************
Grants for root@localhost: GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*[blabla]' WITH GRANT OPTION

...but still not allowed to create a table:

 create table t3(id int, txt varchar(50), primary key(id));
ERROR 1142 (42000): CREATE command denied to user 'root'@'localhost' for table 't3'

Well, it was cause by an annoying user error, i.e. I didn't select a database. After issuing USE dbname it worked fine.

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

POST data with request module on Node.JS

I have to get the data from a POST method of the PHP code. What worked for me was:

const querystring = require('querystring');
const request = require('request');

const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };

params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'

request.post({
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
  url: link,
  body: params,
}, function(error, response, body){
  console.log(body);
});

How to access host port from docker container

For all platforms

Docker v 20.10 and above (since December 14th 2020)

On Linux, add --add-host=host.docker.internal:host-gateway to your Docker command to enable this feature. (See below for Docker Compose configuration.)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

To enable this in Docker Compose on Linux, add the following lines to the container definition:

extra_hosts:
- "host.docker.internal:host-gateway"

For macOS and Windows

Docker v 18.03 and above (since March 21st 2018)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

Linux support pending https://github.com/docker/for-linux/issues/264

MacOS with earlier versions of Docker

Docker for Mac v 17.12 to v 18.02

Same as above but use docker.for.mac.host.internal instead.

Docker for Mac v 17.06 to v 17.11

Same as above but use docker.for.mac.localhost instead.

Docker for Mac 17.05 and below

To access host machine from the docker container you must attach an IP alias to your network interface. You can bind whichever IP you want, just make sure you're not using it to anything else.

sudo ifconfig lo0 alias 123.123.123.123/24

Then make sure that you server is listening to the IP mentioned above or 0.0.0.0. If it's listening on localhost 127.0.0.1 it will not accept the connection.

Then just point your docker container to this IP and you can access the host machine!

To test you can run something like curl -X GET 123.123.123.123:3000 inside the container.

The alias will reset on every reboot so create a start-up script if necessary.

Solution and more documentation here: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

All shards failed

first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like

  1. Shards are actually in non-recoverable state, if your cluster and index state are in Yellow and RED, then it is one of the reason.
  2. Due to some shard recovery happening in background, shards didn't respond.
  3. Due to bad syntax of your query, ES responds in all shards failed.

In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.

The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.

Call angularjs function using jquery/javascript

Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.

Example:

_x000D_
_x000D_
angular.module("app", []).component("component", {_x000D_
  controller: ["$window", function($window) {_x000D_
    var self = this;_x000D_
    _x000D_
    self.logg = function() {_x000D_
      console.log("logging!");_x000D_
    };_x000D_
    _x000D_
    $window.angularControllerLogg = self.logg;_x000D_
  }_x000D_
});_x000D_
               _x000D_
window.angularControllerLogg();
_x000D_
_x000D_
_x000D_