Programs & Examples On #Moniker

Implementing IDisposable correctly

You have no need to do your User class being IDisposable since the class doesn't acquire any non-managed resources (file, database connection, etc.). Usually, we mark classes as IDisposable if they have at least one IDisposable field or/and property. When implementing IDisposable, better put it according Microsoft typical scheme:

public class User: IDisposable {
  ...
  protected virtual void Dispose(Boolean disposing) {
    if (disposing) {
      // There's no need to set zero empty values to fields 
      // id = 0;
      // name = String.Empty;
      // pass = String.Empty;

      //TODO: free your true resources here (usually IDisposable fields)
    }
  }

  public void Dispose() {
    Dispose(true);

    GC.SuppressFinalize(this);
  } 
}

How to create own dynamic type or dynamic object in C#?

dynamic MyDynamic = new ExpandoObject();

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

.then() is chainable and will wait for previous .then() to resolve.

.success() and .error() can be chained, but they will all fire at once (so not much point to that)

.success() and .error() are just nice for simple calls (easy makers):

$http.post('/getUser').success(function(user){ 
   ... 
})

so you don't have to type this:

$http.post('getUser').then(function(response){
  var user = response.data;
})

But generally i handler all errors with .catch():

$http.get(...)
    .then(function(response){ 
      // successHandler
      // do some stuff
      return $http.get('/somethingelse') // get more data
    })
    .then(anotherSuccessHandler)
    .catch(errorHandler)

If you need to support <= IE8 then write your .catch() and .finally() like this (reserved methods in IE):

    .then(successHandler)
    ['catch'](errorHandler)

Working Examples:

Here's something I wrote in more codey format to refresh my memory on how it all plays out with handling errors etc:

http://jsfiddle.net/nalberg/v95tekz2/

Create nice column output in python

This sets independent, best-fit column widths based on the max-metric used in other answers.

data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
padding = 2
col_widths = [max(len(w) for w in [r[cn] for r in data]) + padding for cn in range(len(data[0]))]
format_string = "{{:{}}}{{:{}}}{{:{}}}".format(*col_widths)
for row in data:
    print(format_string.format(*row))

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

How get value from URL

You can get that value by using the $_GET array. So the id value would be stored in $_GET['id'].

So in your case you could store that value in the $id variable as follows:

$id = $_GET['id'];

Get current date in milliseconds

You can use following methods to get current date in milliseconds.

[[NSDate date] timeIntervalSince1970];

OR

double CurrentTime = CACurrentMediaTime(); 

Source: iPhone: How to get current milliseconds?

Adding a new array element to a JSON object

For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.

'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


});

Storage.prototype.setObj = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObj = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

After adding JSON object to Array result is (in LocalStorage):

[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]

after this action you can easily send data to server as List in Java

Full code example is here

How do I store a simple cart using localStorage?

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Why doesn't git recognize that my file has been changed, therefore git add not working

I had some git submodule misconfiguration. I went to repo's root and issued these commands on the directories that had .git folders previously:

git rm --cached sub/directory/path -f

Then the directories appeared in git status.

You may want to make a copy of your repo before trying this just in case.

Android - How to achieve setOnClickListener in Kotlin?

Here's the solution. Your code will like this:

button.setOnClickListener {
            //your code here
        }

No need to add anything. like below:

val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {

}

What are .NET Assemblies?

See this:

In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security

Required attribute HTML5

Safari 7.0.5 still does not support notification for validation of input fields.

To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA

To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation

function hasHtml5Validation () {
  //Check if validation supported && not safari
  return (typeof document.createElement('input').checkValidity === 'function') && 
    !(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}

$('form').submit(function(){
    if(!hasHtml5Validation())
    {
        var isValid = true;
        var $inputs = $(this).find('[required]');
        $inputs.each(function(){
            var $input = $(this);
            $input.removeClass('invalid');
            if(!$.trim($input.val()).length)
            {
                isValid = false;
                $input.addClass('invalid');                 
            }
        });
        if(!isValid)
        {
            return false;
        }
    }
});

SASS / LESS:

input, select, textarea {
    @include appearance(none);
    border-radius: 0px;

    &.invalid {
        border-color: red !important;
    }
}

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

Touch move getting stuck Ignored attempt to cancel a touchmove

I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.

My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this

function onTouchStart() {
  window.addEventListener("touchmove", handleTouchMove, {
    passive: false
  });
}

function onTouchEnd() {
  window.removeEventListener("touchmove", handleTouchMove, {
    passive: true
  });
}

function handleTouchMove(e) {
  e.preventDefault();
}

For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:

let stopScrolling = false;

window.addEventListener("touchmove", handleTouchMove, {
  passive: false
});

function handleTouchMove(e) {
  if (!stopScrolling) {
    return;
  }
  e.preventDefault();
}

function onTouchStart() {
  stopScrolling = true;
}

function onTouchEnd() {
  stopScrolling = false;
}

I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!

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

Truth values can be described using a Boolean algebra. The article also contains tables for and and or. This should help you to get started or to get even more confused.

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

How do I read image data from a URL in Python?

select the image in chrome, right click on it, click on Copy image address, paste it into a str variable (my_url) to read the image:

import shutil
import requests

my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
    shutil.copyfileobj(response.raw, file)
del response

open it;

from PIL import Image

img = Image.open('my_image.png')
img.show()

How to reset settings in Visual Studio Code?

If you want to reset everything, go to %userprofile%\AppData\Roaming\Code and delete the whole folder after you uninstall the VS code, then install it again.

Also in %userprofile%\.vscode delete extensions folder in case you want to delete all extensions.

Get environment value in controller

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.

$_ENV['yourkeyhere'];

Java: JSON -> Protobuf & back conversion

For protobuf 2.5, use the dependency:

"com.googlecode.protobuf-java-format" % "protobuf-java-format" % "1.2"

Then use the code:

com.googlecode.protobuf.format.JsonFormat.merge(json, builder)
com.googlecode.protobuf.format.JsonFormat.printToString(proto)

What do numbers using 0x notation mean?

Literals that start with 0x are hexadecimal integers. (base 16)

The number 0x6400 is 25600.

6 * 16^3 + 4 * 16^2 = 25600

For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)

The number 0x6BF0 is 27632.

6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576    + 2816      + 240       = 27632

asp.net validation to make sure textbox has integer values

simpally add this code:

<asp:FilteredTextBoxExtender ID="txtAltitudeMin_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtAltitudeMin" FilterType="Numbers"></asp:FilteredTextBoxExtender>

How to get a list column names and datatypes of a table in PostgreSQL?

To get information about the table's column, you can use:

\dt+ [tablename]

To get information about the datatype in the table, you can use:

\dT+ [datatype]

Django DB Settings 'Improperly Configured' Error

In my case, I got this when trying to run Django tests through PyCharm. I think it is because PyCharm does not load the initial Django project settings, i.e. those that manage.py shell runs initially. One can add them to the start of the testing script or just run the tests using manage.py test.

Versions:

  • Python 3.5 (in virtualenv)
  • PyCharm 2016.3.2 Professional
  • Django 1.10

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

  using (MemoryStream mem = new MemoryStream())
  {
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);

    // Add a WorkbookPart to the document.
    WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet(new SheetData());

    // Add Sheets to the Workbook.
    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

    // Add a row to the cell table.
    Row row;
    row = new Row() { RowIndex = 1 };
    sheetData.Append(row);

    // In the new row, find the column location to insert a cell in A1.  
    Cell refCell = null;
    foreach (Cell cell in row.Elements<Cell>())
    {
      if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
      {
        refCell = cell;
        break;
      }
    }

    // Add the cell to the cell table at A1.
    Cell newCell = new Cell() { CellReference = "A1" };
    row.InsertBefore(newCell, refCell);

    // Set the cell value to be a numeric value of 100.
    newCell.CellValue = new CellValue("100");
    newCell.DataType = new EnumValue<CellValues>(CellValues.Number);

    // Append a new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet()
    {
      Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
      SheetId = 1,
      Name = "mySheet"
    };

    sheets.Append(sheet);

    workbookpart.Workbook.Save();
    spreadsheetDocument.Close();

    return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
  }

How to download a file from a website in C#

You may need to know the status during the file download or use credentials before making the request.

Here is an example that covers these options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

client.DownloadProgressChanged += (o, e) =>
{
    Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (o, e) => 
{
    Console.WriteLine("Download finished!");
};

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Click on Start menu > Programs > Microsoft Sql Server > Configuration Tools

  2. Select Sql Server Surface Area Configuration.

  3. Now click on Surface Area configuration for services and connections

  4. On the left pane of pop up window click on Remote Connections and Select Local and Remote connections radio button.

  5. Select Using both TCP/IP and named pipes radio button.

  6. click on apply and ok.

Now when try to connect to sql server using sql username and password u'll get the error mentioned below

Cannot connect to SQLEXPRESS.

ADDITIONAL INFORMATION:

Login failed for user 'username'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) ation To fix this error follow steps mentioned below

  1. connect to sql server using window authentication.

  2. Now right click on your server name at the top in left pane and select properties.

  3. Click on security and select sql server and windows authentication mode radio button.

  4. Click on OK.

  5. restart sql server servive by right clicking on server name and select restart.

Now your problem should be fixed and u'll be able to connect using sql server username and password.

Have fun. Ateev Gupta

android : Error converting byte to dex

I met the same problem,and i clean project ,some other problems causeed can not clean,so i manually delete dir 'build' ,so it can can clean Ok,then run it ok for me.

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

Transferring files over SSH

You need to specify both source and destination, and if you want to copy directories you should look at the -r option.

So to recursively copy /home/user/whatever from remote server to your current directory:

scp -pr user@remoteserver:whatever .

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

Break a previous commit into multiple commits

If you just want to extract something from existing commit and keep the original one, you can use

git reset --patch HEAD^

instead of git reset HEAD^. This command allows you to reset just chunks you need.

After you chose the chunks you want to reset, you'll have staged chunks that will reset changes in previous commit after you do

git commit --amend --no-edit

and unstaged chunks that you can add to the separate commit by

git add .
git commit -m "new commit"

Off topic fact:

In mercurial they have hg split - the second feature after hg absorb I'd like to see in git.

UL list style not applying

Turns out that YUI's reset CSS strips the list style from 'ul li' instead of just 'ul', which is why setting it just in 'ul' never worked.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

On SQL Server 2008 R2, I had a mismatch in table columns that caused the Rollback error. It went away when I fixed my sqlcmd table variable populated by the insert-exec statement to match that returned by the stored proc. It was missing org_code. In a windows cmd file, it loads result of stored procedure and selects it.

set SQLTXT= declare @resets as table (org_id nvarchar(9), org_code char(4), ^
tin(char9), old_strt_dt char(10), strt_dt char(10)); ^
insert @resets exec rsp_reset; ^
select * from @resets;

sqlcmd -U user -P pass -d database -S server -Q "%SQLTXT%" -o "OrgReport.txt"

How do I remove all null and empty string values from an object?

Using some ES6 / ES2015:

If you don't like to create an extra function and remove the items 'inline'.

Object.keys(obj).forEach(k => (!obj[k] && obj[k] !== undefined) && delete obj[k]);

jsbin

Same, written as a function.

const removeEmpty = (obj) => {
  Object.keys(obj).forEach((k) => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
  return obj;
};

jsbin

This function uses recursion to delete items from nested objects as well:

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(k =>
    (obj[k] && typeof obj[k] === 'object') && removeEmpty(obj[k]) ||
    (!obj[k] && obj[k] !== undefined) && delete obj[k]
  );
  return obj;
};

jsbin

Same as function before but with ES7 / 2016 Object.entries:

const removeEmpty = (obj) => {
  Object.entries(obj).forEach(([key, val])  =>
    (val && typeof val === 'object') && removeEmpty(val) ||
    (val === null || val === "") && delete obj[key]
  );
  return obj;
};

Same as third example but in plain ES5:

function removeEmpty(obj) {
  Object.keys(obj).forEach(function(key) {
    (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
    (obj[key] === '' || obj[key] === null) && delete obj[key]
  });
  return obj;
};

jsbin

The network path was not found

Same problem with me. I solved this by adding @ before connection string (C# has a thing called 'String Literals') like so:

SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");

sconnection.Open();

How to put sshpass command inside a bash script?

Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.

sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'

Regex for parsing directory and filename

What language? and why use regex for this simple task?

If you must:

^(.*)/([^/]*)$

gives you the two parts you wanted. You might need to quote the parentheses:

^\(.*\)/\([^/]*\)$

depending on your preferred language syntax.

But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.

Angular File Upload

  1. HTML

    <div class="form-group">
      <label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
    </div>

    <button type="button" (click)="RequestUpload()">Ok</button>

  1. ts File
public formData = new FormData();
ReqJson: any = {};

uploadFiles( file ) {
        console.log( 'file', file )
        for ( let i = 0; i < file.length; i++ ) {
            this.formData.append( "file", file[i], file[i]['name'] );
        }
    }

RequestUpload() {
        this.ReqJson["patientId"] = "12"
        this.ReqJson["requesterName"] = "test1"
        this.ReqJson["requestDate"] = "1/1/2019"
        this.ReqJson["location"] = "INDIA"
        this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
            this.http.post( '/Request', this.formData )
                .subscribe(( ) => {                 
                });     
    }
  1. Backend Spring(java file)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Request {
    private static String UPLOADED_FOLDER = "c://temp//";

    @PostMapping("/Request")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
        System.out.println("Json is" + Info);
        if (file.isEmpty()) {
            return "No file attached";
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Succuss";
    }
}

We have to create a folder "temp" in C drive, then this code will print the Json in console and save the uploaded file in the created folder

Can I use DIV class and ID together in CSS?

Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.

Password must have at least one non-alpha character

An expression like this:

[a-zA-Z]*[0-9\+\*][a-zA-Z0-9\+\*]*

should work just fine (obviously insert any additional special characters you want to allow or use ^ operator to match anything except letters/numbers); no need to use complicated lookarounds. This approach makes sense if you only want to allow a certain subset of special characters that you know are "safe", and disallow all others.

If you want to include all special characters except certain ones which you know are "unsafe", then it makes sense to use something like:

\w[^\\]*[^a-zA-Z\\][^\\]*

In this case, you are explicitly disallowing backslashes in your password and allowing any combination with at least one non-alphabetic character otherwise.

The expression above will match any string containing letters and at least one number or +,*. As for the "length of 8" requirement, theres really no reason to check that using regex.

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

Rails: How do I create a default value for attributes in Rails activerecord's model?

For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.

For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).

Rather, you want to set the attribute in a before_validation on: create, like so:

before_validation :set_status_because_rails_cannot, on: :create

def set_status_because_rails_cannot
  self.status ||= 'P'
end

How to wrap text in textview in Android

Use app:breakStrategy="simple" in AppCompatTextView, it will control over paragraph layout.

It has three constant values

  • balanced
  • high_quality
  • simple

Designing in your TextView xml

<android.support.v7.widget.AppCompatTextView
        android:id="@+id/textquestion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:scrollHorizontally="false"
        android:text="Your Question Display Hear....Your Question Display Hear....Your Question Display Hear....Your Question Display Hear...."
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:textStyle="bold"
        app:breakStrategy="simple" />

If your current minimum api level is 23 or more then in Coding

yourtextview.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE);

For more refrence refer this BreakStrategy

Textview breakStrategy image

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The error you're seeing means the data you receive from the remote end isn't valid JSON. JSON (according to the specifiation) is normally UTF-8, but can also be UTF-16 or UTF-32 (in either big- or little-endian.) The exact error you're seeing means some part of the data was not valid UTF-8 (and also wasn't UTF-16 or UTF-32, as those would produce different errors.)

Perhaps you should examine the actual response you receive from the remote end, instead of blindly passing the data to json.loads(). Right now, you're reading all the data from the response into a string and assuming it's JSON. Instead, check the content type of the response. Make sure the webpage is actually claiming to give you JSON and not, for example, an error message that isn't JSON.

(Also, after checking the response use json.load() by passing it the file-like object returned by opener.open(), instead of reading all data into a string and passing that to json.loads().)

how to get all child list from Firebase android

Firebase stores a sequence of values in this format:

"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"

If that is how you have them, you are getting the wrong type. The above structure is represented as a Map, not as a List:

mFirebaseRef = new Firebase(FIREBASE_URL);

mFirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

        List<Object> values = td.values();

        //notifyDataSetChanged();
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

System.Net.WebException HTTP status code

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

Definition of a Balanced Tree

There's no difference between these two things. Think about it.

Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?

There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.

It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).

Why is quicksort better than mergesort?

Quick sort is an in-place sorting algorithm, so its better suited for arrays. Merge sort on the other hand requires extra storage of O(N), and is more suitable for linked lists.

Unlike arrays, in liked list we can insert items in the middle with O(1) space and O(1) time, therefore the merge operation in merge sort can be implemented without any extra space. However, allocating and de-allocating extra space for arrays have an adverse effect on the run time of merge sort. Merge sort also favors linked list as data is accessed sequentially, without much random memory access.

Quick sort on the other hand requires a lot of random memory access and with an array we can directly access the memory without any traversing as required by linked lists. Also quick sort when used for arrays have a good locality of reference as arrays are stored contiguously in memory.

Even though both sorting algorithms average complexity is O(NlogN), usually people for ordinary tasks uses an array for storage, and for that reason quick sort should be the algorithm of choice.

EDIT: I just found out that merge sort worst/best/avg case is always nlogn, but quick sort can vary from n2(worst case when elements are already sorted) to nlogn(avg/best case when pivot always divides the array in two halves).

How to add style from code behind?

You can use the CssClass property of the hyperlink:

LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        background-color:Red;
                    }
                    .d:hover
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
        this.HyperLink1.CssClass = "d";

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

How to perform a for loop on each character in a string in Bash?

You can use a C-style for loop:

foo=string
for (( i=0; i<${#foo}; i++ )); do
  echo "${foo:$i:1}"
done

${#foo} expands to the length of foo. ${foo:$i:1} expands to the substring starting at position $i of length 1.

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

How to get current url in view in asp.net core 1.0

public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
{
    var rq = httpContext.Request;
    return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
}

How to disable a button when an input is empty?

Another way to check is to inline the function, so that the condition will be checked on every render (every props and state change)

const isDisabled = () => 
  // condition check

This works:

<button
  type="button"
  disabled={this.isDisabled()}
>
  Let Me In
</button>

but this will not work:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>

What's the fastest algorithm for sorting a linked list?

As I know, the best sorting algorithm is O(n*log n), whatever the container - it's been proved that sorting in the broad sense of the word (mergesort/quicksort etc style) can't go lower. Using a linked list will not give you a better run time.

The only one algorithm which runs in O(n) is a "hack" algorithm which relies on counting values rather than actually sorting.

Apache: Restrict access to specific source IP inside virtual host

In Apache 2.4, the authorization configuration syntax has changed, and the Order, Deny or Allow directives should no longer be used.

The new way to do this would be:

<VirtualHost *:8080>
    <Location />
        Require ip 192.168.1.0
    </Location>
    ...
</VirtualHost>

Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2

How to change Jquery UI Slider handle

You also should set border:none to that css class.

How do MySQL indexes work?

Basically an index is a map of all your keys that is sorted in order. With a list in order, then instead of checking every key, it can do something like this:

1: Go to middle of list - is higher or lower than what I'm looking for?

2: If higher, go to halfway point between middle and bottom, if lower, middle and top

3: Is higher or lower? Jump to middle point again, etc.

Using that logic, you can find an element in a sorted list in about 7 steps, instead of checking every item.

Obviously there are complexities, but that gives you the basic idea.

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

How to get href value using jQuery?

If your html link is like this:

<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

Then you can access the href in jquery as given below (there is no need to use "a" in href for this)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}

"The import org.springframework cannot be resolved."

Add the following JPA dependency.

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

How do I convert a TimeSpan to a formatted string?

According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:

dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"

Iterator over HashMap in Java

The cleanest way is to not (directly) use an iterator at all:

  • type your map with generics
  • use a foreach loop to iterate over the entries:

Like this:

Map<Integer, String> hm = new HashMap<Integer, String>();

hm.put(0, "zero");
hm.put(1, "one");

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    // do something with the entry
    System.out.println(entry.getKey() + " - " + entry.getValue());
    // the getters are typed:
    Integer key = entry.getKey();
    String value = entry.getValue();
}

This is way more efficient than iterating over keys, because you avoid n calls to get(key).

Displaying files (e.g. images) stored in Google Drive on a website

Solution provided by Niutech worked for me i.e.

http://googledrive.com/host/<folderID>/<filename>

But there are 2 outstanding issues

  1. You cannot have 2 files with the same name in the same folder in the drive else this link won't work.

  2. It is not yet clear but Google seems to be planning to deprecate image hosting via drive. please see the link below. https://support.google.com/richmedia/answer/6098968?hl=en

Implement a simple factory pattern with Spring 3 annotations

You can manually ask Spring to Autowire it.

Have your factory implement ApplicationContextAware. Then provide the following implementation in your factory:

@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
}

and then do the following after creating your bean:

YourBean bean = new YourBean();
applicationContext.getAutowireCapableBeanFactory().autowireBean(bean);
bean.init(); //If it has an init() method.

This will autowire your LocationService perfectly fine.

Datatable date sorting dd/mm/yyyy issue

Another solution: https://datatables.net/blog/2014-12-18

with 2 JavaScript libraries:

  1. cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js
  2. cdn.datatables.net/plug-ins/1.10.15/sorting/datetime-moment.js

then only this :

$(document).ready(function() {
   $.fn.dataTable.moment( 'DD/MM/YYYY' );
   $('#example').DataTable(); 
});

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

sql delete statement where date is greater than 30 days

Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

SELECT * 
FROM Results 
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)

Is there a difference between "==" and "is"?

Most of them already answered to the point. Just as an additional note (based on my understanding and experimenting but not from a documented source), the statement

== if the objects referred to by the variables are equal

from above answers should be read as

== if the objects referred to by the variables are equal and objects belonging to the same type/class

. I arrived at this conclusion based on the below test:

list1 = [1,2,3,4]
tuple1 = (1,2,3,4)

print(list1)
print(tuple1)
print(id(list1))
print(id(tuple1))

print(list1 == tuple1)
print(list1 is tuple1)

Here the contents of the list and tuple are same but the type/class are different.

Creating Roles in Asp.net Identity MVC 5

Here we go:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));


   if(!roleManager.RoleExists("ROLE NAME"))
   {
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
      role.Name = "ROLE NAME";
      roleManager.Create(role);

    }

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.

Is this a good way to clone an object in ES6?

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

Python loop that also accesses previous and next values

Pythonic and elegant way:

objects = [1, 2, 3, 4, 5]
value = 3
if value in objects:
   index = objects.index(value)
   previous_value = objects[index-1]
   next_value = objects[index+1] if index + 1 < len(objects) else None

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
     array[index]                -> obj      or nil
     array[start, length]        -> an_array or nil
     array[range]                -> an_array or nil
     array.slice(index)          -> obj      or nil
     array.slice(start, length)  -> an_array or nil
     array.slice(range)          -> an_array or nil
------------------------------------------------------------------------
     Element Reference---Returns the element at index, or returns a 
     subarray starting at start and continuing for length elements, or 
     returns a subarray specified by range. Negative indices count 
     backward from the end of the array (-1 is the last element). 
     Returns nil if the index (or starting index) are out of range.

        a = [ "a", "b", "c", "d", "e" ]
        a[2] +  a[0] + a[1]    #=> "cab"
        a[6]                   #=> nil
        a[1, 2]                #=> [ "b", "c" ]
        a[1..3]                #=> [ "b", "c", "d" ]
        a[4..7]                #=> [ "e" ]
        a[6..10]               #=> nil
        a[-3, 3]               #=> [ "c", "d", "e" ]
        # special cases
        a[5]                   #=> nil
        a[6, 1]                #=> nil
        a[5, 1]                #=> []
        a[5..10]               #=> []

Aligning a button to the center

Add width:100px, margin:50%. Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.

<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>

Can we instantiate an abstract class directly?

According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.

    public class MyCustomClass extends YourAbstractClass {

/// attributes, methods ,...
}
  1. work with interfaces.

C++ preprocessor __VA_ARGS__ number of arguments

herein a simple way to count 0 or more arguments of VA_ARGS, my exemple assumes a maximum of 5 variables, but you can add more if you want.

#define VA_ARGS_NUM_PRIV(P1, P2, P3, P4, P5, P6, Pn, ...) Pn
#define VA_ARGS_NUM(...) VA_ARGS_NUM_PRIV(-1, ##__VA_ARGS__, 5, 4, 3, 2, 1, 0)


VA_ARGS_NUM()      ==> 0
VA_ARGS_NUM(19)    ==> 1
VA_ARGS_NUM(9, 10) ==> 2
         ...

Facebook Post Link Image

If you used any plugin for seo then Check 1st your seo plugin settings.Then find out Noindex setting if Enable Media for Noindex then disable it.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

While it's true that @RequestBody must map to a single object, that object can be a Map, so this gets you a good way to what you are attempting to achieve (no need to write a one off backing object):

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
   //json.get("str1") == "test one"
}

You can also bind to Jackson's ObjectNode if you want a full JSON tree:

public boolean getTest(@RequestBody ObjectNode json) {
   //json.get("str1").asText() == "test one"

Single Result from Database by using mySQLi

Use mysqli_fetch_row(). Try this,

$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row   = mysqli_fetch_row($result);

$ssfullname = $row['ssfullname'];
$ssemail    = $row['ssemail'];

Copy tables from one database to another in SQL Server

  1. Script the create table in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)

  2. INSERT bar.[schema].table SELECT * FROM foo.[schema].table

What is in your .vimrc?

I didn't realize how many of my 3200 .vimrc lines were just for my quirky needs and would be pretty uninspiring to list here. But maybe that's why Vim is so useful...

iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ
iab MoN January February March April May June July August September October November December
iab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
iab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890 
iab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0

" Highlight every other line
map ,<Tab> :set hls<CR>/\\n.*\\n/<CR>

" This is for working across multiple xterms and/or gvims
" Transfer/read and write one block of text between vim sessions (capture whole line):
" Write
nmap ;w :. w! ~/.vimxfer<CR>
" Read
nmap ;r :r ~/.vimxfer<CR>
" Append 
nmap ;a :. w! >>~/.vimxfer<CR>

Javascript setInterval not working

That's because you should pass a function, not a string:

function funcName() {
    alert("test");
}

setInterval(funcName, 10000);

Your code has two problems:

  • var func = funcName(); calls the function immediately and assigns the return value.
  • Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.

How to add line break for UILabel?

You have to set the numberOfLines property on the UILabel. The default is 1, if you set it to 0 it will remove all limits.

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)") 
or die(mysqli_error($link));

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You won't be able to draw images directly from another server into a canvas and then use getImageData. It's a security issue and the canvas will be considered "tainted".

Would it work for you to save a copy of the image to your server using PHP and then just load the new image? For example, you could send the URL to the PHP script and save it to your server, then return the new filename to your javascript like this:

<?php //The name of this file in this example is imgdata.php

  $url=$_GET['url'];

  // prevent hackers from uploading PHP scripts and pwning your system
  if(!@is_array(getimagesize($url))){
    echo "path/to/placeholderImage.png";
    exit("wrong file type.");
  }

  $img = file_get_contents($url);

  $fn = substr(strrchr($url, "/"), 1);
  file_put_contents($fn,$img);
  echo $fn;

?>

You'd use the PHP script with some ajax javascript like this:

xi=new XMLHttpRequest();
xi.open("GET","imgdata.php?url="+yourImageURL,true);
xi.send();

xi.onreadystatechange=function() {
  if(xi.readyState==4 && xi.status==200) {
    img=new Image;
    img.onload=function(){ 
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    }
    img.src=xi.responseText;
  }
}

If you use getImageData on the canvas after that, it will work fine.

Alternatively, if you don't want to save the whole image, you could pass x & y coordinates to your PHP script and calculate the pixel's rgba value on that side. I think there are good libraries for doing that kind of image processing in PHP.

If you want to use this approach, let me know if you need help implementing it.

edit-1: peeps pointed out that the php script is exposed and allows the internet to potentially use it maliciously. there are a million ways to handle this, one of the simplest being some sort of URL obfuscation... i reckon secure php practices deserves a separate google ;P

edit-2: by popular demand, I've added a check to ensure it is an image and not a php script (from: PHP check if file is an image).

In a Git repository, how to properly rename a directory?

lots of correct answers, but as I landed here to copy & paste a folder rename with history, I found that this

git mv <old name> <new name>

will move the old folder (itself) to nest within the new folder

while

git mv <old name>/ <new name>

(note the '/') will move the nested content from the old folder to the new folder

both commands didn't copy along the history of nested files. I eventually renamed each nested folder individually ?

git mv <old name>/<nest-folder> <new name>/<nest-folder>

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

Bash function to find newest file matching pattern

This is a possible implementation of the required Bash function:

# Print the newest file, if any, matching the given pattern
# Example usage:
#   newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
    # Use ${1-} instead of $1 in case 'nounset' is set
    local -r glob_pattern=${1-}

    if (( $# != 1 )) ; then
        echo 'usage: newest_matching_file GLOB_PATTERN' >&2
        return 1
    fi

    # To avoid printing garbage if no files match the pattern, set
    # 'nullglob' if necessary
    local -i need_to_unset_nullglob=0
    if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
        shopt -s nullglob
        need_to_unset_nullglob=1
    fi

    newest_file=
    for file in $glob_pattern ; do
        [[ -z $newest_file || $file -nt $newest_file ]] \
            && newest_file=$file
    done

    # To avoid unexpected behaviour elsewhere, unset nullglob if it was
    # set by this function
    (( need_to_unset_nullglob )) && shopt -u nullglob

    # Use printf instead of echo in case the file name begins with '-'
    [[ -n $newest_file ]] && printf '%s\n' "$newest_file"

    return 0
}

It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How to write specific CSS for mozilla, chrome and IE

For clean code, you might make use of the javascript file here: http://rafael.adm.br/css_browser_selector/ By including the line:

<script src="css_browser_selector.js" type="text/javascript"></script>

You can write subsequent css with the following simple pattern:

.ie7 [thing] {
  background-color: orange
}
.chrome [thing] {
  background-color: gray
}

postgresql COUNT(DISTINCT ...) very slow

-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';

\echo original
EXPLAIN ANALYZE
SELECT
        COUNT (distinct val) as aantal
FROM one
        ;

\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
        distinct val
       -- , COUNT(*)
FROM one
GROUP BY val;

\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
    SELECT distinct val
    FROM one
    GROUP BY val
    )
SELECT COUNT (*) as aantal
FROM agg
        ;

Results:

original                                                      QUERY PLAN                                                      
----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
   ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
 Total runtime: 1766.642 ms
(3 rows)

group by+count(*)
                                                         QUERY PLAN                                                         
----------------------------------------------------------------------------------------------------------------------------
 HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
   ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
         ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
 Total runtime: 412.686 ms
(4 rows)

with CTE
                                                             QUERY PLAN                                                             
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
   CTE agg
     ->  HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
           ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
                 ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
       ->  CTE Scan on agg  (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
     Total runtime: 408.300 ms
    (7 rows)

The same plan as for the CTE could probably also be produced by other methods (window functions)

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

f = open('words.txt')
for word in f.read().split():
    print(word)

Check if a property exists in a class

There are 2 possibilities.

You really don't have Label property.

You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance

If your property is not public, you will need to use BindingFlags.NonPublic or some other combination of flags which fits your use case. Read the referenced API docs to find the details.

EDIT:

ooops, just noticed you call GetProperty on typeof(MyClass). typeof(MyClass) is Type which for sure has no Label property.

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

What Process is using all of my disk IO

Have you considered lsof (list open files)?

How to store and retrieve a dictionary with redis

The redis SET command stores a string, not arbitrary data. You could try using the redis HSET command to store the dict as a redis hash with something like

for k,v in my_dict.iteritems():
    r.hset('my_dict', k, v)

but the redis datatypes and python datatypes don't quite line up. Python dicts can be arbitrarily nested, but a redis hash is going to require that your value is a string. Another approach you can take is to convert your python data to string and store that in redis, something like

r.set('this_dict', str(my_dict))

and then when you get the string out you will need to parse it to recreate the python object.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0.

Is there a portable way to get the current username in Python?

psutil provides a portable way that doesn't use environment variables like the getpass solution. It is less prone to security issues, and should probably be the accepted answer as of today.

import psutil

def get_username():
    return psutil.Process().username()

Under the hood, this combines the getpwuid based method for unix and the GetTokenInformation method for Windows.

array of string with unknown size

If you will later know the length of the array you can create the initial array like this:

String[] array;

And later when you know the length you can finish initializing it like this

array = new String[42];

LINQ to read XML

Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:

//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ1
{
    static void Main( )
    {
        //Load xml
        XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path

        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
           select new 
           { 
               Header = lv1.Attribute("name").Value,
               Children = lv1.Descendants("level2")
            };

        StringBuilder result = new StringBuilder(); //had to add this to make the result work
        //Loop through results
        foreach (var lv1 in lv1s)
        {
            result.AppendLine("  " + lv1.Header);
            foreach(var lv2 in lv1.Children)
            result.AppendLine("    " + lv2.Attribute("name").Value);
        }
        Console.WriteLine(result.ToString()); //added this so you could see the output on the console
    }
}

And next:

//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ
{
static void Main( )
    {
        XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
        Console.WriteLine(GetOutline(0, rootElement));  
    }

static private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
        return result.ToString();
    }
}

These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.

EDIT: added @eglasius' example as well since it became useful to me:

//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ2
{
    static void Main( )
    {
        StringBuilder result = new StringBuilder(); //needed for result below
        XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
        var lv1s = xdoc.Root.Descendants("level1"); 
        var lvs = lv1s.SelectMany(l=>
             new string[]{ l.Attribute("name").Value }
             .Union(
                 l.Descendants("level2")
                 .Select(l2=>"   " + l2.Attribute("name").Value)
              )
            );
        foreach (var lv in lvs)
        {
           result.AppendLine(lv);
        }
        Console.WriteLine(result);//added this so you could see the result
    }
}

Is background-color:none valid CSS?

The answer is no.

Incorrect

.class {
    background-color: none; /* do not do this */
}

Correct

.class {
    background-color: transparent;
}

background-color: transparent accomplishes the same thing what you wanted to do with background-color: none.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Make an existing Git branch track a remote branch?

Make sure you run :

git config push.default tracking

to be able to push trouble free

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

Android eclipse DDMS - Can't access data/data/ on phone to pull files

No one seems to understand that a retail Nexus One even after being rooted still will not let you browse the file system using DDMS File Explorer. We are talking about real phones here and not the emulator. If you happen to have a Nexus One Developer Phone you can browse the file system using DDMS Filer Explorer, but a retail Nexus One that has been rooted you can't. Got it?

So I hope that answers the question of not being able to use the DDMS File Explorer to browse the file system of a rooted retail Nexus One. After rooting a retail Nexus One there is still something that remains to be done to use DDMS to use the File Explorer to browse the phones File System. I don't know what it is. Maybe someone else knowns.

How can I toggle word wrap in Visual Studio?

In Visual Studio 2008 it is Ctrl + E + W.

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

spark submit add multiple jars in classpath

You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .

spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

ImportError: No module named 'encodings'

I was facing this issue "ModuleNotFoundError: No module named 'encodings" after updating to macOS Catalina.

I was having multiple versions of Python installed in my system.

Removing all the python versions(2.7 and 3.7.4) from macOS system and reinstalling the latest python 3.8 worked for me.

To remove a python from macOS, I've followed the instructions from here How to uninstall Python 2.7 on a Mac OS X 10.6.4?

The above link is for python 2.7 and but you can use the same for 3.7 also.

Find closing HTML tag in Sublime Text

I think, you may want to try another approach with folding enabled.

In both ST2 and ST3, if you enable folding in User settings:

{
    ...(previous item)
    "fold_buttons": true,
    ...(next item, thus the comma)
}

You can see the triangle folding button at the left side of the line where the start tag is. Click it to expand/fold. If you want to copy, fold and copy, you get all block.

enter image description here

How much data can a List can hold at the maximum?

How much data can be added in java.util.List in Java at the maximum?

This is very similar to Theoretical limit for number of keys (objects) that can be stored in a HashMap?

The documentation of java.util.List does not explicitly documented any limit on the maximum number of elements. The documentation of List.toArray however, states that ...

Return an array containing all of the elements in this list in proper sequence (from first to last element); would have trouble implementing certain methods faithfully, such as

... so strictly speaking it would not be possible to faithfully implement this method if the list had more than 231-1 = 2147483647 elements since that is the largest possible array.

Some will argue that the documentation of size()...

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

...indicates that there is no upper limit, but this view leads to numerous inconsistencies. See this bug report.

Is there any default size an array list?

If you're referring to ArrayList then I'd say that the default size is 0. The default capacity however (the number of elements you can insert, without forcing the list to reallocate memory) is 10. See the documentation of the default constructor.

The size limit of ArrayList is Integer.MAX_VALUE since it's backed by an ordinary array.

Check if a Bash array contains a value

I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.

arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
    echo "found!"
else
    echo "not found!"
fi

You take out your pattern from each element only if it starts ${arr[@]/#pattern/} or ends ${arr[@]/%pattern/} with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/} only works in zsh.

If the modified array is equal to the original, then it doesn't contain the element.

Edit:

This one works in bash:

 function contains () {
        local arr=(${@:2})
        local el=$1
        local marr=(${arr[@]/#$el/})
        [[ "${#arr[@]}" != "${#marr[@]}" ]]
    }

After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.

How can I use an http proxy with node.js http.Client?

One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):

var http = require('http');

http.get ({
    host: '127.0.0.1',
    port: 8888,
    path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
    console.log (response);
});

Running command line silently with VbScript and getting output?

You can redirect output to a file and then read the file:

return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)

Set fso  = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

lock_guard and unique_lock are pretty much the same thing; lock_guard is a restricted version with a limited interface.

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

So you always use lock_guard, unless you need the capabilities of unique_lock. A condition_variable needs a unique_lock.

What does the construct x = x || y mean?

To add some explanation to all said before me, I should give you some examples to understand logical concepts.

var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true

It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

And operator have the opposite structure like below.

var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh

Change background color of iframe issue

JavaScript is what you need. If you are loading iframe when loading the page, insert the test for iframe using the onload event. If iframe is inserted in realtime, then create a callback function on insertion and hook in whatever action you need to take :)

How to run VBScript from command line without Cscript/Wscript

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

Check the answer -> Here

And here is an example:

Converter.bat

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

Purpose of installing Twitter Bootstrap through npm?

Answer 1:

  • Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)

  • "npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.

Answer 2:

If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

Fastest way to implode an associative array with keys

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

What is the difference between jQuery: text() and html() ?

((please update if necessary, this answer is a Wiki))

Sub-question: when only text, what is faster, .text() or .html()?

Answer: .html() is faster! See here a "behaviour test-kit" for all the question.

So, in conclusion, if you have "only a text", use html() method.

Note: Doesn't make sense? Remember that the .html() function is only a wrapper to .innerHTML, but in the .text() function jQuery adds an "entity filter", and this filter naturally consumes time.


Ok, if you really want performance... Use pure Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

  • jQuery's .html() is ~2x faster than .text().
  • pure JS' .innerHTML is ~3x faster than .html().
  • pure JS' .nodeValue is ~50x faster than .html(), ~100x than .text(), and ~20x than .innerHTML.

PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

See this complete benchmark:

// Using jQuery:
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").html('BENCHMARK WORK');
var ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").text('BENCHMARK WORK');
alert("JQuery (3000x): \nhtml="+ht+"\ntext="+simplecron.duration());

// Using pure JavaScript only:
simplecron.restart(); for (var i=1; i<3000; i++)
    document.getElementById('work').innerHTML = 'BENCHMARK WORK';
ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    document.getElementById('work').nodeValue = 'BENCHMARK WORK';
alert("Pure JS (3000x):\ninnerHTML="+ht+"\nnodeValue="+simplecron.duration());

How to get a key in a JavaScript object by its value?

Or, easier yet - create a new object with the keys and values in the order you want then do look up against that object. We have had conflicts using the prototype codes above. You don't have to use the String function around the key, that is optional.

 newLookUpObj = {};
 $.each(oldLookUpObj,function(key,value){
        newLookUpObj[value] = String(key);
    });

Validate Dynamically Added Input fields

The one mahesh posted is not working because the attribute name is missing:

So instead of

<input id="list" class="required"  />

You can use:

<input id="list" name="list" class="required"  />

Modified version

How do you change the launcher logo of an app in Android Studio?

  1. Go to AndroidManifest.xml

  2. In the tag, look for android:icon tag.

  3. Copy and paste your icon in drawable folder(available in res folder of your project).

  4. Set the value of android:icon tag as

    android:icon="@drawable/youriconname"

Voila! you are done. Save the changes and test.

Multiple WHERE clause in Linq

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" &&
                  r.Field<string>("UserName") != "YYYY"
            select r;

DataTable newDT = query.CopyToDataTable();

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where !ignoredUserNames.Contains(r.Field<string>("UserName"))
            select r;

DataTable newDT = query.CopyToDataTable();

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

How to find if directory exists in Python

Just to provide the os.stat version (python 2):

import os, stat, errno
def CheckIsDir(directory):
  try:
    return stat.S_ISDIR(os.stat(directory).st_mode)
  except OSError, e:
    if e.errno == errno.ENOENT:
      return False
    raise

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

List<String> listA = new ArrayList<String>();

    listA.add("A");
    listA.add("B");

List<String> listB = new ArrayList<String>();

    listB.add("B");
    listB.add("C");

Set<String> newSet = new HashSet<String>(listA);

    newSet.addAll(listB);
List<String> newList = new ArrayList<String>(newSet);

System.out.println("New List :"+newList);

is giving you New List :[A, B, C]

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

How to use requirements.txt to install all dependencies in a python project

If you are using Linux OS:

  1. Remove matplotlib==1.3.1 from requirements.txt
  2. Try to install with sudo apt-get install python-matplotlib
  3. Run pip install -r requirements.txt (Python 2), or pip3 install -r requirements.txt (Python 3)
  4. pip freeze > requirements.txt

If you are using Windows OS:

  1. python -m pip install -U pip setuptools
  2. python -m pip install matplotlib

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

I can guarantee you that bash alone won't be any faster than sed for this task. Starting up external processes in bash is a generally bad idea but only if you do it a lot.

So, if you're starting a sed process for each line of your input, I'd be concerned. But you're not. You only need to start one sed which will do all the work for you.

You may however find that the following sed will be a bit faster than your version:

(whatever) | sed 's/...$//'

All this does is remove the last three characters on each line, rather than substituting the whole line with a shorter version of itself. Now maybe more modern RE engines can optimise your command but why take the risk.

To be honest, about the only way I can think of that would be faster would be to hand-craft your own C-based filter program. And the only reason that may be faster than sed is because you can take advantage of the extra knowledge you have on your processing needs (sed has to allow for generalised procession so may be slower because of that).

Don't forget the optimisation mantra: "Measure, don't guess!"


If you really want to do this one line at a time in bash (and I still maintain that it's a bad idea), you can use:

pax> line=123456789abc
pax> line2=${line%%???}
pax> echo ${line2}
123456789
pax> _

You may also want to investigate whether you actually need a speed improvement. If you process the lines as one big chunk, you'll see that sed is plenty fast. Type in the following:

#!/usr/bin/bash

echo This is a pretty chunky line with three bad characters at the end.XXX >qq1
for i in 4 16 64 256 1024 4096 16384 65536 ; do
    cat qq1 qq1 >qq2
    cat qq2 qq2 >qq1
done

head -20000l qq1 >qq2
wc -l qq2

date
time sed 's/...$//' qq2 >qq1
date
head -3l qq1

and run it. Here's the output on my (not very fast at all) R40 laptop:

pax> ./chk.sh
20000 qq2
Sat Jul 24 13:09:15 WAST 2010

real    0m0.851s
user    0m0.781s
sys     0m0.050s
Sat Jul 24 13:09:16 WAST 2010
This is a pretty chunky line with three bad characters at the end.
This is a pretty chunky line with three bad characters at the end.
This is a pretty chunky line with three bad characters at the end.

That's 20,000 lines in under a second, pretty good for something that's only done every hour.

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

Trying Gradle build - "Task 'build' not found in root project"

run

gradle clean 

then try

gradle build 

it worked for me

Check for false

Like this:

if(borrar())
{
   // Do something
}

If borrar() returns true then do something (if it is not false).

What is the default initialization of an array in Java?

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

So Java is initializing the array by running its constructor method while creating the object

How to link to a named anchor in Multimarkdown?

Taken from the Multimarkdown Users Guide (thanks to @MultiMarkdown on Twitter for pointing it out)

[Some Text][]will link to a header named “Some Text”
e.g.

### Some Text ###

An optional label of your choosing to help disambiguate cases where multiple headers have the same title:

### Overview [MultiMarkdownOverview] ##

This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.

If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.

In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

Simple regular expression for a decimal with a precision of 2

To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

.NET Format a string with fixed spaces

it seems like you want something like this, that will place you string at a fixed point in a string of constant length:

Dim totallength As Integer = 100
Dim leftbuffer as Integer = 5
Dim mystring As String = "string goes here"
Dim Formatted_String as String = mystring.PadLeft(leftbuffer + mystring.Length, "-") + String.Empty.PadRight(totallength - (mystring.Length + leftbuffer), "-")

note that this will have problems if mystring.length + leftbuffer exceeds totallength

newline in <td title="">

If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples

Not able to access adb in OS X through Terminal, "command not found"

Quick Answer

Pasting this command in terminal solves the issue in most cases:

** For Current Terminal Session:

  • (in macOS) export PATH="~/Library/Android/sdk/platform-tools":$PATH
  • (in Windows) i will update asap

** Permanently:

  • (in macOS) edit the ~/.bash_profile using vi ~/.bash_profile and add this line to it: export PATH="~/Library/Android/sdk/platform-tools":$PATH

However, if not, continue reading.


Detailed Answer

Android Debug Bridge, or adb for short, is usually located in Platform Tools and comes with Android SDK, You simply need to add its location to system path. So system knows about it, and can use it if necessary.

Find ADB's Location

Path to this folder varies by installation scenario, but common ones are:


  • If you have installed Android Studio, path to ADB would be: (Most Common)
    • (in macOS) ~/Library/Android/sdk/platform-tools
    • (in Windows) i will update asap

  • If you have installed Android Studio somewhere else, determine its location by going to:

    • (in macOS) Android Studio > Preferences > Appearance And Behavior > System Settings > Android SDK and pay attention to the box that says: Android SDK Location
    • (in Windows) i will update asap

  • However Android SDK could be Installed without Android studio, in this case your path might be different, and depends on your installation.

Add it to System Path

When you have determined ADB's location, add it to system, follow this syntax and type it in terminal:

  • (in macOS)

    export PATH="your/path/to/adb/here":$PATH

    for example: export PATH="~/Library/Android/sdk/platform-tools":$PATH

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Had an issue with this as well, iPhone + Safari where needed to add:

position: fixed;

As mentioned elsewhere, this created a scroll-to-top issue. Fix that worked for me was to capture the position to top upon modal open, and then animate to that position on modal close

upon modal open:

scrollTo = $('body').scrollTop();
$('body').css("position", "fixed");

upon modal close

$('body').css("position", "static");
$('body').animate({scrollTop: scrollTo}, 0);

What HTTP traffic monitor would you recommend for Windows?

I now use CharlesProxy for development, but previously I have used Fiddler

Java Equivalent of C# async/await?

There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.

Java libraries implementing Fibers

You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.

Submit form using AJAX and jQuery

This is what ended up working.

$("select").change(function(){
    $.get("/page.html?" + $(this).parent("form").find(":input").serialize()); 
});

Best way to check function arguments?

Edit: as of 2019 there is more support for using type annotations and static checking in Python; check out the typing module and mypy. The 2013 answer follows:


Type checking is generally not Pythonic. In Python, it is more usual to use duck typing. Example:

In you code, assume that the argument (in your example a) walks like an int and quacks like an int. For instance:

def my_function(a):
    return a + 7

This means that not only does your function work with integers, it also works with floats and any user defined class with the __add__ method defined, so less (sometimes nothing) has to be done if you, or someone else, want to extend your function to work with something else. However, in some cases you might need an int, so then you could do something like this:

def my_function(a):
    b = int(a) + 7
    c = (5, 6, 3, 123541)[b]
    return c

and the function still works for any a that defines the __int__ method.

In answer to your other questions, I think it is best (as other answers have said to either do this:

def my_function(a, b, c):
    assert 0 < b < 10
    assert c        # A non-empty string has the Boolean value True

or

def my_function(a, b, c):
    if 0 < b < 10:
        # Do stuff with b
    else:
        raise ValueError
    if c:
        # Do stuff with c
    else:
        raise ValueError

Some type checking decorators I made:

import inspect

def checkargs(function):
    def _f(*arguments):
        for index, argument in enumerate(inspect.getfullargspec(function)[0]):
            if not isinstance(arguments[index], function.__annotations__[argument]):
                raise TypeError("{} is not of type {}".format(arguments[index], function.__annotations__[argument]))
        return function(*arguments)
    _f.__doc__ = function.__doc__
    return _f

def coerceargs(function):
    def _f(*arguments):
        new_arguments = []
        for index, argument in enumerate(inspect.getfullargspec(function)[0]):
            new_arguments.append(function.__annotations__[argument](arguments[index]))
        return function(*new_arguments)
    _f.__doc__ = function.__doc__
    return _f

if __name__ == "__main__":
    @checkargs
    def f(x: int, y: int):
        """
        A doc string!
        """
        return x, y

    @coerceargs
    def g(a: int, b: int):
        """
        Another doc string!
        """
        return a + b

    print(f(1, 2))
    try:
        print(f(3, 4.0))
    except TypeError as e:
        print(e)

    print(g(1, 2))
    print(g(3, 4.0))

How can I limit the visible options in an HTML <select> dropdown?

Raj_89 solution is the closest to being valid option altough as mentioned by Kevin Swarts in comment it is going to break IE, which for large number of corporate client is an issue (and telling your client that you won't code for IE "because reasons" is unlikely to make your boss happy ;) ).

So I played around with it and here is the problem: the 'onmousedown' event is throwing a fit in IE, so what we want to do, is to prevent default when user clicks the dropdown for the first time. It is important this is only time we do this: if we prevent defult on the next click, when user makes his pick, the onchange event won't fire.

This way we get nice dropdown, no flicker, no breaking down IE - just works... well at least in IE10 and up, and latest relases of all the other major browsers.

<p>Which is the most annoing browser of them all:</p>
<select id="sel" size = "1">
    <option></option>
    <option>IE 9</option>
    <option>IE 10</option>
    <option>Edge</option>
    <option>Firefox</option>
    <option>Chrome</option>
    <option>Opera</option>
</select>

Here is the fiddle: https://jsfiddle.net/88cxzhom/27/

Few more things to notice: 1) The absolute positioning and setting z-index is helpful to avoid moving other elements when the options are displayed. 2) Use 'currentTarget' property - this will be the select element across all browsers. While 'target' will be select in IE, the rest will actually allow you to work with option.

Hope this helps someone.

Disable asp.net button after click to prevent double clicking

This works with a regular html button.

    <input id="Button1"
    onclick="this.disabled='true';" type="button"
    value="Submit" name="Button1"
    runat="server" onserverclick="Button1_Click">

The button is disabled until the postback is finished, preventing double clicking.

Write to UTF-8 file in Python

I use the file *nix command to convert a unknown charset file in a utf-8 file

# -*- encoding: utf-8 -*-

# converting a unknown formatting file in utf-8

import codecs
import commands

file_location = "jumper.sub"
file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)

file_stream = codecs.open(file_location, 'r', file_encoding)
file_output = codecs.open(file_location+"b", 'w', 'utf-8')

for l in file_stream:
    file_output.write(l)

file_stream.close()
file_output.close()

Difference between Static methods and Instance methods

Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.

Setting the value of checkbox to true or false with jQuery

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

--

$('#vehicleChkBox').change(function(){
    if(this.checked)
        $('#vehicleChkBox').val('TRUE');
   else
        $('#vehicleChkBox').val('False');
});

What is the best way to detect a mobile device?

Just copy the following function and it returns a boolean value. its regex is looks like the marked answer but it is has some difference:

const isMobile = () =>
  /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series([46])0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
    navigator.userAgent
  ) ||
  /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br([ev])w|bumb|bw-([nu])|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do([cp])o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly([-_])|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-([mpt])|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c([- _agpst])|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac([ \-/])|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja([tv])a|jbro|jemu|jigs|kddi|keji|kgt([ /])|klon|kpt |kwc-|kyo([ck])|le(no|xi)|lg( g|\/([klu])|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t([- ov])|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30([02])|n50([025])|n7(0([01])|10)|ne(([cm])-|on|tf|wf|wg|wt)|nok([6i])|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan([adt])|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c([-01])|47|mc|nd|ri)|sgh-|shar|sie([-m])|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel([im])|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c([- ])|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
    navigator.userAgent.substr(0, 4)
  );

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Paying tribute to IgorBeaz, you need to stop running the current container. For that you are going to know current CONTAINER ID:

$ docker container ls

You get something like:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
12a32e8928ef        friendlyhello       "python app.py"     51 seconds ago      Up 50 seconds       0.0.0.0:4000->80/tcp   romantic_tesla   

Then you stop the container by:

$ docker stop 12a32e8928ef

Finally you try to do what you wanted to do, for example:

$ docker run -p 4000:80 friendlyhello

How to convert Blob to File in JavaScript

This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

How to test android apps in a real device with Android Studio?

  • First we have to enable the USB debugging mode. for that go to Settings -> Developer Options ->USB debugging in your phone checked it and allow it.
  • After it open android studio, click on SDK manager , check mark the Google USB Driver and hit install package.
  • After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  • Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  • Select Device Manager –> Portable Devices –> Your Device Name
  • Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  • Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  • Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

How to validate an email address using a regular expression?

I use this;

^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

How to get max value of a column using Entity Framework?

As many said - this version

int maxAge = context.Persons.Max(p => p.Age);

throws an exception when table is empty.

Use

int maxAge = context.Persons.Max(x => (int?)x.Age) ?? 0;

or

int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()

Find the nth occurrence of substring in a string

Here is another approach using re.finditer.
The difference is that this only looks into the haystack as far as necessary

from re import finditer
from itertools import dropwhile
needle='an'
haystack='bananabanana'
n=2
next(dropwhile(lambda x: x[0]<n, enumerate(re.finditer(needle,haystack))))[1].start() 

Node / Express: EADDRINUSE, Address already in use - Kill server

server.close() takes a while to close the connection, thus we should make this an asynchronous call as such:

await server.close();

IMPORTANT: when using await, we must use the async keyword in our encapsulating function as such:

async () => {
  await server.close();
}

How to correctly iterate through getElementsByClassName

You could always use array methods:

var slides = getElementsByClassName("slide");
Array.prototype.forEach.call(slides, function(slide, index) {
    Distribute(slides.item(index));
});

ORA-12154 could not resolve the connect identifier specified

If you are using LDAP, make sure that the environment variable "TNS_ADMIN" exists and points to the folder containing the file "ldap.ora".

If this variable does not exist, create it and restart Visual Studio.

SQL Update to the SUM of its joined values

An alternate to the above solutions is using Aliases for Tables:

UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;

How can I get the MAC and the IP address of a connected client in PHP?

All you need to do is to put arp into diferrent group.

Default:

-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*

With command:

sudo chown root:www-data /usr/sbin/arp

you will get:

-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*

And because apache is a daemon running under the user www-data, it's now able to execute this command.

So if you now use a PHP script, e.g.:

<?php
$mac = system('arp -an');
echo $mac;
?>

you will get the output of linux arp -an command.

How to detect a remote side socket close?

You can also check for socket output stream error while writing to client socket.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}

Drop data frame columns by name

Find the index of the columns you want to drop using which. Give these indexes a negative sign (*-1). Then subset on those values, which will remove them from the dataframe. This is an example.

DF <- data.frame(one=c('a','b'), two=c('c', 'd'), three=c('e', 'f'), four=c('g', 'h'))
DF
#  one two three four
#1   a   d     f    i
#2   b   e     g    j

DF[which(names(DF) %in% c('two','three')) *-1]
#  one four
#1   a    g
#2   b    h

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Just in case someone checked this thread and had the same issue as mine...

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I'm using NHibernate, I receive same error, during creating an object...

I was passing the key manually, and also specified a GUID generator in mapping, so hibernate generate same exact error for me, so once I removed the GUID, and left the field empty, everything went just fine.

this answer may not help you, but will help someone like me, who just your thread becasue of same error

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

I run into exactly the same problem, but unfortunately none of the suggested solutions really worked for me. The problem did not happen during deployment, and I was neither doing any hot deployments.

In my case the problem occurred every time at the same point during the execution of my web-application, while connecting (via hibernate) to the database.

This link (also mentioned earlier) did provide enough insides to resolve the problem. Moving the jdbc-(mysql)-driver out of the WEB-INF and into the jre/lib/ext/ folder seems to have solved the problem. This is not the ideal solution, since upgrading to a newer JRE would require you to reinstall the driver. Another candidate that could cause similar problems is log4j, so you might want to move that one as well

Using Mockito with multiple calls to the same method with the same arguments

You can do that using the thenAnswer method (when chaining with when):

when(someMock.someMethod()).thenAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
});

Or using the equivalent, static doAnswer method:

doAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
}).when(someMock).someMethod();

How to access session variables from any class in ASP.NET?

The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.

How to use RecyclerView inside NestedScrollView?

One solution to keep the recycling feature of the recyclerview and avoiding the recyclerview to load all your data is setting a fix height in the recyclerview itself. By doing this the recyclerview is limited only to load as much as its height can show the user thus recycling its element if ever you scroll to the bottom/top.

Best practice for using assert?

An Assert is to check -
1. the valid condition,
2. the valid statement,
3. true logic;
of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.

In example 1, since variable 'str' is not null. So no any assert or exception get raised.

Example 1:

#!/usr/bin/python

str = 'hello Python!'
strNull = 'string is Null'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)


------------------------------------------------------

Output:
hello Python!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py

In example 2, var 'str' is null. So we are saving the user from going ahead of faulty program by assert statement.

Example 2:

#!/usr/bin/python

str = ''
strNull = 'NULL String'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)


------------------------------------------------------

Output:
AssertionError: NULL String

The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag

python -O assertStatement.py
nothing will get print

Anaconda Navigator won't launch (windows 10)

You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:

A) Use the key combination Win-key + R then type cmd and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts (or whatever directory path yours is).

B) Navigate using windows explorer to that Scripts directory then type cmd in the address bar of that window and hit return (that will launch the terminal already set to that directory).

Next type the follow commands waiting in between for each to complete:

activate root
conda update -n root conda
conda update --all

When complete type the following and Navigator hopefully should launch:

anaconda-navigator

Timing a command's execution in PowerShell

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1  
$command = Get-History -Count 1  
$command.EndExecutionTime - $command.StartExecutionTime

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

One option if the number of keys is small is to use chained gets:

value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

But if you have keySet defined, this might be clearer:

value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]
        break

The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

Can I install Python 3.x and 2.x on the same Windows computer?

I would assume so, I have Python 2.4, 2.5 and 2.6 installed side-by-side on the same computer.

Node.js throws "btoa is not defined" error

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

console.log(Buffer.from('Hello World!').toString('base64'));

Reverse (assuming the content you're decoding is a utf8 string):

console.log(Buffer.from(b64Encoded, 'base64').toString());

Note: prior to Node v4, use new Buffer rather than Buffer.from.

c++ exception : throwing std::string

Simplest way to throw an Exception in C++:

#include <iostream>
using namespace std;
void purturb(){
    throw "Cannot purturb at this time.";
}
int main() {
    try{
        purturb();
    }
    catch(const char* msg){
        cout << "We caught a message: " << msg << endl;
    }
    cout << "done";
    return 0;
}

This prints:

We caught a message: Cannot purturb at this time.
done

If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

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

ADB Shell Input Events

Also, if you want to send embedded spaces with the input command, use %s

adb shell input text 'this%sis%san%sexample'   

will yield

this is an example

being input.

% itself does not need escaping - only the special %s pair is treated specially. This leads of course to the obvious question of how to enter the literal string %s, which you would have to do with two separate commands.

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:

--ignore-space-change 
--ignore-all-space 
--ignore-space-at-eol

Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

Iterate over model instance field names and values in template

I've come up with the following method, which works for me because in every case the model will have a ModelForm associated with it.

def GetModelData(form, fields):
    """
    Extract data from the bound form model instance and return a
    dictionary that is easily usable in templates with the actual
    field verbose name as the label, e.g.

    model_data{"Address line 1": "32 Memory lane",
               "Address line 2": "Brainville",
               "Phone": "0212378492"}

    This way, the template has an ordered list that can be easily
    presented in tabular form.
    """
    model_data = {}
    for field in fields:
        model_data[form[field].label] = eval("form.data.%s" % form[field].name)
    return model_data

@login_required
def clients_view(request, client_id):
    client = Client.objects.get(id=client_id)
    form = AddClientForm(client)

    fields = ("address1", "address2", "address3", "address4",
              "phone", "fax", "mobile", "email")
    model_data = GetModelData(form, fields)

    template_vars = RequestContext(request,
        {
            "client": client,
            "model_data": model_data
        }
    )
    return render_to_response("clients-view.html", template_vars)

Here is an extract from the template I am using for this particular view:

<table class="client-view">
    <tbody>
    {% for field, value in model_data.items %}
        <tr>
            <td class="field-name">{{ field }}</td><td>{{ value }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

The nice thing about this method is that I can choose on a template-by-template basis the order in which I would like to display the field labels, using the tuple passed in to GetModelData and specifying the field names. This also allows me to exclude certain fields (e.g. a User foreign key) as only the field names passed in via the tuple are built into the final dictionary.

I'm not going to accept this as the answer because I'm sure someone can come up with something more "Djangonic" :-)

Update: I'm choosing this as the final answer because it is the simplest out of those given that does what I need. Thanks to everyone who contributed answers.

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

Global constants file in Swift

What I did in my Swift project
1: Create new Swift File
2: Create a struct and static constant in it.
3: For Using just use YourStructName.baseURL

Note: After Creating initialisation takes little time so it will show in other viewcontrollers after 2-5 seconds.

import Foundation

    struct YourStructName {
    static let MerchantID = "XXX"
    static let MerchantUsername = "XXXXX"
    static let ImageBaseURL = "XXXXXXX"
    static let baseURL = "XXXXXXX"
    }