Programs & Examples On #Parentid

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

How to add/update child entities when updating a parent entity in EF

@Charles McIntosh really gave me the answer for my situation in that the passed in model was detached. For me what ultimately worked was saving the passed in model first... then continuing to add the children as I already was before:

public async Task<IHttpActionResult> GetUPSFreight(PartsExpressOrder order)
{
    db.Entry(order).State = EntityState.Modified;
    db.SaveChanges();
  ...
}

How to set an "Accept:" header on Spring RestTemplate request?

Here is a simple answer. Hope it helps someone.

import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


public String post(SomeRequest someRequest) {
    // create a list the headers 
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("username", "user123"));
    interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
    interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
    // initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();
    // set header interceptors here
    restTemplate.setInterceptors(interceptors);
    // post the request. The response should be JSON string
    String response = restTemplate.postForObject(Url, someRequest, String.class);
    return response;
}

Build tree array from flat array in javascript

This is an old thread but I figured an update never hurts, with ES6 you can do:

_x000D_
_x000D_
const data = [{
    id: 1,
    parent_id: 0
}, {
    id: 2,
    parent_id: 1
}, {
    id: 3,
    parent_id: 1
}, {
    id: 4,
    parent_id: 2
}, {
    id: 5,
    parent_id: 4
}, {
    id: 8,
    parent_id: 7
}, {
    id: 9,
    parent_id: 8
}, {
    id: 10,
    parent_id: 9
}];

const arrayToTree = (items=[], id = null, link = 'parent_id') => items.filter(item => id==null ? !items.some(ele=>ele.id===item[link]) : item[link] === id ).map(item => ({ ...item, children: arrayToTree(items, item.id) }))
const temp1=arrayToTree(data)
console.log(temp1)

const treeToArray = (items=[], key = 'children') => items.reduce((acc, curr) => [...acc, ...treeToArray(curr[key])].map(({ [`${key}`]: child, ...ele }) => ele), items);
const temp2=treeToArray(temp1)

console.log(temp2)
_x000D_
_x000D_
_x000D_

hope it helps someone

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

You need to CAST the ParentId as an nvarchar, so that the output is always the same data type.

SELECT Id   'PatientId',
       ISNULL(CAST(ParentId as nvarchar(100)),'')  'ParentId'
FROM Patients

Nullable DateTime conversion

You might want to do it like this:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 

The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.

Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

What are the options for storing hierarchical data in a relational database?

My favorite answer is as what the first sentence in this thread suggested. Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy.

The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use the extreme RBAR method known as a "Push Stack" to do the conversion and has been considered to be way to expensive to reach the Nirvana of the simplicity of maintenance by the Adjacency List and the awesome performance of Nested Sets. As a result, most people end up having to settle for one or the other especially if there are more than, say, a lousy 100,000 nodes or so. Using the push stack method can take a whole day to do the conversion on what MLM'ers would consider to be a small million node hierarchy.

I thought I'd give Celko a bit of competition by coming up with a method to convert an Adjacency List to Nested sets at speeds that just seem impossible. Here's the performance of the push stack method on my i5 laptop.

Duration for     1,000 Nodes = 00:00:00:870 
Duration for    10,000 Nodes = 00:01:01:783 (70 times slower instead of just 10)
Duration for   100,000 Nodes = 00:49:59:730 (3,446 times slower instead of just 100) 
Duration for 1,000,000 Nodes = 'Didn't even try this'

And here's the duration for the new method (with the push stack method in parenthesis).

Duration for     1,000 Nodes = 00:00:00:053 (compared to 00:00:00:870)
Duration for    10,000 Nodes = 00:00:00:323 (compared to 00:01:01:783)
Duration for   100,000 Nodes = 00:00:03:867 (compared to 00:49:59:730)
Duration for 1,000,000 Nodes = 00:00:54:283 (compared to something like 2 days!!!)

Yes, that's correct. 1 million nodes converted in less than a minute and 100,000 nodes in under 4 seconds.

You can read about the new method and get a copy of the code at the following URL. http://www.sqlservercentral.com/articles/Hierarchy/94040/

I also developed a "pre-aggregated" hierarchy using similar methods. MLM'ers and people making bills of materials will be particularly interested in this article. http://www.sqlservercentral.com/articles/T-SQL/94570/

If you do stop by to take a look at either article, jump into the "Join the discussion" link and let me know what you think.

LAST_INSERT_ID() MySQL

Instead of this LAST_INSERT_ID() try to use this one

mysqli_insert_id(connection)

What does ON [PRIMARY] mean?

It refers to which filegroup the object you are creating resides on. So your Primary filegroup could reside on drive D:\ of your server. you could then create another filegroup called Indexes. This filegroup could reside on drive E:\ of your server.

JPA OneToMany not deleting child

As explained, it is not possible to do what I want with JPA, so I employed the hibernate.cascade annotation, with this, the relevant code in the Parent class now looks like this:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy = "parent")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
            org.hibernate.annotations.CascadeType.DELETE,
            org.hibernate.annotations.CascadeType.MERGE,
            org.hibernate.annotations.CascadeType.PERSIST,
            org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private Set<Child> childs = new HashSet<Child>();

I could not simple use 'ALL' as this would have deleted the parent as well.

Simplest way to do a recursive self-join?

The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()

WITH    q AS 
        (
        SELECT  m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    #t m
        WHERE   ParentID =0
        UNION ALL
        SELECT  m.*,  q.bc + '.' + str(ROW_NUMBER()  OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN
        FROM    #t m
        JOIN    q
        ON      m.parentID = q.DBID
        )
SELECT  *
FROM    q
ORDER BY
        bc

LINQ - Left Join, Group By, and Count

 (from p in context.ParentTable     
  join c in context.ChildTable 
    on p.ParentId equals c.ChildParentId into j1 
  from j2 in j1.DefaultIfEmpty() 
     select new { 
          ParentId = p.ParentId,
         ChildId = j2==null? 0 : 1 
      })
   .GroupBy(o=>o.ParentId) 
   .Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })

How to efficiently build a tree from a flat structure?

one elegant way to do this is to represent items in the list as string holding a dot separated list of parents, and finally a value:

server.port=90
server.hostname=localhost
client.serverport=90
client.database.port=1234
client.database.host=localhost

When assembling a tree, you would end up with something like:

server:
  port: 90
  hostname: localhost
client:
  serverport=1234
  database:
    port: 1234
    host: localhost

I have a configuration library that implements this override configuration (tree) from command line arguments (list). The algorithm to add a single item to the list to a tree is here.

What is the most efficient/elegant way to parse a flat table into a tree?

If elements are in tree order, as shown in your example, you can use something like the following Python example:

delimiter = '.'
stack = []
for item in items:
  while stack and not item.startswith(stack[-1]+delimiter):
    print "</div>"
    stack.pop()
  print "<div>"
  print item
  stack.append(item)

What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack.

If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python:

print "  " * len(stack)

You could also easily use this method to construct a set of nested lists or dictionaries.

Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach:

idx = {}
idx[0] = []
for node in results:
  child_list = []
  idx[node.Id] = child_list
  idx[node.ParentId].append((node, child_list))

This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID.

How to start and stop android service from a adb shell?

I can start service through

am startservice com.xxx/.service.XXXService

but i don't know how to stop it yet.

Changing selection in a select with the Chosen plugin

From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field

$(document).ready(function() {

    $('select').chosen();

    $('button').click(function() {
        $('select').val(2);
        $('select').trigger("chosen:updated");
    });

});

NOTE: versions prior to 1.0 used the following:

$('select').trigger("liszt:updated");

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Closing a file after File.Create

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object in order to close it and release resources that it's using:

var myFile = File.Create(myPath);
myFile.Close();

However, since FileStream implements IDisposable, you can take advantage of the using statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:

using (var myFile = File.Create(myPath))
{
   // interact with myFile here, it will be disposed automatically
}

How do I write the 'cd' command in a makefile?

What do you want it to do once it gets there? Each command is executed in a subshell, so the subshell changes directory, but the end result is that the next command is still in the current directory.

With GNU make, you can do something like:

BIN=/bin
foo:
    $(shell cd $(BIN); ls)

What is __main__.py?

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

MySQL high CPU usage

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

ORACLE IIF Statement

Two other alternatives:

  1. a combination of NULLIF and NVL2. You can only use this if emp_id is NOT NULL, which it is in your case:

    select nvl2(nullif(emp_id,1),'False','True') from employee;
    
  2. simple CASE expression (Mt. Schneiders used a so-called searched CASE expression)

    select case emp_id when 1 then 'True' else 'False' end from employee;
    

The executable gets signed with invalid entitlements in Xcode

In my case: I need enable Inter-App Audio in

Capabilities -> Inter-App Audio

I think because I use Parse.com Notification, it need link to AudioToolbox.framework

How to append a newline to StringBuilder

you can use line.seperator for appending new line in

JavaScript/jQuery to download file via POST with JSON data

I think the best approach is to use a combination, Your second approach seems to be an elegant solution where browsers are involved.

So depending on the how the call is made. (whether its a browser or a web service call) you can use a combination of the two, with sending a URL to the browser and sending raw data to any other web service client.

How to remove first and last character of a string?

It's easy, You need to find index of [ and ] then substring. (Here [ is always at start and ] is at end) ,

String loginToken = "[wdsd34svdf]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );

WMI "installed" query different from add/remove programs list?

I believe your syntax is using the Win32_Product Class in WMI. One cause is that this class only displays products installed using Windows Installer (See Here). The Uninstall Registry Key is your best bet.

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall

UPDATE FOR COMMENTS:

The Uninstall Registry Key is the standard place to list what is installed and what isn't installed. It is the location that the Add/Remove Programs list will use to populate the list of applications. I'm sure that there are applications that don't list themselves in this location. In that case you'd have to resort to another cruder method such as searching the Program Files directory or looking in the Start Menu Programs List. Both of those ways are definitely not ideal.

In my opinion, looking at the registry key is the best method.

SQL Insert Query Using C#

The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.

If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).

how to run or install a *.jar file in windows?

If double-clicking on it brings up WinRAR, you need to change the program you are running it with. You can right-click on it and click "Open with". Java should be listed in there.

However, you must first upgrade your Java version to be compatible with that JAR.

What does "request for member '*******' in something not a structure or union" mean?

It also happens if you're trying to access an instance when you have a pointer, and vice versa:

struct foo
{
  int x, y, z;
};

struct foo a, *b = &a;

b.x = 12;  /* This will generate the error, should be b->x or (*b).x */

As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

typedef struct foo* Foo;

Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;

Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

What is "Linting"?

Lint was the name of a program that would go through your C code and identify problems before you compiled, linked, and ran it. It was a static checker, much like FindBugs today for Java.

Like Google, "lint" became a verb that meant static checking your source code.

How to unpublish an app in Google Play Developer Console

As per new Interface follow these steps

  1. Go to Google Play Developer Console
  2. Select your app you want to un-publish
  3. From the left Navigation Release >> Setup >> Advance Settings
  4. In the App Availability Check on Unpublished Radio button enter image description here

Call javascript from MVC controller action

Yes, it is definitely possible using Javascript Result:

return JavaScript("Callback()");

Javascript should be referenced by your view:

function Callback(){
    // do something where you can call an action method in controller to pass some data via AJAX() request
}

Bootstrap 3: Keep selected tab on page refresh

Basing myself on answers provided by Xavi Martínez and koppor I came up with a solution that uses the url hash or localStorage depending on the availability of the latter:

function rememberTabSelection(tabPaneSelector, useHash) {
    var key = 'selectedTabFor' + tabPaneSelector;
    if(get(key)) 
        $(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');

    $(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
        set(key, this.getAttribute('href'));
    }); 

    function get(key) {
        return useHash ? location.hash: localStorage.getItem(key);
    }

    function set(key, value){
        if(useHash)
            location.hash = value;
        else
            localStorage.setItem(key, value);
    }
}

Usage:

$(document).ready(function () {
    rememberTabSelection('#rowTab', !localStorage);
    // Do Work...
});

It does not keep up with the back button as is the case for Xavi Martínez's solution.

ES6 export all values from object

I just had need to do this for a config file.

var config = {
    x: "CHANGE_ME",
    y: "CHANGE_ME",
    z: "CHANGE_ME"
}

export default config;

You can do it like this

import { default as config } from "./config";

console.log(config.x); // CHANGE_ME

This is using Typescript mind you.

Center text in div?

display: block;
text-align: center;

Produce a random number in a range using C#

Try below code.

Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51

Fatal error: Namespace declaration statement has to be the very first statement in the script in

There is a mistake in its source. Check out its source if you may. It reads like this

<?php
    class BulletProofException extends Exception{}

    namespace BulletProof;
    ....

That is insane. Personally, I'd say the code is well documented, and elegant, but the author missed a simple point; he declared the namespace within the class. Namespace whenever used should be the first statement.

Too bad I am not in Github; could have pulled a request otherwise :(

Dynamic loading of images in WPF

Here is the extension method to load an image from URI:

public static BitmapImage GetBitmapImage(
    this Uri imageAbsolutePath,
    BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = bitmapCacheOption;
    image.UriSource = imageAbsolutePath;
    image.EndInit();

    return image;
}

Sample of use:

Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);

Simple as that!

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I tried all existing fixes and not working for me

I re-install python 2.7 (will also install pip) by downloading .pkg at https://www.python.org/downloads/mac-osx/

works for me after installation downloaded pkg

Change package name for Android in React Native

Go to file android/app/src/main/AndroidManifest.xml -

Update :

attr android:label of Element application as :

Old value - android:label="@string/app_name"

New Value - android:label="(string you want to put)"

and

attr android:label of Element activity as :

Old value - android:label="@string/app_name"

New Value - android:label="(string you want to put)"

Worked for me, hopefully it will help.

XAMPP permissions on Mac OS X?

if you use one line folder or file

chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)

getMinutes() 0-9 - How to display two digit numbers?

For two digit minutes use: new Date().toLocaleFormat("%M")

Upgrading React version and it's dependencies by reading package.json

you can update all of the dependencies to their latest version by npm update

php how to go one level up on dirname(__FILE__)

You could use PHP's dirname function. <?php echo dirname(__DIR__); ?>. That will give you the name of the parent directory of __DIR__, which stores the current directory.

What does "fatal: bad revision" mean?

I had a "fatal : bad revision" with Idea / Webstorm because I had a git directory inside another, without using properly submodules or subtrees.

I checked for .git dirs with :

find ./ -name '.git' -print

Round up double to 2 decimal places

Just single line of code:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])

Setting a property by reflection with a string value

If you are writing Metro app, you should use other code:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType));

Note:

ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");

instead of

ship.GetType().GetProperty("Latitude");

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

jQuery: Handle fallback for failed AJAX Request

You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    fail: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

EDIT I added a timeout to the $.ajax call and set it to five seconds.

How to make space between LinearLayout children?

Try to add Space widget after adding view like this:

layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)

What column type/length should I use for storing a Bcrypt hashed password in a Database?

If you are using PHP's password_hash() with the PASSWORD_DEFAULT algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash() might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).

From the manual page:

Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT to force password_hash() to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.

Spring Boot application.properties value not populating

You can use Environment Class to get data :

@Autowired
private Environment env;
String prop= env.getProperty('some.prop');

How can I generate a list of files with their absolute path in Linux?

Command: ls -1 -d "$PWD/"*

This will give the absolute paths of the file like below.

[root@kubenode1 ssl]# ls -1 -d "$PWD/"*
/etc/kubernetes/folder/file-test-config.txt
/etc/kubernetes/folder/file-test.txt
/etc/kubernetes/folder/file-client.txt

What is a clean, Pythonic way to have multiple constructors in Python?

I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.

class Gouda(Cheese):
    def __init__(self):
        super(Gouda).__init__(num_holes=10)


class Parmesan(Cheese):
    def __init__(self):
        super(Parmesan).__init__(num_holes=15) 

jQuery - Check if DOM element already exists

if ID is available - You can use getElementById()

var element =  document.getElementById('elementId');
  if (typeof(element) != 'undefined' && element != null)
  { 
     // exists.
  }

OR Try with Jquery -

if ($(document).find(yourElement).length == 0) 
{ 
 // -- Not Exist
}

ADB Android Device Unauthorized

Here's what I did that that brought the authorization prompt and made my device appear. I used a Samsung Galaxy s7 edge.

  1. Enable developer mode and USB debugging on your device.

  2. Revoke the USB debugging authorization

  3. Plug your phone to computer via USB.

  4. Drag notification panel and select "Software Installation" as shown in the image below

    image

  5. This will begin installing USB driver and the prompt for USB debugging authorization will show.

How to set default Checked in checkbox ReactJS?

<div className="display__lbl_input">
              <input
                type="checkbox"
                onChange={this.handleChangeFilGasoil}
                value="Filter Gasoil"
                name="Filter Gasoil"
                id=""
              />
              <label htmlFor="">Filter Gasoil</label>
            </div>

handleChangeFilGasoil = (e) => {
    if(e.target.checked){
        this.setState({
            checkedBoxFG:e.target.value
        })
        console.log(this.state.checkedBoxFG)
    }
    else{
     this.setState({
        checkedBoxFG : ''
     })
     console.log(this.state.checkedBoxFG)
    }
  };

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

Get current time in milliseconds in Python?

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

Check/Uncheck all the checkboxes in a table

Actually your checkAll(..) is hanging without any attachment.

1) Add onchange event handler

<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>

2) Modified the code to handle check/uncheck

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }

Updated Fiddle

Ascending and Descending Number Order in java

Arrays.sort(arr, Collections.reverseOrder());
for(int i = 0; i < arr.length; i++){
    System.out.print( " " +arr[i]);
}

And move Arrays.sort() out of that for loop.. You are sorting the same array on each iteration..

How to find a user's home directory on linux or unix?

Normally you use the statement

String userHome = System.getProperty( "user.home" );

to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)

Save PHP array to MySQL?

check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.

$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";

If the values in the array are text values, you will need to add quotes

$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";

mysql_query($query);

Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.

Return the most recent record from ElasticSearch index

Get the Last ID using by date (with out time stamp)

Sample URL : http://localhost:9200/deal/dealsdetails/
Method : POST

Query :

{
  "fields": ["_id"],
  "sort": [{
      "created_date": {
        "order": "desc"
      }
    },
    {
      "_score": {
        "order": "desc"
      }
    }
  ],
  "size": 1
}

result:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 9,
    "max_score": null,
    "hits": [{
      "_index": "deal",
      "_type": "dealsdetails",
      "_id": "10",
      "_score": 1,
      "sort": [
        1478266145174,
        1
      ]
    }]
  }
}

How do I execute code AFTER a form has loaded?

You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.

How to programmatically set cell value in DataGridView?

in VB you can use this one

Dim selectedRow As DataRowView
selectedRow = dg.Rows(dg.CurrentCell.RowIndex).DataBoundItem
selectedRow("MyProp") = "myValue"
dg.NotifyCurrentCellDirty(True)

thanks to saeed serpooshan for last row

How to check if any value is NaN in a Pandas DataFrame

jwilner's response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:

df.isnull().values.any()

enter image description here

import numpy as np
import pandas as pd
import perfplot


def setup(n):
    df = pd.DataFrame(np.random.randn(n))
    df[df > 0.9] = np.nan
    return df


def isnull_any(df):
    return df.isnull().any()


def isnull_values_sum(df):
    return df.isnull().values.sum() > 0


def isnull_sum(df):
    return df.isnull().sum() > 0


def isnull_values_any(df):
    return df.isnull().values.any()


perfplot.save(
    "out.png",
    setup=setup,
    kernels=[isnull_any, isnull_values_sum, isnull_sum, isnull_values_any],
    n_range=[2 ** k for k in range(25)],
)

df.isnull().sum().sum() is a bit slower, but of course, has additional information -- the number of NaNs.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

If your items are wider than the ListBox, the other answers here won't help: the items in the ItemTemplate remain wider than the ListBox.

The fix that worked for me was to disable the horizontal scrollbar, which, apparently, also tells the container of all those items to remain only as wide as the list box.

Hence the combined fix to get ListBox items that are as wide as the list box, whether they are smaller and need stretching, or wider and need wrapping, is as follows:

<ListBox HorizontalContentAlignment="Stretch" 
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">

(credits for the scroll bar idea)

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Select current date by default in ASP.Net Calendar control

I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.

These now all work:-

<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>

What HTTP status response code should I use if the request is missing a required parameter?

For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.

I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.

I would copy Google.

How to have a default option in Angular.js select box

In my case since the default varies from case to case in the form. I add a custom attribute in the select tag.

 <select setSeletected="{{data.value}}">
      <option value="value1"> value1....
      <option value="value2"> value2....
       ......

in the directives I created a script that checks the value and when angular fills it in sets the option with that value to selected.

 .directive('setSelected', function(){
    restrict: 'A',
    link: (scope, element, attrs){
     function setSel=(){
     //test if the value is defined if not try again if so run the command
       if (typeof attrs.setSelected=='undefined'){             
         window.setTimeout( function(){setSel()},300) 
       }else{
         element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);          
       }
     }
    }

  setSel()

})

just translated this from coffescript on the fly at least the jist of it is correct if not the hole thing.

It's not the simplest way but get it done when the value varies

Logging best practices

As far as aspect oriented logging is concerned I was recommended PostSharp on another SO question -

Aspect Oriented Logging with Unity\T4\anything else

The link provided in the answer is worth visiting if you are evaluating logging frameworks.

AddRange to a Collection

No, this seems perfectly reasonable. There is a List<T>.AddRange() method that basically does just this, but requires your collection to be a concrete List<T>.

findViewByID returns null

Set the activity content from a layout resource. ie.,setContentView(R.layout.basicXml);

How to use jQuery with TypeScript

In my case I had to do this

npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency

Then in the script file A.ts

import * as $ from "jquery";
... jquery code ...

How to add an element to the beginning of an OrderedDict?

I got an infinity loop while trying to print or save the dictionary using @Ashwini Chaudhary answer with Python 2.7. But I managed to reduce his code a little, and got it working here:

def move_to_dict_beginning(dictionary, key):
    """
        Move a OrderedDict item to its beginning, or add it to its beginning.
        Compatible with Python 2.7
    """

    if sys.version_info[0] < 3:
        value = dictionary[key]
        del dictionary[key]
        root = dictionary._OrderedDict__root

        first = root[1]
        root[1] = first[0] = dictionary._OrderedDict__map[key] = [root, first, key]
        dict.__setitem__(dictionary, key, value)

    else:
        dictionary.move_to_end( key, last=False )

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

Check if AJAX response data is empty/blank/null/undefined/0

$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        // do console.log(data);
        console.log(data);
        // you'll find that what exactly inside data 
        // I do not prefer alter(data); now because, it does not 
        // completes requirement all the time 
        // After that you can easily put if condition that you do not want like
        // if(data != '')
        // if(data == null)
        // or whatever you want 
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});

How to select bottom most rows?

Logically,

BOTTOM (x) is all the records except TOP (n - x), where n is the count; x <= n

E.g. Select Bottom 1000 from Employee:

In T-SQL,

DECLARE 
@bottom int,
@count int

SET @bottom = 1000 
SET @count = (select COUNT(*) from Employee)

select * from Employee emp where emp.EmployeeID not in 
(
SELECT TOP (@count-@bottom) Employee.EmployeeID FROM Employee
)

Nginx not running with no error message

For what it's worth: I just had the same problem, after editing the nginx.conf file. I tried and tried restarting it by commanding sudo nginx restart and various other commands. None of them produced any output. Commanding sudo nginx -t to check the configuration file gave the output sudo: nginx: command not found, which was puzzling. I was starting to think there were problems with the path.

Finally, I logged in as root (sudo su) and commanded sudo nginx restart. Now, the command displayed an error message concerning the configuration file. After fixing that, it restarted successfully.

What's the difference between using CGFloat and float?

CGFloat is a regular float on 32-bit systems and a double on 64-bit systems

typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit

So you won't get any performance penalty.

Add an element to an array in Swift

In Swift 4.2: You can use

myArray.append("Tim") //To add "Tim" into array

or

myArray.insert("Tim", at: 0) //Change 0 with specific location 

:not(:empty) CSS selector is not working?

You could try using :placeholder-shown...

_x000D_
_x000D_
input {
  padding: 10px 15px;
  font-size: 16px;
  border-radius: 5px;
  border: 2px solid lightblue;
  outline: 0;
  font-weight:bold;
  transition: border-color 200ms;
  font-family: sans-serif;
}

.validation {
  opacity: 0;
  font-size: 12px;
  font-family: sans-serif;
  color: crimson;
  transition: opacity;
}

input:required:valid {
  border-color: forestgreen;
}

input:required:invalid:not(:placeholder-shown) {
  border-color: crimson;
}

input:required:invalid:not(:placeholder-shown) + .validation {
  opacity: 1;
}

  
_x000D_
<input type="email" placeholder="e-mail" required>
<div class="validation">Not valid</span>
_x000D_
_x000D_
_x000D_

no great support though... caniuse

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

facebook: permanent Page Access Token?

Application request limit reached (#4) - FB API v2.1 and greater

This answer led me to the "ultimate answer for us" and so it is very much related so I am appending it here. While it's related to the above it is different and it seems FB has simplified the process some.

Our sharing counts on our site stopped worked when FB rolled over the api to v 2.1. In our case we already had a FB APP and we were NOT using the FB login. So what we needed to do was get a FB APP Token to make the new requests. This is as of Aug. 23 2016.

  1. Go to: https://developers.facebook.com/tools/explorer
  2. Select the api version and then use GET and paste the following:

    /oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
    

    You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page

  3. Run the graph query and you will see:

    {
       "access_token": "app-id|app-token",
       "token_type": "bearer"
    }
    

    Where

    "app-id"
    and
    "app-token"
    will be your app id from your FB app page and the generated FB App HASH you just received.

  4. Next go test your new APP access token: FB Access Token tester

  5. You should see, by pasting the

    "app-token"
    into the token tester, a single app based token without an expiration date/time.

In our case we are using the FB js sdk so we changed our call to be like so (please note this ONLY gets the share count and not the share and comment count combined like it used to be):

FB.api(
    '/','GET',{
    // this is our FB app token for our FB app 
        access_token: FBAppToken,
        "id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}

This is now working properly. This took a lot of searching and an official bug report with FB to confirm that we have to start making tokenized requests to the FB api. As an aside I did request that they (FB) add a clue to the Error code (#4) that mentions the tokenized request.

I just got another report from one of our devs that our FB comment count is broken as well due to the new need for tokenized requests so I will update this accordingly.

Check if an apt-get package is installed and then install it if it's not on Linux

To check if packagename was installed, type:

dpkg -s <packagename>

You can also use dpkg-query that has a neater output for your purpose, and accepts wild cards, too.

dpkg-query -l <packagename>

To find what package owns the command, try:

dpkg -S `which <command>`

For further details, see article Find out if package is installed in Linux and dpkg cheat sheet.

How to run multiple DOS commands in parallel?

if you have multiple parameters use the syntax as below. I have a bat file with script as below:

start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3 
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6 

This will open multiple consoles.

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

How to fix "set SameSite cookie to none" warning?

If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:

document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";

you could instead use:

document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";

It worked for me. More info here.

Initializing a dictionary in python with a key value and no corresponding values

It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.

1) If you want to count the number of occurrences of keys, you can just do:

Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1

2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:

Definition.get(key)  # returns None if key not stored
Definition.get(key, default_other_than_none)

3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.

For example, if you only want to store values for those keys:

expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
    Definition[key_found] = value

Or if you want to make sure all expected keys were found:

assert(all(key in Definition for key in expected_keys))

Properly embedding Youtube video into bootstrap 3.0 page

This works fine for me...

   .delimitador{
        width:100%;
        margin:auto;
    }
    .contenedor{
        height:0px;
        width:100%;
        /*max-width:560px; /* Así establecemos el ancho máximo (si lo queremos) */
        padding-top:56.25%; /* Relación: 16/9 = 56.25% */
        position:relative;
    }

    iframe{
            position:absolute;
            height:100%;
            width:100%;
            top:0px;
            left:0px;
    }

and then

<div class="delimitador">
<div class="contenedor">
// youtube code 
</div>
</div>

Very Simple, Very Smooth, JavaScript Marquee

I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };

    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();
};
})(jQuery);

usage:

for start: $('#Text1').marquee()

pause: $('#Text1').marquee({ pause: true })

resume: $('#Text1').marquee({ pause: false })

Node.js: Python not found exception due to node-sass and node-gyp

My machine is Windows 10, I've faced similar problems while tried to compile SASS using node-sass package. My node version is v10.16.3 and npm version is 6.9.0

The way that I resolved the problem:

  1. At first delete package-lock.json file and node_modules/ folder.
  2. Open Windows PowerShell as Administrator.
  3. Run the command npm i -g node-sass.
  4. After that, go to the project folder and run npm install
  5. And finally, run the SASS compiling script, in my case, it is npm run build:css

And it works!!

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

WHERE Clause to find all records in a specific month

I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

Let's assume you have a table named things that looks something like this:

id happend_at
-- ----------------
1  2009-01-01 12:08
2  2009-02-01 12:00
3  2009-01-12 09:40
4  2009-01-29 17:55

And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

SELECT id FROM things 
   WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009

Which would return:

id
---
1
3
4

"Could not find a version that satisfies the requirement opencv-python"

As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?

Try this:(Worked in Anaconda Prompt or Pycharm)

pip install opencv-contrib-python

pip install opencv-python

How can I select from list of values in SQL Server

If it is a list of parameters from existing SQL table, for example ID list from existing Table1, then you can try this:

select distinct ID
      FROM Table1
      where 
      ID in (1, 1, 1, 2, 5, 1, 6)
ORDER BY ID;

Or, if you need List of parameters as a SQL Table constant(variable), try this:

WITH Id_list AS (
     select ID
      FROM Table1
      where 
      ID in (1, 1, 1, 2, 5, 1, 6)
)
SELECT distinct * FROM Id_list
ORDER BY ID;

SQLAlchemy: print the actual query

This code is based on brilliant existing answer from @bukzor. I just added custom render for datetime.datetime type into Oracle's TO_DATE().

Feel free to update code to suit your database:

import decimal
import datetime

def printquery(statement, bind=None):
    """
    print a query, with values filled in
    for debugging purposes *only*
    for security, you should always separate queries from their values
    please also note that this function is quite slow
    """
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        if bind is None:
            bind = statement.session.get_bind(
                    statement._mapper_zero_or_none()
            )
        statement = statement.statement
    elif bind is None:
        bind = statement.bind 

    dialect = bind.dialect
    compiler = statement._compiler(dialect)
    class LiteralCompiler(compiler.__class__):
        def visit_bindparam(
                self, bindparam, within_columns_clause=False, 
                literal_binds=False, **kwargs
        ):
            return super(LiteralCompiler, self).render_literal_bindparam(
                    bindparam, within_columns_clause=within_columns_clause,
                    literal_binds=literal_binds, **kwargs
            )
        def render_literal_value(self, value, type_):
            """Render the value of a bind parameter as a quoted literal.

            This is used for statement sections that do not accept bind paramters
            on the target driver/database.

            This should be implemented by subclasses using the quoting services
            of the DBAPI.

            """
            if isinstance(value, basestring):
                value = value.replace("'", "''")
                return "'%s'" % value
            elif value is None:
                return "NULL"
            elif isinstance(value, (float, int, long)):
                return repr(value)
            elif isinstance(value, decimal.Decimal):
                return str(value)
            elif isinstance(value, datetime.datetime):
                return "TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')" % value.strftime("%Y-%m-%d %H:%M:%S")

            else:
                raise NotImplementedError(
                            "Don't know how to literal-quote value %r" % value)            

    compiler = LiteralCompiler(dialect, statement)
    print compiler.process(statement)

how to load url into div tag

$(document).ready(function() {
 $('#content').load('your_url_here');
});

How do I use Notepad++ (or other) with msysgit?

This works for me

git config --global core.editor C:/Progra~1/Notepad++/notepad++.exe

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

How to resolve "local edit, incoming delete upon update" message

I just got this same issue and I found that

$ svn revert foo bar

solved the problem.

svn resolve did not work for me:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working
svn: Try 'svn help' for more info
svn: Not enough arguments provided

$ svn resolve --accept working .

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working foo
Resolved conflicted state of 'foo'

$ svn st
!  +    foo
!  +  C bar
      >   local edit, incoming delete upon update

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

How to randomize (shuffle) a JavaScript array?

the shortest arrayShuffle function

function arrayShuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

How to change column datatype in SQL database without losing data

I can modify the table field's datatype, with these following query: and also in the Oracle DB,

ALTER TABLE table_name
MODIFY column_name datatype;

IsNothing versus Is Nothing

I initially used IsNothing but I've been moving towards using Is Nothing in newer projects, mainly for readability. The only time I stick with IsNothing is if I'm maintaining code where that's used throughout and I want to stay consistent.

Format a JavaScript string using placeholders and an object of substitutions?

As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().

Placeholders:

  • %s String.
  • %d,%i Integer number.
  • %f Floating point number.
  • %o Object hyperlink.

e.g.

console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);

BTW, to see the output:

  • In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
  • In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.

@Update - nodejs support

Seems nodejs don't support %f, instead, could use %d in nodejs. With %d number will be printed as floating number, not just integer.

Cannot find Microsoft.Office.Interop Visual Studio

If you have installed latest Visual studio and want to To locate library of Microsoft.Office.Interop.Outlook or any other Microsoft.Office.Interop library then you should look into below 2 folders:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

Please note that folder could be C:\Program Files\

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

It seems that you can transfer your Certificates and Provisioning profiles from one machine to the other, so if you are having issues in setting up your certificate and/or profiles because you migrated your Dev machine, have a look at this:

how to transfer xcode certificates between macs

Is it possible to specify a different ssh port when using rsync?

I was not able to get rsync to connect via ssh on a different port, but I was able to redirect the ssh connection to the computer I wanted via iptables. This is not the solution I was looking for, but it solved my problem.

Different ways of adding to Dictionary

To insert the Value into the Dictionary

 Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
 dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
 string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
 dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key

How to create a simple proxy in C#?

The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.

How to set index.html as root file in Nginx?

location / { is the most general location (with location {). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; } because of a lot of duplicate content for every subdirectory of your site.

The approach with

try_files $uri $uri/index.html index.html;

is bad, as mentioned in a comment above, because it returns index.html for pages which should not exist on your site (any possible $uri will end up in that). Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files.

Your approach

location = / {
   index index.html;

is also bad, since index makes an internal redirect too. In case you want that, you should be able to handle that in a specific location. Create e.g.

location = /index.html {

as was proposed here. But then you will have a working link http://example.org/index.html, which may be not desired. Another variant, which I use, is:

root /www/my-root;

# http://example.org
# = means exact location
location = / {
    try_files /index.html =404;
}

# disable http://example.org/index as a duplicate content
location = /index      { return 404; }

# This is a general location. 
# (e.g. http://example.org/contacts <- contacts.html)
location / {
    # use fastcgi or whatever you need here
    # return 404 if doesn't exist
    try_files $uri.html =404;
}

P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server { block:

error_log /var/log/nginx/debug.log debug;

and see there all internal redirects etc.

How to Use -confirm in PowerShell

This is a simple loop that keeps prompting unless the user selects 'y' or 'n'

$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
    if ($confirmation -eq 'n') {exit}
    $confirmation = Read-Host "Ready? [y/n]"
}

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3

eg:

Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

How do I remove the title bar from my app?

Best way is to use actionbar function setTitle() if you wish to show logo or have some other stuff in you actionBar but dont want to see name of the app, write this code in MainActivity.java or anywhere you wish to hide title in onCreate:

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.full_white_logo_m); // display logo
actionBar.setTitle(""); // hide title

This way your app won't have reason to crash.

C Program to find day of week given date

The answer I came up with:

const int16_t TM_MON_DAYS_ACCU[12] = {
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};

int tm_is_leap_year(unsigned year) {
    return ((year & 3) == 0) && ((year % 400 == 0) || (year % 100 != 0));
}

// The "Doomsday" the the day of the week of March 0th,
// i.e the last day of February.
// In common years January 3rd has the same day of the week,
// and on leap years it's January 4th.
int tm_doomsday(int year) {
    int result;
    result  = TM_WDAY_TUE;
    result += year;       // I optimized the calculation a bit:
    result += year >>= 2; // result += year / 4
    result -= year /= 25; // result += year / 100
    result += year >>= 2; // result += year / 400
    return result;
}

void tm_get_wyday(int year, int mon, int mday, int *wday, int *yday) {
    int is_leap_year = tm_is_leap_year(year);
    // How many days passed since Jan 1st?
    *yday = TM_MON_DAYS_ACCU[mon] + mday + (mon <= TM_MON_FEB ? 0 : is_leap_year) - 1;
    // Which day of the week was Jan 1st of the given year?
    int jan1 = tm_doomsday(year) - 2 - is_leap_year;
    // Now just add these two values.
    *wday = (jan1 + *yday) % 7;
}

with these defines (matching struct tm of time.h):

#define TM_WDAY_SUN 0
#define TM_WDAY_MON 1
#define TM_WDAY_TUE 2
#define TM_WDAY_WED 3
#define TM_WDAY_THU 4
#define TM_WDAY_FRI 5
#define TM_WDAY_SAT 6

#define TM_MON_JAN  0
#define TM_MON_FEB  1
#define TM_MON_MAR  2
#define TM_MON_APR  3
#define TM_MON_MAY  4
#define TM_MON_JUN  5
#define TM_MON_JUL  6
#define TM_MON_AUG  7
#define TM_MON_SEP  8
#define TM_MON_OCT  9
#define TM_MON_NOV 10
#define TM_MON_DEC 11

Single vs Double quotes (' vs ")

I have had an issue using Bootstrap where using double quotes did matter vs using single quote (which didn't work). class='row-fluid' gave me issues causing the last span to fall below the other spans rather than sitting nicely beside on the far right, whereas class="row-fluid" worked.

PHP salt and hash SHA256 for login password

You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)

<?php
$password1 = $_POST['password'];
$salt      = 'hello_1m_@_SaLT';
$hashed    = hash('sha256', $password1 . $salt);
?>

When you insert :

$qry="INSERT INTO member VALUES('$username', '$hashed')";

And for retrieving user :

$qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";

Use of exit() function

Include stdlib.h in your header, and then call abort(); in any place you want to exit your program. Like this:

switch(varName)
{
    case 1: 
     blah blah;
    case 2:
     blah blah;
    case 3:
     abort();
}

When the user enters the switch accepts this and give it to the case 3 where you call the abort function. It will exit your screen immediately after hitting enter key.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Let's make it simple as hell. If you want a single number for the number of dimensions like 2, 3, 4, etc., then just use tf.rank(). But, if you want the exact shape of the tensor then use tensor.get_shape()

with tf.Session() as sess:
   arr = tf.random_normal(shape=(10, 32, 32, 128))
   a = tf.random_gamma(shape=(3, 3, 1), alpha=0.1)
   print(sess.run([tf.rank(arr), tf.rank(a)]))
   print(arr.get_shape(), ", ", a.get_shape())     


# for tf.rank()    
[4, 3]

# for tf.get_shape()
Output: (10, 32, 32, 128) , (3, 3, 1)

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.

I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.

How to automatically redirect HTTP to HTTPS on Apache servers?

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

Converting .NET DateTime to JSON

You can try a 3rd party library like json.net There's documention on the project site. It does say it requires .net 3.5.

Otherwise there's another one called Nii.json which i believe is a port from java. I found a link to it on this blog

Can we locate a user via user's phone number in Android?

I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.

Reading/writing an INI file

This article on CodeProject "An INI file handling class using C#" should help.

The author created a C# class "Ini" which exposes two functions from KERNEL32.dll. These functions are: WritePrivateProfileString and GetPrivateProfileString. You will need two namespaces: System.Runtime.InteropServices and System.Text.

Steps to use the Ini class

In your project namespace definition add

using INI;

Create a INIFile like this

INIFile ini = new INIFile("C:\\test.ini");

Use IniWriteValue to write a new value to a specific key in a section or use IniReadValue to read a value FROM a key in a specific Section.

Note: if you're beginning from scratch, you could read this MSDN article: How to: Add Application Configuration Files to C# Projects. It's a better way for configuring your application.

Why did Servlet.service() for servlet jsp throw this exception?

I tried my best to follow the answers given above. But I have below reason for the same.

Note: This is for maven+eclipse+tomcat deployment and issue faced especially with spring mvc.

1- If you are including servlet and jsp dependency please mark them provided in scope.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
  1. Possibly you might be including jstl as dependency. So, jsp-api.jar and servlet-api.jar will be included along. So, require to exclude the servlet-api and jsp-api being deployed as required lib in target or in "WEB-INF/lib" as given below.

    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl-api</artifactId>
        <version>1.2</version>
        <exclusions>
            <exclusion>
                <artifactId>servlet-api</artifactId>
                <groupId>javax.servlet</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jsp-api</artifactId>
                <groupId>javax.servlet.jsp</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    

PHP + MySQL transactions examples

As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:

// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)

$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this

// note: this is meant for InnoDB tables. won't work with MyISAM tables.

try {

    $conn->autocommit(FALSE); // i.e., start transaction

    // assume that the TABLE groups has an auto_increment id field
    $query = "INSERT INTO groups (name) ";
    $query .= "VALUES ('$group_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    $group_id = $conn->insert_id; // last auto_inc id from *this* connection

    $query = "INSERT INTO group_membership (group_id,name) ";
    $query .= "VALUES ('$group_id','$member_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    // our SQL queries have been successful. commit them
    // and go back to non-transaction mode.

    $conn->commit();
    $conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {

    // before rolling back the transaction, you'd want
    // to make sure that the exception was db-related
    $conn->rollback(); 
    $conn->autocommit(TRUE); // i.e., end transaction   
}

Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As already explained in other answers, when in Private Browsing mode Safari will always throw this exception when trying to save data with localStorage.setItem() .

To fix this I wrote a fake localStorage that mimics localStorage, both methods and events.

Fake localStorage: https://gist.github.com/engelfrost/fd707819658f72b42f55

This is probably not a good general solution to the problem. This was a good solution for my scenario, where the alternative would be major re-writes to an already existing application.

Ansible: How to delete files and folders inside a directory?

Isn't it that simple ... tested working ..

eg.

---
- hosts: localhost
  vars:
     cleandir: /var/lib/cloud/
  tasks:
   - shell: ls -a -I '.' -I '..' {{ cleandir }}
     register: ls2del
     ignore_errors: yes
   - name: Cleanup {{ cleandir }}
     file:
       path: "{{ cleandir }}{{ item }}"
       state: absent
     with_items: "{{ ls2del.stdout_lines }}"

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

how to make a new line in a jupyter markdown cell

"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."

That inspired me to try using two spaces instead of just one - and it worked!!

(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

How to apply Hovering on html area tag?

You can use jQuery to achieve this

Example:

$(function () {
        $('.map').maphilight();
    });

Go through this LINK to know more.

If the above one doesnt work then go through this link.

EDIT :

Give same class to each area tag like class="mapping"

and try this below code

$('.mapping').mouseover(function() {
    alert($(this).attr('id'));
}).mouseout(function(){
    alert('Mouseout....');      
});

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

Disable Logback in SpringBoot

Just add logback.xml configuration in your classpath and add all your configuration with root appender added. Once the Spring boot completes the bean loading, it will start logging based on your configuration.

"message failed to fetch from registry" while trying to install any module

For me, it's usually a proxy issue, and I try everything:

npm config set registry http://registry.npmjs.org/
npm config set strict-ssl false

npm config set proxy http://myusername:[email protected]:8080
npm config set https-proxy http://myusername:[email protected]:8080
set HTTPS_PROXY=http://myusername:[email protected]:8080
set HTTP_PROXY=http://myusername:[email protected]:8080
export HTTPS_PROXY=http://myusername:[email protected]:8080
export HTTP_PROXY=http://myusername:[email protected]:8080
export http_proxy=http://myusername:[email protected]:8080

npm --proxy http://myusername:[email protected]:8080 \
--without-ssl --insecure -g install

How can I remove the decimal part from JavaScript number?

u can also show a certain number of digit after decimal point(here 2 digits) using following code :

_x000D_
_x000D_
var num = (15.46974).toFixed(2)_x000D_
console.log(num) // 15.47_x000D_
console.log(typeof num) // string
_x000D_
_x000D_
_x000D_

Implements vs extends: When to use? What's the difference?

extends is for extending a class.

implements is for implementing an interface

The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
     public void doAction() {
       //specify what must happen
     }

     public String doThis(int number) {
       //specfiy what must happen
     }
 }

now extending a class

 public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

in this case

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2

Also, note that an @Override tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden

I suggest you do some more research on dynamic binding, polymorphism and in general inheritance in Object-oriented programming

How to fix "could not find a base address that matches schema http"... in WCF

I had to do two things to the IIS configuration of the site/application. My issue had to do with getting net.tcp working in an IIS Web Site App:

First:

  1. Right click on the IIS App name.
  2. Manage Web Site
  3. Advanced Settings
  4. Set Enabled protocols to be "http,net.tcp"

Second:

  1. Under the Actions menu on the right side of the Manager, click Bindings...
  2. Click Add
  3. Change type to "net.tcp"
  4. Set binding information to {open port number}:*
  5. OK

Setting background-image using jQuery CSS property

Further to the other answers, you can also use "background". This is particularly useful when you want to set other properties relating to the way the image is used by the background, such as:

$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");

How to call javascript function on page load in asp.net

use your code within

  <script type="text/javascript">
     function window.onload()
       {

        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
       document.getElementById('<%= offSet.ClientID%>').value = retVal;

      }
  </script>

How can I lookup a Java enum from its String value?

You can define your Enum as following code :

public enum Verbosity 
{
   BRIEF, NORMAL, FULL, ACTION_NOT_VALID;
   private int value;

   public int getValue()
   {
     return this.value;
   } 

   public static final Verbosity getVerbosityByValue(int value)
   {
     for(Verbosity verbosity : Verbosity.values())
     {
        if(verbosity.getValue() == value)
            return verbosity ;
     }

     return ACTION_NOT_VALID;
   }

   @Override
   public String toString()
   {
      return ((Integer)this.getValue()).toString();
   }
};

See following link for more clarification

Get the ID of a drawable in ImageView

Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

Using sed, how do you print the first 'N' characters of a line?

colrm x

For example, if you need the first 100 characters:

cat file |colrm 101 

It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm.

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Set value to an entire column of a pandas dataframe

Python can do unexpected things when new objects are defined from existing ones. You stated in a comment above that your dataframe is defined along the lines of df = df_all.loc[df_all['issueid']==specific_id,:]. In this case, df is really just a stand-in for the rows stored in the df_all object: a new object is NOT created in memory.

To avoid these issues altogether, I often have to remind myself to use the copy module, which explicitly forces objects to be copied in memory so that methods called on the new objects are not applied to the source object. I had the same problem as you, and avoided it using the deepcopy function.

In your case, this should get rid of the warning message:

from copy import deepcopy
df = deepcopy(df_all.loc[df_all['issueid']==specific_id,:])
df['industry'] = 'yyy'

EDIT: Also see David M.'s excellent comment below!

df = df_all.loc[df_all['issueid']==specific_id,:].copy()
df['industry'] = 'yyy'

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

Entity Framework Core add unique constraint code-first

None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

In the instance below I want to ensure the OutletRef field is unique:

public class ApplicationDbContext : IdentityDbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Outlet>()
                .HasIndex(o => new { o.OutletRef });
        }
    }

This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

How to create a DataTable in C# and how to add rows?

You have to add datarows to your datatable for this.

// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();

// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";

// Add the row to the rows collection
dt.Rows.Add ( dr );

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

How to get first character of a string in SQL?

SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student

Spring .properties file: get element as an Array

If you define your array in properties file like:

base.module.elementToSearch=1,2,3,4,5,6

You can load such array in your Java class like this:

  @Value("${base.module.elementToSearch}")
  private String[] elementToSearch;

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

Reading a List from properties file and load with spring annotation @Value

I think this is simpler for grabbing the array and stripping spaces:

@Value("#{'${my.array}'.replace(' ', '').split(',')}")
private List<String> array;

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How can I select an element by name with jQuery?

You can get the element in JQuery by using its ID attribute like this:

$("#tcol1").hide();

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Changing datagridview cell color dynamically

Thanks it working

here i am done with this by qty field is zero means it shown that cells are in red color

        int count = 0;

        foreach (DataGridViewRow row in ItemDg.Rows)
        {
            int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
            if (qtyEntered <= 0)
            {
                ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
                ItemDg[1, count].Style.BackColor = Color.Red;

                ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory                       
            }
            ItemDg[0, count].Value = "0";//assign a default value to quantity enter
            count++;
        }

    }

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

Execute jar file with multiple classpath libraries from command prompt

Let maven generate a batch file to start your application. This is the simplest way to this.

You can use the appassembler-maven-plugin for such purposes.

In a bootstrap responsive page how to center a div

Update for Bootstrap 4

Now that Bootstrap 4 is flexbox, vertical alignment is easier. Given a full height flexbox div, just us my-auto for even top and bottom margins...

<div class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
      <h1 class="display-3">Hello, world!</h1>
    </div>
</div>

http://codeply.com/go/ayraB3tjSd/bootstrap-4-vertical-center


Vertical center in Bootstrap 4

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

This also includes the last date

$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );

for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d");
}

If you dont need the last date just remove = from the condition.

You seem to not be depending on "@angular/core". This is an error

While running ng serve you should be in the app's/project's directory.

If you run the command in another directory you get the error:

You seem to not be depending on "@angular/core". This is an error.

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

Google Maps Android API v2 Authorization failure

Since I just wasted a lot of time getting the API to work, I will try to give a step-by-step validation for the Map API v2:

Step 1: Apply for your API key

If you are unfamiliar with the Google API console, read the very good answer of Rusfearuth above.

Step 2: Check you SHA Hash (in this case I use the debug key of eclipse):

On a Windows machine got to your user directory on a command prompt:

C:\Users\you>keytool -list -alias androiddebugkey -keystore .android\debug.keyst
ore -storepass android -keypass android

You will get something like:

androiddebugkey, 15.10.2012, PrivateKeyEntry,
Zertifikat-Fingerprint (SHA1): 66:XX:47:XX:1E:XX:FE:XX:DE:XX:EF:XX:98:XX:83:XX:9A:XX:23:A6

Then look at your package name of the map activity, e.g. com.example.mypackagename

You combine this and check that with your settings in the Google API console:

66:XX:47:XX:1E:XX:FE:XX:DE:XX:EF:XX:98:XX:83:XX:9A:XX:23:A6;com.example.mypackagename

where you get your API-key:

AZzaSyDhkhNotUseFullKey49ylKD2bw1HM

Step 3. Manifest meta data

Check if the meta-data are present and contain the right key. If you release your app, you need a different key.

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AZzaSyDhkhNotUseFullKey49ylKD2bw1HM" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

Step 4. Manifest features:

You need this entry as the map API requires some grapics support:

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

Do not worry, 99.7% of devices support this.

Step 5. Manifest library:

Add the google library.

    <uses-library
        android:name="com.google.android.maps"
        android:required="false" /> // This is required if you want your app to start in the emulator. I set it to false also if map is not an essential part of the application.

Step 6. Manifest permissions:

Check the package name twice: com.example.yourpackage

<permission
    android:name="com.example.yourpackage.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.yourpackage.permission.MAPS_RECEIVE" />

Add the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

The following permissions are optional and not required if you just show a map. Try to not use them.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Step 7. Include the map fragment into your layout:

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    class="com.google.android.gms.maps.SupportMapFragment"
    map:cameraTargetLat="47.621120"
    map:cameraTargetLng="-122.349594"
    map:cameraZoom="15" />

If your release to 2.x Android versions you need to add support in your Activity:

import android.support.v4.app.FragmentActivity;

For the map: entries to work include

xmlns:map="http://schemas.android.com/apk/res-auto"

in your activity layout (e.g. LinearLayout).

In my case I have to clean the project each time I change something in the layout. Seems to be a bug.

Step 8: Use Eclipse - Project - Clean.

Enjoy!

CSS : center form in page horizontally and vertically

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. align="center" attribute is now obsolete. You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

How to wait until an element exists?

You can do

$('#yourelement').ready(function() {

});

Please note that this will only work if the element is present in the DOM when being requested from the server. If the element is being dynamically added via JavaScript, it will not work and you may need to look at the other answers.

How can I dynamically switch web service addresses in .NET without a recompile?

When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Web Reference Properties

Changing the value to dynamic will put an entry in your app.config.

Here is the CodePlex article that has more information.

Does Django scale?

You can definitely run a high-traffic site in Django. Check out this pre-Django 1.0 but still relevant post here: http://menendez.com/blog/launching-high-performance-django-site/

Calendar date to yyyy-MM-dd format in java

java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.

String myString=format1.format(date);

How to match hyphens with Regular Expression?

[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

depending on you application, i suggest using FLOAT(9,6)

spatial keys will give you more features, but in by production benchmarks the floats are much faster than the spatial keys. (0,01 VS 0,001 in AVG)

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
        $('#btn_ZoomIn').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            })
        $('#btn_ZoomOut').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            })
        $('#btn_ZoomReset').click(
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');
            })
    });

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

Convert categorical data in pandas dataframe

What I do is, I replace values.

Like this-

df['col'].replace(to_replace=['category_1', 'category_2', 'category_3'], value=[1, 2, 3], inplace=True)

In this way, if the col column has categorical values, they get replaced by the numerical values.

Range with step of type float

When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1) return [0.0, 1.1] or [0.0, 1.1, 2.199999999]? There's no way to be certain without rigorous analysis.

The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.

Python - Locating the position of a regex match in a string?

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

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

dotnet now includes a command for gitignore.

Open cmd.exe from your project folder and type:

dotnet new gitignore

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

I was not able to uninstall PostgreSQL 9.0.8. But I finally found this. (I installed Postgres using homebrew)

brew list

Look for the correct folder name. Something like.

postgresql9

Once you find the correct name do:

brew uninstall postgresql9

That should uninstall it.

git: fatal unable to auto-detect email address

Problem solved after I run those commands with sudo

How can I get the username of the logged-in user in Django?

'request.user' has the logged in user.
'request.user.username' will return username of logged in user.

How can I specify a [DllImport] path at runtime?

set the dll path in the config file

<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />

before calling the dll in you app, do the following

string dllPath= ConfigurationManager.AppSettings["dllPath"];    
   string appDirectory = Path.GetDirectoryName(dllPath);
   Directory.SetCurrentDirectory(appDirectory);

then call the dll and you can use like below

 [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

Compare and contrast REST and SOAP web services?

In day to day, practical programming terms, the biggest difference is in the fact that with SOAP you are working with static and strongly defined data exchange formats where as with REST and JSON data exchange formatting is very loose by comparison. For example with SOAP you can validate that exchanged data matches an XSD schema. The XSD therefore serves as a 'contract' on how the client and the server are to understand how the data being exchanged must be structured.

JSON data is typically not passed around according to a strongly defined format (unless you're using a framework that supports it .. e.g. http://msdn.microsoft.com/en-us/library/jj870778.aspx or implementing json-schema).

In-fact, some (many/most) would argue that the "dynamic" secret sauce of JSON goes against the philosophy/culture of constraining it by data contracts (Should JSON RESTful web services use data contract)

People used to working in dynamic loosely typed languages tend to feel more comfortable with the looseness of JSON while developers from strongly typed languages prefer XML.

http://www.mnot.net/blog/2012/04/13/json_or_xml_just_decide

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

Automatically set appsettings.json for dev and release environments in asp.net core?

  1. Create multiple appSettings.$(Configuration).json files like:

    • appSettings.staging.json
    • appSettings.production.json
  2. Create a pre-build event on the project which copies the respective file to appSettings.json:

    copy appSettings.$(Configuration).json appSettings.json
    
  3. Use only appSettings.json in your Config Builder:

    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

.NET console application as Windows service

I use a service class that follows the standard pattern prescribed by ServiceBase, and tack on helpers to easy F5 debugging. This keeps service data defined within the service, making them easy to find and their lifetimes easy to manage.

I normally create a Windows application with the structure below. I don't create a console application; that way I don't get a big black box popping in my face every time I run the app. I stay in in the debugger where all the action is. I use Debug.WriteLine so that the messages go to the output window, which docks nicely and stays visible after the app terminates.

I usually don't bother add debug code for stopping; I just use the debugger instead. If I do need to debug stopping, I make the project a console app, add a Stop forwarder method, and call it after a call to Console.ReadKey.

public class Service : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        // Start logic here.
    }

    protected override void OnStop()
    {
        // Stop logic here.
    }

    static void Main(string[] args)
    {
        using (var service = new Service()) {
            if (Environment.UserInteractive) {
                service.Start();
                Thread.Sleep(Timeout.Infinite);
            } else
                Run(service);
        }
    }
    public void Start() => OnStart(null);
}

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

How to change Jquery UI Slider handle

.ui-slider .ui-slider-handle{
    width:50px; 
    height:50px; 
    background:url(../images/slider_grabber.png) no-repeat; overflow: hidden; 
    position:absolute;
    top: -10px;
    border-style:none; 
}

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

How to extract year and month from date in PostgreSQL without using to_char() function?

It is working for "greater than" functions not for less than.

For example:

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;

is working fine.

but for

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;

I am getting error.

Ignore duplicates when producing map using streams

I have encountered such a problem when grouping object, i always resolved them by a simple way: perform a custom filter using a java.util.Set to remove duplicate object with whatever attribute of your choice as bellow

Set<String> uniqueNames = new HashSet<>();
Map<String, String> phoneBook = people
                  .stream()
                  .filter(person -> person != null && !uniqueNames.add(person.getName()))
                  .collect(toMap(Person::getName, Person::getAddress));

Hope this helps anyone having the same problem !

how to call url of any other website in php

If you meant .. to REDIRECT from that page to another, the function is really simple

header("Location:www.google.com");

php return 500 error but no error log

Here is another reason why errors might not be visible:

I had the same issue. In my case, I had copied the source from a production environment. Hence the ENVIRONMENT variable defined in index.php was set to 'production'. This caused error_reporting to be set to 0 (no logging). Just set it to 'development' and you should start seeing error messages in apache log.

Turned out the 500 was due to a semi colon missing in database config :-)

Homebrew refusing to link OpenSSL

The solution above from edwardthesecond worked for me too on Sierra

 brew install openssl
 cd /usr/local/include 
 ln -s ../opt/openssl/include/openssl 
 ./configure && make

Other steps I did before were:

  • installing openssl via brew

    brew install openssl
    
  • adding openssl to the path as suggested by homebrew

    brew info openssl
    echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
    

How to load up CSS files using Javascript?

Use this code:

var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "external.css");
document.getElementsByTagName("head")[0].appendChild(element);

How to detect current state within directive

Also you can use ui-sref-active directive:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

Or filters: "stateName" | isState & "stateName" | includedByState