Programs & Examples On #Has many through

In Ruby on Rails, a has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t
    Rake::Task["build"].reenable
    Rake::Task["build"].invoke
  end
end

That should sort you out, just needed the same thing myself.

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

How to add property to a class dynamically?

For those coming from search engines, here are the two things I was looking for when talking about dynamic properties:

class Foo:
    def __init__(self):
        # we can dynamically have access to the properties dict using __dict__
        self.__dict__['foo'] = 'bar'

assert Foo().foo == 'bar'


# or we can use __getattr__ and __setattr__ to execute code on set/get
class Bar:
    def __init__(self):
        self._data = {}
    def __getattr__(self, key):
        return self._data[key]
    def __setattr__(self, key, value):
        self._data[key] = value

bar = Bar()
bar.foo = 'bar'
assert bar.foo == 'bar'

__dict__ is good if you want to put dynamically created properties. __getattr__ is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).

If you only want one dynamic property, have a look at the property() built-in function.

How to analyse the heap dump using jmap in java

MAT, jprofiler,jhat are possible options. since jhat comes with jdk, you can easily launch it to do some basic analysis. check this out

Selenium using Python - Geckodriver executable needs to be in PATH

Some additional input/clarification for future readers of this thread:

The following suffices as a resolution for Windows 7, Python 3.6, and Selenium 3.11:

dsalaj's note for another answer for Unix is applicable to Windows as well; tinkering with the PATH environment variable at the Windows level and restart of the Windows system can be avoided.

(1) Download geckodriver (as described in this thread earlier) and place the (unzipped) geckdriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 10 seconds for the above code to open up the Firefox browser for the specified URL. (2) The Python console would show the following error if there's no server already running at the specified URL or serving a page with the title containing the string 'Django': selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%9

TypeError : Unhashable type

The real reason because set does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

How to get the current date without the time?

You can use following code to get the date and time separately.

DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];

You can also, check the MSDN for more information.

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

Select NOT IN multiple columns

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

How to avoid .pyc files?

From "What’s New in Python 2.6 - Interpreter Changes":

Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.dont_write_bytecode variable, and Python code can change the value to modify the interpreter’s behaviour.

Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc files by introducing a special __pycache__ subfolder, see What's New in Python 3.2 - PYC Repository Directories.

How to determine CPU and memory consumption from inside a process?

On linux, you cannot/shouldnot get "Total Available Physical Memory" with SysInfo's freeram or by doing some arithmetic on totalram. The recommended way to do this is by reading proc/meminfo, quoting https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773:

Many load balancing and workload placing programs check /proc/meminfo to estimate how much free memory is available. They generally do this by adding up "free" and "cached", which was fine ten years ago, but is pretty much guaranteed to be wrong today.

It is more convenient to provide such an estimate in /proc/meminfo. If things change in the future, we only have to change it in one place.

One way to do it is as https://stackoverflow.com/a/350039/7984460 suggest: read the file, and use fscanf to grab the line (but instead of going for MemTotal, go for MemAvailable)

Likewise, if you want to get the total amounf of physical memory used, depending on what you mean by "use", you might not want to subtract freeram from totalram, but subtract memavailable from memtotal to get what top/htop tell you.

How to put a UserControl into Visual Studio toolBox

The issue with my designer was 32 vs 64 bit issue. I could add the control to tool box after following the instructions in Cannot add Controls from 64-bit Assemblies to the Toolbox or Use in Designers Within the Visual Studio IDE MS KB article.

How to create threads in nodejs

If you're using Rx, it's rather simple to plugin in rxjs-cluster to split work into parallel execution. (disclaimer: I'm the author)

https://www.npmjs.com/package/rxjs-cluster

iOS 7 - Failing to instantiate default view controller

enter image description here

Apart from above correct answer, also make sure that you have set correct Main Interface in General.

CSS flex, how to display one item on first line and two on the next line

You can do something like this:

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.flex>div {_x000D_
  flex: 1 0 50%;_x000D_
}_x000D_
_x000D_
.flex>div:first-child {_x000D_
  flex: 0 1 100%;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div>Hi</div>_x000D_
  <div>Hello</div>_x000D_
  <div>Hello 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is a demo: http://jsfiddle.net/73574emn/1/

This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basis to be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;

The identity used to sign the executable is no longer valid

Experienced the same issue. Was an issue with an expired certificate. You'll need to create a new cert and corresponding prov profile. Follow dulgan's advice for doing so.

SQL Column definition : default value and not null redundant?

My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.

Like this:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL

What is the difference between a Docker image and a container?

Dockerfile is like your Bash script that produce a tarball (Docker image).

Docker containers is like extracted version of the tarball. You can have as many copies as you like in different folders (the containers).

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

jQuery access input hidden value

There's a jQuery selector for that:

// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );

// Filter those which have a specific type
hidden_fields.attr( 'text' );

Will give you all hidden input fields and filter by those with a specific type="".

Python import csv to list

Here is the easiest way in Python 3.x to import a CSV to a multidimensional array, and its only 4 lines of code without importing anything!

#pull a CSV into a multidimensional array in 4 lines!

L=[]                            #Create an empty list for the main array
for line in open('log.txt'):    #Open the file and read all the lines
    x=line.rstrip()             #Strip the \n from each line
    L.append(x.split(','))      #Split each line into a list and add it to the
                                #Multidimensional array
print(L)

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

oracle driver. `

<dependency>
    <groupId>com.hynnet</groupId>
    <artifactId>jdbc-fo</artifactId>
    <version>12.1.0.2</version>
</dependency>

`

What’s the best way to get an HTTP response code from a URL?

In future, for those that use python3 and later, here's another code to find response code.

import urllib.request

def getResponseCode(url):
    conn = urllib.request.urlopen(url)
    return conn.getcode()

Making a WinForms TextBox behave like your browser's address bar

Click event of textbox? Or even MouseCaptureChanged event works for me. - OK. doesn't work.

So you have to do 2 things:

private bool f = false;

private void textBox_MouseClick(object sender, MouseEventArgs e)
{ 
  if (this.f) { this.textBox.SelectAll(); }
  this.f = false;
}

private void textBox_Enter(object sender, EventArgs e)
{
  this.f = true;
  this.textBox.SelectAll();
}
private void textBox_MouseMove(object sender, MouseEventArgs e) // idea from the other answer
{
  this.f = false; 
}

Works for tabbing (through textBoxes to the one) as well - call SelectAll() in Enter just in case...

Python Variable Declaration

Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.

list = []
for i in stuff:
  list.append(i)

By the way, this is not really a good way to setup the list. It would be better to say:

list = [i for i in stuff] # list comprehension

...but I digress.

Your other question. The custom object should be a class itself.

class CustomObject(): # always capitalize the class name...this is not syntax, just style.
  pass
customObj = CustomObject()

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

Why is @font-face throwing a 404 error on woff files?

Solution for IIS7

I also came across the same issue. I think doing this configuration from the server level would be better since it applies for all the websites.

  1. Go to IIS root node and double-click the "MIME Types" configuration option

  2. Click "Add" link in the Actions panel on the top right.

  3. This will bring up a dialog. Add .woff file extension and specify "application/x-font-woff" as the corresponding MIME type.

Add MIME Type for .woff file name extension

Go to MIME Types

Add MIME Type

Here is what I did to solve the issue in IIS 7

seek() function?

The seek function expect's an offset in bytes.

Ascii File Example:

So if you have a text file with the following content:

simple.txt

abc

You can jump 1 byte to skip over the first character as following:

fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc

Binary file example gathering width :

fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]

Note: Once you call read you are changing the position of the read-head, which act's like seek.

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

FTP/SFTP access to an Amazon S3 Bucket

Amazon has released SFTP services for S3, but they only do SFTP (not FTP or FTPES) and they can be cost prohibitive depending on your circumstances.

I'm the Founder of DocEvent.io, and we provide FTP/S Gateways for your S3 bucket without having to spin up servers or worry about infrastructure.

There are also other companies that provide a standalone FTP server that you pay by the month that can connect to an S3 bucket through the software configuration, for example brickftp.com.

Lastly there are also some AWS Marketplace apps that can help, here is a search link. Many of these spin up instances in your own infrastructure - this means you'll have to manage and upgrade the instances yourself which can be difficult to maintain and configure over time.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

In my case it was an issue with the configuration file web.config on my machine when I updated the newton version VS automatically fixed my web.config file to point to the new version. When I uploaded it to production the existing web.config was pointing to the old version.

Once I updated the web.config it started working again.

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
  </dependentAssembly>

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Web-scraping JavaScript page with Python

If you have ever used the Requests module for python before, I recently found out that the developer created a new module called Requests-HTML which now also has the ability to render JavaScript.

You can also visit https://html.python-requests.org/ to learn more about this module, or if your only interested about rendering JavaScript then you can visit https://html.python-requests.org/?#javascript-support to directly learn how to use the module to render JavaScript using Python.

Essentially, Once you correctly install the Requests-HTML module, the following example, which is shown on the above link, shows how you can use this module to scrape a website and render JavaScript contained within the website:

from requests_html import HTMLSession
session = HTMLSession()

r = session.get('http://python-requests.org/')

r.html.render()

r.html.search('Python 2 will retire in only {months} months!')['months']

'<time>25</time>' #This is the result.

I recently learnt about this from a YouTube video. Click Here! to watch the YouTube video, which demonstrates how the module works.

Let JSON object accept bytes or let urlopen output strings

Your workaround actually just saved me. I was having a lot of problems processing the request using the Falcon framework. This worked for me. req being the request form curl pr httpie

json.loads(req.stream.read().decode('utf-8'))

How to disable logging on the standard error stream in Python?

There are some really nice answers here, but apparently the simplest is not taken too much in consideration (only from infinito).

root_logger = logging.getLogger()
root_logger.disabled = True

This disables the root logger, and thus all the other loggers. I haven't really tested but it should be also the fastest.

From the logging code in python 2.7 I see this

def handle(self, record):
    """
    Call the handlers for the specified record.

    This method is used for unpickled records received from a socket, as
    well as those created locally. Logger-level filtering is applied.
    """
    if (not self.disabled) and self.filter(record):
        self.callHandlers(record)

Which means that when it's disabled no handler is called, and it should be more efficient that filtering to a very high value or setting a no-op handler for example.

MsgBox "" vs MsgBox() in VBScript

A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

MsgBox(prompt[, buttons][, title][, helpfile, context])

indicate, this routine is of the third kind.

The syntactical rules of VBScript are simple:

Use parameter list () when calling a (routine as a) Function

If you want to display a message to the user and need to know the user's reponse:

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Don't use parameter list () when calling a (routine as a) Sub

If you want to display a message to the user and are not interested in the response:

MsgBox "Hello World!", 65, "MsgBox Example"

This beautiful simplicity is messed up by:

The design flaw of using () for parameter lists and to force call-by-value semantics

>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2

S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that

>> s = "value"
>> MsgBox(s)

'works' are in for a suprise when they try:

>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number:       1044
Error Description:  Cannot use parentheses when calling a Sub

The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by

Randomize()

although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in

Randomize n

and

Randomize (n)

The Call statement that allows parameter list () in Sub calls:

s = "value" Call MsgBox(s, 65, "MsgBox Example")

which further encourage programmers to use () without thinking.

(Based on What do you mean "cannot use parentheses?")

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

Depending on the boost version libboost-system comes with the -mt suffix which should indicate the libraries multithreading capability.

So if -lboost_system cannot be found by the linker try -lboost_system-mt.

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

Converting java.util.Properties to HashMap<String,String>

The Java 8 way:

properties.entrySet().stream().collect(
    Collectors.toMap(
         e -> e.getKey().toString(),
         e -> e.getValue().toString()
    )
);

Remove substring from the string

def replaceslug
  slug = "" + name
    @replacements = [
      [ "," , ""],
      [ "\\?" , ""],
      [ " " , "-"],
      [ "'" , "-"],
      [ "Ç" , "c"],
      [ "S" , "s"],
      [ "I" , "i"],
      [ "I" , "i"],
      [ "Ü" , "u"],
      [ "Ö" , "o"],
      [ "G" , "g"],
      [ "ç" , "c"],
      [ "s" , "s"],
      [ "i" , "i"],
      [ "ü" , "u"],
      [ "ö" , "o"],
      [ "g" , "g"],
    ]
  @replacements.each do |pair|
    slug.gsub!(pair[0], pair[1])
  end
  self.slug = slug.downcase
end

How to mark a method as obsolete or deprecated?

The shortest way is by adding the ObsoleteAttribute as an attribute to the method. Make sure to include an appropriate explanation:

[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }

You can also cause the compilation to fail, treating the usage of the method as an error instead of warning, if the method is called from somewhere in code like this:

[Obsolete("Method1 is deprecated, please use Method2 instead.", true)]

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

Date formatting in WPF datagrid

Very late to the party here but in case anyone else stumbles across this page...

You can do it by setting the AutoGeneratingColumn handler in XAML:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

And then in code behind do something like this:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}

How to play a local video with Swift?

Swift 3

if let filePath = Bundle.main.path(forResource: "small", ofType: ".mp4") {
    let filePathURL = NSURL.fileURL(withPath: filePath)

    let player = AVPlayer(url: filePathURL)
    let playerController = AVPlayerViewController()
    playerController.player = player
    self.present(playerController, animated: true) {
        player.play()
    }
}

How to Check whether Session is Expired or not in asp.net

I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.

However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.

You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="30">
  </forms>
</authentication>

The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.

There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

How to set a default value with Html.TextBoxFor?

You can simply do :

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :

@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

C/C++ Struct vs Class

It's not possible to define member functions or derive structs from each other in C.

Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I just got the same error, when I didn't use the correct case. I could checkout out 'integration'. Git told me to perform a git pull to update my branch. I did that, but received the mentioned error. The correct branch name is 'Integration' with a capital 'I'. When I checked out that branch and pulled, it worked without problem.

Understanding React-Redux and mapStateToProps()

This react & redux example is based off Mohamed Mellouki's example. But validates using prettify and linting rules. Note that we define our props and dispatch methods using PropTypes so that our compiler doesn't scream at us. This example also included some lines of code that had been missing in Mohamed's example. To use connect you will need to import it from react-redux. This example also binds the method filterItems this will prevent scope problems in the component. This source code has been auto formatted using JavaScript Prettify.

import React, { Component } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class ItemsContainer extends Component {
  constructor(props) {
    super(props);
    const { items, filters } = props;
    this.state = {
      items,
      filteredItems: filterItems(items, filters),
    };
    this.filterItems = this.filterItems.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const { itmes } = this.state;
    const { filters } = nextProps;
    this.setState({ filteredItems: filterItems(items, filters) });
  }

  filterItems = (items, filters) => {
    /* return filtered list */
  };

  render() {
    return <View>/*display the filtered items */</View>;
  }
}

/*
define dispatch methods in propTypes so that they are validated.
*/
ItemsContainer.propTypes = {
  items: PropTypes.array.isRequired,
  filters: PropTypes.array.isRequired,
  onMyAction: PropTypes.func.isRequired,
};

/*
map state to props
*/
const mapStateToProps = state => ({
  items: state.App.Items.List,
  filters: state.App.Items.Filters,
});

/*
connect dispatch to props so that you can call the methods from the active props scope.
The defined method `onMyAction` can be called in the scope of the componets props.
*/
const mapDispatchToProps = dispatch => ({
  onMyAction: value => {
    dispatch(() => console.log(`${value}`));
  },
});

/* clean way of setting up the connect. */
export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);

This example code is a good template for a starting place for your component.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:

<configuration>
  <appSettings>
    <add key="key" value="value"/>
  </appSettings>
</configuration>

limit text length in php and provide 'Read more' link

Basically, you need to integrate a word limiter (e.g. something like this) and use something like shadowbox. Your read more link should link to a PHP script that displays the entire article. Just setup Shadowbox on those links and you're set. (See instructions on their site. Its easy.)

How to compare pointers?

It depends on the types of the values, and the way that operators happen to have been defined. For example, string comparison is by value, not by address. But char * is by address normally (I think).

A big trap for the unwary. There is no guaranteed pointer comparison operator, but

  (void *)a == (void *)b 

is probably fairly safe.

SQL Server Operating system error 5: "5(Access is denied.)"

Yes,It's right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of "C:\Murach\SQL Server 2008\Databases" to the service account.

Property 'map' does not exist on type 'Observable<Response>'

You need to import the map operator:

import 'rxjs/add/operator/map'

Or more generally:

import 'rxjs/Rx';

Notice: For versions of RxJS 6.x.x and above, you will have to use pipeable operators as shown in the code snippet below:

import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

// ...
export class MyComponent {
  constructor(private http: HttpClient) { }
  getItems() {
    this.http.get('https://example.com/api/items').pipe(map(data => {})).subscribe(result => {
      console.log(result);
    });
  }
}

This is caused by the RxJS team removing support for using See the breaking changes in RxJS' changelog for more info.

From the changelog:

operators: Pipeable operators must now be imported from rxjs like so: import { map, filter, switchMap } from 'rxjs/operators';. No deep imports.

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

What worked for me was simply to do the following:

open the php.ini file.

Under the DYNAMIC EXTENSIONS heading, comment out the following line as

;extension=php_java.dll

Restarted Apache and all was fine

How to completely DISABLE any MOUSE CLICK

You can overlay a big, semi-transparent <div> that takes all the clicks. Just append a new <div> to <body> with this style:

.overlay {
    background-color: rgba(1, 1, 1, 0.7);
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
}

Vim delete blank lines

This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function

fun! DelBlank()
   let _s=@/
   let l = line(".")
   let c = col(".")
   :g/^\n\{2,}/d
   let @/=_s
   call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>

How to convert a string or integer to binary in Ruby?

I am almost a decade late but if someone still come here and want to find the code without using inbuilt function like to_S then I might be helpful.

find the binary

def find_binary(number)
  binary = []  
  until(number == 0)
    binary << number%2
    number = number/2
  end
  puts binary.reverse.join
end

Shortcut to open file in Vim

unless I'm missing something, :e filename is the fastest way I've found.

You can use tab to autocomplete the filename as well.

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

Count the items from a IEnumerable<T> without iterating?

I use IEnum<string>.ToArray<string>().Length and it works fine.

In the shell, what does " 2>&1 " mean?

echo test > afile.txt

redirects stdout to afile.txt. This is the same as doing

echo test 1> afile.txt

To redirect stderr, you do:

echo test 2> afile.txt

>& is the syntax to redirect a stream to another file descriptor - 0 is stdin, 1 is stdout, and 2 is stderr.

You can redirect stdout to stderr by doing:

echo test 1>&2 # or echo test >&2

Or vice versa:

echo test 2>&1

So, in short... 2> redirects stderr to an (unspecified) file, appending &1 redirects stderr to stdout.

Convert hex to binary

Use Built-in format() function and int() function It's simple and easy to understand. It's little bit simplified version of Aaron answer

int()

int(string, base)

format()

format(integer, # of bits)

Example

# w/o 0b prefix
>> format(int("ABC123EFFF", 16), "040b")
1010101111000001001000111110111111111111

# with 0b prefix
>> format(int("ABC123EFFF", 16), "#042b")
0b1010101111000001001000111110111111111111

# w/o 0b prefix + 64bit
>> format(int("ABC123EFFF", 16), "064b")
0000000000000000000000001010101111000001001000111110111111111111

See also this answer

Compare every item to every other item in ArrayList

The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.

List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}

Output is true true false

JavaScript - Getting HTML form values

This is a developed example of https://stackoverflow.com/a/41262933/2464828

Consider

<form method="POST" enctype="multipart/form-data" onsubmit="return check(event)">
    <input name="formula">
</form>

Let us assume we want to retrieve the input of name formula. This can be done by passing the event in the onsubmit field. We can then use FormData to retrieve the values of this exact form by referencing the SubmitEvent object.

const check = (e) => {
    const form = new FormData(e.target);
    const formula = form.get("formula");
    console.log(formula);
    return false
};

The JavaScript code above will then print the value of the input to the console.

If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

how to delete a specific row in codeigniter?

**multiple delete not working**

function delete_selection() 
{
        $id_array = array();
        $selection = $this->input->post("selection", TRUE);
        $id_array = explode("|", $selection);

        foreach ($id_array as $item):
            if ($item != ''):
                //DELETE ROW
                $this->db->where('entry_id', $item);
                $this->db->delete('helpline_entry');
            endif;
        endforeach;
    }

How do I pass a unique_ptr argument to a constructor or a function?

Edit: This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: How do I pass a unique_ptr argument to a constructor or a function?

The basic idea of ::std::move is that people who are passing you the unique_ptr should be using it to express the knowledge that they know the unique_ptr they're passing in will lose ownership.

This means you should be using an rvalue reference to a unique_ptr in your methods, not a unique_ptr itself. This won't work anyway because passing in a plain old unique_ptr would require making a copy, and that's explicitly forbidden in the interface for unique_ptr. Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use ::std::move inside your methods as well.

This means your two methods should look like this:

Base(Base::UPtr &&n) : next(::std::move(n)) {} // Spaces for readability

void setNext(Base::UPtr &&n) { next = ::std::move(n); }

Then people using the methods would do this:

Base::UPtr objptr{ new Base; }
Base::UPtr objptr2{ new Base; }
Base fred(::std::move(objptr)); // objptr now loses ownership
fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership

As you see, the ::std::move expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have objptr suddenly lose ownership for no readily apparent reason.

Using Regular Expressions to Extract a Value in Java

In Java 1.4 and up:

String input = "...";
Matcher matcher = Pattern.compile("[^0-9]+([0-9]+)[^0-9]+").matcher(input);
if (matcher.find()) {
    String someNumberStr = matcher.group(1);
    // if you need this to be an int:
    int someNumberInt = Integer.parseInt(someNumberStr);
}

How to set a Fragment tag by code?

Nowadays there's a simpler way to achieve this if you are using a DialogFragment (not a Fragment):

val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
    activity.supportFragmentManager,
    "YOUR_TAG_FRAGMENT"
)

Under the hood, the show() method does create a FragmentTransaction and adds the tag by using the add() method. But it's much more convenient to use the show() method in my opinion.

You could shorten it for Fragment too, by using a Kotlin Extension :)

receiving json and deserializing as List of object at spring mvc controller

For me below code worked, first sending json string with proper headers

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

And then on Spring side -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.

My json object is like this -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

Can a Byte[] Array be written to a file in C#?

You can use the FileStream.Write(byte[] array, int offset, int count) method to write it out.

If your array name is "myArray" the code would be.

myStream.Write(myArray, 0, myArray.count);

How to compare two dates to find time difference in SQL Server 2005, date manipulation

If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)

SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;

Various DATEDIFF functionalities are:

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017

How to print bytes in hexadecimal using System.out.println?

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

Add a common Legend for combined ggplots

If you are plotting the same variables in both plots, the simplest way would be to combine the data frames into one, then use facet_wrap.

For your example:

big_df <- rbind(df1,df2)

big_df <- data.frame(big_df,Df = rep(c("df1","df2"),
times=c(nrow(df1),nrow(df2))))

ggplot(big_df,aes(x=x, y=y,colour=group)) 
+ geom_point(position=position_jitter(w=0.04,h=0.02),size=1.8) 
+ facet_wrap(~Df)

Plot 1

Another example using the diamonds data set. This shows that you can even make it work if you have only one variable common between your plots.

diamonds_reshaped <- data.frame(price = diamonds$price,
independent.variable = c(diamonds$carat,diamonds$cut,diamonds$color,diamonds$depth),
Clarity = rep(diamonds$clarity,times=4),
Variable.name = rep(c("Carat","Cut","Color","Depth"),each=nrow(diamonds)))

ggplot(diamonds_reshaped,aes(independent.variable,price,colour=Clarity)) + 
geom_point(size=2) + facet_wrap(~Variable.name,scales="free_x") + 
xlab("")

Plot 2

Only tricky thing with the second example is that the factor variables get coerced to numeric when you combine everything into one data frame. So ideally, you will do this mainly when all your variables of interest are the same type.

In Maven how to exclude resources from the generated jar?

Do you mean to property files located in src/main/resources? Then you should exclude them using the maven-resource-plugin. See the following page for details:

http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html

What issues should be considered when overriding equals and hashCode in Java?

Logically we have:

a.getClass().equals(b.getClass()) && a.equals(b) ? a.hashCode() == b.hashCode()

But not vice-versa!

javascript windows alert with redirect function

Use this if you also want to consider non-javascript users:

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://someplace.com';
       </SCRIPT>
       <NOSCRIPT>
           <a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
       </NOSCRIPT>");

How can I clear the Scanner buffer in Java?

This should fix it...

Scanner in=new Scanner(System.in);
    int rounds = 0;
    while (rounds < 1 || rounds > 3) {
        System.out.print("How many rounds? ");
        if (in.hasNextInt()) {
            rounds = in.nextInt();
        } else {
            System.out.println("Invalid input. Please try again.");
            in.next(); // -->important
            System.out.println();
        }
        // Clear buffer
    }
    System.out.print(rounds+" rounds.");

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

How to get child element by class name?

Here is a relatively simple recursive solution. I think a breadth-first search is appropriate here. This will return the first element matching the class that is found.

function getDescendantWithClass(element, clName) {
    var children = element.childNodes;
    for (var i = 0; i < children.length; i++) {
        if (children[i].className &&
            children[i].className.split(' ').indexOf(clName) >= 0) {
            return children[i];
         }
     }
     for (var i = 0; i < children.length; i++) {
         var match = getDescendantWithClass(children[i], clName);
         if (match !== null) {
             return match;
         }
     }
     return null;
}

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

AngularJs ReferenceError: $http is not defined

Probably you haven't injected $http service to your controller. There are several ways of doing that.

Please read this reference about DI. Then it gets very simple:

function MyController($scope, $http) {
   // ... your code
}

Converting LastLogon to DateTime format

Get-ADUser -Filter {Enabled -eq $true} -Properties Name,Manager,LastLogon | 
Select-Object Name,Manager,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}

Node.js Write a line into a .txt file

I did a log file which prints data into text file using "Winston" log. The source code is here below,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';var s = '         ';var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];

array1[0]  =  78;`
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;

for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}

for (var k=0;k<4;k++)
{
array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}

function mydata()      //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++) 
{
logger.write(array3[n]);
}
logger.write(endOfLine); 
}

for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}

A completely free agile software process tool

EDIT: Kanbanize is a commercial product and offers a 30 day free trial.

Disclosing: I am a co-founder of http://kanbanize.com/

Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.

Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.

Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.

I hope that helps.

How to make Google Fonts work in IE?

You can try fontsforweb.com where fonts are working for all browsers, because they are provided in TTF, WOFF and EOT formats together with CSS code ready to be pasted on your page i.e.

@font-face{ 
    font-family: "gothambold1";
    src: url('http://fontsforweb.com/public/fonts/5903/gothambold1.eot');
    src: local("Gotham-Bold"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.woff') format("woff"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.ttf') format("truetype");
}
.fontsforweb_fontid_5903 {
    font-family: "gothambold1";
}

or you can download them zipped in a package with CSS file attached

then just add class to any element to apply that font i.e.

<h2 class="fontsforweb_fontid_5903">This will be written with Gotham Bold font and will work in all browsers</h2>

See it working: http://jsfiddle.net/SD4MP/

Convert file to byte array and vice versa

//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 

FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);

//Now the bytes of the file are contain in the "byte[] data"
/*If you want to convert these bytes into a file, you have to write these bytes to a 
certain location, then it will make a new file at that location if same named file is 
not available at that location*/
FileOutputStream fileOutputStream =new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Video.mp4");
fileOutputStream.write(data);
 /* It will write or make a new file named Video.mp4 in the "Download" directory of 
    the External Storage */

Regular Expression Match to test for a valid year

This works for 1900 to 2099:

/(?:(?:19|20)[0-9]{2})/

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

How do I find files that do not contain a given string pattern?

Problem

I need to refactor a large project which uses .phtml files to write out HTML using inline PHP code. I want to use Mustache templates instead. I want to find any .phtml giles which do not contain the string new Mustache as these still need to be rewritten.

Solution

find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

Explanation

Before the pipes:

Find

find . Find files recursively, starting in this directory

-iname '*.phtml' Filename must contain .phtml (the i makes it case-insensitive)

-exec 'grep -H -E -o -c 'new Mustache' {}' Run the grep command on each of the matched paths

Grep

-H Always print filename headers with output lines.

-E Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

-o Prints only the matching part of the lines.

-c Only a count of selected lines is written to standard output.


This will give me a list of all file paths ending in .phtml, with a count of the number of times the string new Mustache occurs in each of them.

$> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/orders.phtml:1
./app/MyApp/Customer/View/Account/banking.phtml:1
./app/MyApp/Customer/View/Account/applycomplete.phtml:1
./app/MyApp/Customer/View/Account/catalogue.phtml:1
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The first pipe grep :0$ filters this list to only include lines ending in :0:

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The second pipe sed 's/..$//' strips off the final two characters of each line, leaving just the file paths.

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
./app/MyApp/Customer/View/Account/studio.phtml
./app/MyApp/Customer/View/Account/classadd.phtml
./app/MyApp/Customer/View/Account/orders-trade.phtml

how to change the dist-folder path in angular-cli after 'ng build'

For Angular 6+ things have changed a little.

Define where ng build generates app files

Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "outputPath": "dist/my-app-name",

Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.

You can overwrite the output path using command line arguments (e.g. for CI jobs):

ng build -op dist/example
ng build --output-path=dist/example

S.a. https://github.com/angular/angular-cli/wiki/build

Hosting angular app in subdirectory

Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.

To make it work in a sub directory, you'll have to set the base href.

In angular.json:

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "baseHref": "/my-folder/",

Cli:

ng build --base-href=/my-folder/

If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.

Here's an example how we do it in our docker container:

entrypoint.sh

if [ -n "${BASE_PATH}" ]
then
  files=( $(find . -name "index.html") )
  cp -n "${files[0]}" "${files[0]}.org"
  cp "${files[0]}.org" "${files[0]}"
  sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi

How to set the color of "placeholder" text?

Try this

_x000D_
_x000D_
input::-webkit-input-placeholder { /* WebKit browsers */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */_x000D_
    color:    #f51;_x000D_
}_x000D_
input::-moz-placeholder { /* Mozilla Firefox 19+ */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-ms-input-placeholder { /* Internet Explorer 10+ */_x000D_
    color:    #f51;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

What is a callback in java

Maybe an example would help.

Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

How to get Android GPS location

Here's your problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

Latitude and Longitude are double-values, because they represent the location in degrees.

By casting them to int, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"

Eclipse C++ : "Program "g++" not found in PATH"

Maybe it has nothing to do here, but it could be useful for someone.
I installed jdk on: D:\Program Files\Java\jdk1.7.0_06\bin
So I added it to %PATH% variable and checked it on cmd and everything was ok, but Eclipse kept showing me that error.
I used quotation marks on %PATH% so it reads something like:

%SYSTEMROOT%\System32;"D:\Program Files\Java\jdk1.7.0_06\bin"

and problem solved.

SQL Server procedure declare a list

Alternative to @Peter Monks.

If the number in the 'in' statement is small and fixed.

DECLARE @var1 varchar(30), @var2 varchar(30), @var3  varchar(30);

SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';

Select * FROM Database Where x in (@var1,@var2,@var3);

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

Change navbar color in Twitter Bootstrap

Try this too. This worked for me.

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
  background-color: #00a950;
  color: #000000;
}

How to convert any Object to String?

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3

pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

code:

ToStringBuilder.reflectionToString(yourObject)

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

Determine command line working directory when running node bin script

Here's what worked for me:

console.log(process.mainModule.filename);

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

Is there a stopwatch in Java?

Spring provides an elegant org.springframework.util.StopWatch class (spring-core module).

StopWatch stopWatch = new StopWatch();

stopWatch.start();
// Do something
stopWatch.stop();

System.out.println(stopWatch.getTotalTimeMillis());

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1

1) Make sure .Net core SDK installed on your machine. Download .NET!

2) set PATH environment variables as below Path

how to copy only the columns in a DataTable to another DataTable?

The DataTable.Clone() method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.

For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().

E.g.:

public class CoolNewTable : DataTable {
   public void FillFromReader(DbDataReader reader) {
       // We want to get the schema information (i.e. columns) from the 
       // DbDataReader and 
       // import it into *this* DataTable, NOT a new one.
       DataTable schema = reader.GetSchemaTable(); 
       //GetSchemaTable() returns a DataTable with the columns we want.

       ImportSchema(this, schema); // <--- how do we do this?
   }
}

The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.

I.e. the code for ImportSchema would be something like this:

void ImportSchema(DataTable dest, DataTable source) {
    foreach(var c in source.Columns)
        dest.Columns.Add(c);
}

or, if you're using Linq:

void ImportSchema(DataTable dest, DataTable source) {
    var cols = source.Columns.Cast<DataColumn>().ToArray();
    dest.Columns.AddRange(cols);
}

This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.

How to remove Firefox's dotted outline on BUTTONS as well as links?

The below worked for me in case of LINKS, thought of sharing - in case someone is interested.

a, a:visited, a:focus, a:active, a:hover{
    outline:0 none !important;
}

Cheers!

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

How can I install pip on Windows?

I use the cross-platform Anaconda package manager from continuum.io on Windows and it is reliable. It has virtual environment management and a fully featured shell with common utilities (e.g. conda, pip).

> conda install <package>               # access distributed binaries

> pip install <package>                 # access PyPI packages 

conda also comes with binaries for libraries with non-Python dependencies, e.g. pandas, numpy, etc. This proves useful particularly on Windows as it can be hard to correctly compile C dependencies.

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.

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I +1'd Miro's answer for the link to the header-checker site http://www.webconfs.com/http-header-check.php. It pops up an obnoxious ad every time you use it, but it is, nevertheless, very useful for verifying the presence of the Access-Control-Allow-Origin header.

I'm reading a .json file from the javascript on my web page. I found that adding the following to my .htaccess file fixed the problem when viewing my web page in IE 11 (version 11.447.14393.0):

<FilesMatch "\.(json)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I also added the following to /etc/httpd.conf (Apache's configuration file):

AllowOverride All

The header-checker site verified that the Access-Control-Allow-Origin header is now being sent (thanks, Miro!).

However, Firefox 50.0.2, Opera 41.0.2353.69, and Edge 38.14393.0.0 all fetch the file anyhow, even without the Access-Control-Allow-Origin header. (Note: they might be checking IP addresses, since the two domains I was using are both hosted on the same server, at the same IPv4 address.)

However, Chrome 54.0.2840.99 m (64-bit) ignores the Access-Control-Allow-Origin header and fails anyhow, erroneously reporting:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{mydomain}' is therefore not allowed access.

I think this has got to be some sort of "first." IE is working correctly; Chrome, Firefox, Opera and Edge are all buggy; and Chrome is the worst. Isn't that the exact opposite of the usual case?

Convert tuple to list and back

You have a tuple of tuples.
To convert every tuple to a list:

[list(i) for i in level] # list of lists

--- OR ---

map(list, level)

And after you are done editing, just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

--- OR --- (Thanks @jamylak)

tuple(itertools.imap(tuple, edited))

You can also use a numpy array:

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

For manipulating:

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

Add common prefix to all cells in Excel

Type a value in one cell (EX:B4 CELL). For temporary use this formula in other cell (once done delete it). =CONCAT(XY,B4) . click and drag till the value you need. Copy the whole column and right click paste only values (second option).

I tried and it's working as expected.

Console output in a Qt GUI app?

In your .pro add

CONFIG          += console

How to change or add theme to Android Studio?

I am using android studio 2.2.3 and I am able to change theme by following steps

  1. go to File > Setting it open an window like attach image
  2. then Editor > Colors & Fonts
  3. Select theme from Scheme dropdownlist
  4. now select Ok

enter image description here

Using Google Translate in C#

If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

One way is to setup a chroot environment. Debian has a number of tools for that, for example debootstrap

How to find if an array contains a string

I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!

You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.

There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6

Undefined reference to vtable

The GNU C++ compiler has to make a decision where to put the vtable in case you have the definition of the virtual functions of an object spread across multiple compilations units (e.g. some of the objects virtual functions definitions are in a .cpp file others in another .cpp file, and so on).

The compiler chooses to put the vtable in the same place as where the first declared virtual function is defined.

Now if you for some reason forgot to provide a definition for that first virtual function declared in the object (or mistakenly forgot to add the compiled object at linking phase), you will get this error.

As a side effect, please note that only for this particular virtual function you won't get the traditional linker error like you are missing function foo.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

This will work:

The problem may happen when you're trying to read a list with a single element as a JsonArray rather than a JsonNode or vice versa.

Since you can't know for sure if the returned list contains a single element (so the json looks like this {...}) or multiple elements (and the json looks like this [{...},{...}]) - you'll have to check in runtime the type of the element.

It should look like this:

(Note: in this code sample I'm using com.fasterxml.jackson)

String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);

// Start by checking if this is a list -> the order is important here:                      
if (rootNode instanceof ArrayNode) {
    // Read the json as a list:
    myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);
    ...
} else if (rootNode instanceof JsonNode) {
    // Read the json as a single object:
    myObjClass object = mapper.readValue(rootNode.toString(), myObjClass.class);
    ...
} else {
    ...
}

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

None of the above answers worked for me. And since there is no accepted answer, I found the following extended my image from horizontal edge to horizontal edge:

Container ( width: MediaQuery
                    .of(context)
                    .size
                    .width,
                child: 
                  Image.network(my_image_name, fit: BoxFit.fitWidth )
              )

How can I inspect the file system of a failed `docker build`?

Everytime docker successfully executes a RUN command from a Dockerfile, a new layer in the image filesystem is committed. Conveniently you can use those layers ids as images to start a new container.

Take the following Dockerfile:

FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt

and build it:

$ docker build -t so-2622957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
 ---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
 ---> Running in 4dbd01ebf27f
 ---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
 ---> Running in 74d81cb9d2b1
 ---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1

You can now start a new container from 00f017a8c2a6, 044e1532c690 and 5bd8172529c1:

$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory

$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo

$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar

of course you might want to start a shell to explore the filesystem and try out commands:

$ docker run --rm -it 044e1532c690 sh      
/ # ls -l /tmp
total 4
-rw-r--r--    1 root     root             4 Mar  9 19:09 foo.txt
/ # cat /tmp/foo.txt 
foo

When one of the Dockerfile command fails, what you need to do is to look for the id of the preceding layer and run a shell in a container created from that id:

docker run --rm -it <id_last_working_layer> bash -il

Once in the container:

  • try the command that failed, and reproduce the issue
  • then fix the command and test it
  • finally update your Dockerfile with the fixed command

If you really need to experiment in the actual layer that failed instead of working from the last working layer, see Drew's answer.

Passing Javascript variable to <a href >

If you want it to be dynamic, so that the value of the variable at the time of the click is used, do the following:

<script language="javascript" type="text/javascript">
var scrt_var = 10; 
</script>
<a href="2.html" onclick="location.href=this.href+'?key='+scrt_var;return false;">Link</a>

Of course, that's the quick and dirty solution. You should really have a script that after DOM load adds an onclick handler to all relevant <a> elements.

Python function to convert seconds into minutes, hours, and days

This will convert n seconds into d days, h hours, m minutes, and s seconds.

from datetime import datetime, timedelta

def GetTime():
    sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
    d = datetime(1,1,1) + sec

    print("DAYS:HOURS:MIN:SEC")
    print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I did a code pull but did not update project version on eclipse server/modules tab. For some reason, maven clean install did not delete old project folder from target and instead created new folder too.

Correcting project version on server fixed this issue.

Posting this just in case someone makes the same mistake.

What is the yield keyword used for in C#?

It's trying to bring in some Ruby Goodness :)
Concept: This is some sample Ruby Code that prints out each element of the array

 rubyArray = [1,2,3,4,5,6,7,8,9,10]
    rubyArray.each{|x| 
        puts x   # do whatever with x
    }

The Array's each method implementation yields control over to the caller (the 'puts x') with each element of the array neatly presented as x. The caller can then do whatever it needs to do with x.

However .Net doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.

//calling code
foreach(int i in obCustomClass.Each())
{
    Console.WriteLine(i.ToString());
}

// CustomClass implementation
private int[] data = {1,2,3,4,5,6,7,8,9,10};
public IEnumerable<int> Each()
{
   for(int iLooper=0; iLooper<data.Length; ++iLooper)
        yield return data[iLooper]; 
}

Automated Python to Java translation

Yes Jython does this, but it may or may not be what you want

How to view file diff in git before commit

If you want to see what you haven't git added yet:

git diff myfile.txt

or if you want to see already added changes

git diff --cached myfile.txt

How to use confirm using sweet alert?

I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.

How do I check if a number is a palindrome?

Try this:

print('!* To Find Palindrome Number') 

def Palindrome_Number():

            n = input('Enter Number to check for palindromee')  
            m=n 
            a = 0  

    while(m!=0):  
        a = m % 10 + a * 10    
        m = m / 10    

    if( n == a):    
        print('%d is a palindrome number' %n)
    else:
        print('%d is not a palindrome number' %n)

just call back the functions

How can I remove file extension from a website address?

just nearly the same with the first answer about, but some more advantage.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Just add up if you have a other file-extension in your sites

How do I expand the output display to see more columns of a pandas DataFrame?

Update: Pandas 0.23.4 onwards

This is not necessary, pandas autodetects the size of your terminal window if you set pd.options.display.width = 0. (For older versions see at bottom.)

pandas.set_printoptions(...) is deprecated. Instead, use pandas.set_option(optname, val), or equivalently pd.options.<opt.hierarchical.name> = val. Like:

import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

Here is the help for set_option:

set_option(pat,value) - Sets the value of the specified option

Available options:
display.[chop_threshold, colheader_justify, column_space, date_dayfirst,
         date_yearfirst, encoding, expand_frame_repr, float_format, height,
         line_width, max_columns, max_colwidth, max_info_columns, max_info_rows,
         max_rows, max_seq_items, mpl_style, multi_sparse, notebook_repr_html,
         pprint_nest_depth, precision, width]
mode.[sim_interactive, use_inf_as_null]

Parameters
----------
pat - str/regexp which should match a single option.

Note: partial matches are supported for convenience, but unless you use the
full option name (e.g. x.y.z.option_name), your code may break in future
versions if new options with similar names are introduced.

value - new value of option.

Returns
-------
None

Raises
------
KeyError if no such option exists

display.chop_threshold: [default: None] [currently: None]
: float or None
        if set to a float value, all float values smaller then the given threshold
        will be displayed as exactly 0 by repr and friends.
display.colheader_justify: [default: right] [currently: right]
: 'left'/'right'
        Controls the justification of column headers. used by DataFrameFormatter.
display.column_space: [default: 12] [currently: 12]No description available.

display.date_dayfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the day first, eg 20/01/2005
display.date_yearfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the year first, eg 2005/01/20
display.encoding: [default: UTF-8] [currently: UTF-8]
: str/unicode
        Defaults to the detected encoding of the console.
        Specifies the encoding to be used for strings returned by to_string,
        these are generally strings meant to be displayed on the console.
display.expand_frame_repr: [default: True] [currently: True]
: boolean
        Whether to print out the full DataFrame repr for wide DataFrames
        across multiple lines, `max_columns` is still respected, but the output will
        wrap-around across multiple "pages" if it's width exceeds `display.width`.
display.float_format: [default: None] [currently: None]
: callable
        The callable should accept a floating point number and return
        a string with the desired format of the number. This is used
        in some places like SeriesFormatter.
        See core.format.EngFormatter for an example.
display.height: [default: 60] [currently: 1000]
: int
        Deprecated.
        (Deprecated, use `display.height` instead.)

display.line_width: [default: 80] [currently: 1000]
: int
        Deprecated.
        (Deprecated, use `display.width` instead.)

display.max_columns: [default: 20] [currently: 500]
: int
        max_rows and max_columns are used in __repr__() methods to decide if
        to_string() or info() is used to render an object to a string.  In case
        python/IPython is running in a terminal this can be set to 0 and pandas
        will correctly auto-detect the width the terminal and swap to a smaller
        format in case all columns would not fit vertically. The IPython notebook,
        IPython qtconsole, or IDLE do not run in a terminal and hence it is not
        possible to do correct auto-detection.
        'None' value means unlimited.
display.max_colwidth: [default: 50] [currently: 50]
: int
        The maximum width in characters of a column in the repr of
        a pandas data structure. When the column overflows, a "..."
        placeholder is embedded in the output.
display.max_info_columns: [default: 100] [currently: 100]
: int
        max_info_columns is used in DataFrame.info method to decide if
        per column information will be printed.
display.max_info_rows: [default: 1690785] [currently: 1690785]
: int or None
        max_info_rows is the maximum number of rows for which a frame will
        perform a null check on its columns when repr'ing To a console.
        The default is 1,000,000 rows. So, if a DataFrame has more
        1,000,000 rows there will be no null check performed on the
        columns and thus the representation will take much less time to
        display in an interactive session. A value of None means always
        perform a null check when repr'ing.
display.max_rows: [default: 60] [currently: 500]
: int
        This sets the maximum number of rows pandas should output when printing
        out various output. For example, this value determines whether the repr()
        for a dataframe prints out fully or just a summary repr.
        'None' value means unlimited.
display.max_seq_items: [default: None] [currently: None]
: int or None

        when pretty-printing a long sequence, no more then `max_seq_items`
        will be printed. If items are ommitted, they will be denoted by the addition
        of "..." to the resulting string.

        If set to None, the number of items to be printed is unlimited.
display.mpl_style: [default: None] [currently: None]
: bool

        Setting this to 'default' will modify the rcParams used by matplotlib
        to give plots a more pleasing visual style by default.
        Setting this to None/False restores the values to their initial value.
display.multi_sparse: [default: True] [currently: True]
: boolean
        "sparsify" MultiIndex display (don't display repeated
        elements in outer levels within groups)
display.notebook_repr_html: [default: True] [currently: True]
: boolean
        When True, IPython notebook will use html representation for
        pandas objects (if it is available).
display.pprint_nest_depth: [default: 3] [currently: 3]
: int
        Controls the number of nested levels to process when pretty-printing
display.precision: [default: 7] [currently: 7]
: int
        Floating point output precision (number of significant digits). This is
        only a suggestion
display.width: [default: 80] [currently: 1000]
: int
        Width of the display in characters. In case python/IPython is running in
        a terminal this can be set to None and pandas will correctly auto-detect the
        width.
        Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a
        terminal and hence it is not possible to correctly detect the width.
mode.sim_interactive: [default: False] [currently: False]
: boolean
        Whether to simulate interactive mode for purposes of testing
mode.use_inf_as_null: [default: False] [currently: False]
: boolean
        True means treat None, NaN, INF, -INF as null (old way),
        False means None and NaN are null, but INF, -INF are not null
        (new way).
Call def:   pd.set_option(self, *args, **kwds)

EDIT: older version information, much of this has been deprecated.

As @bmu mentioned, pandas auto detects (by default) the size of the display area, a summary view will be used when an object repr does not fit on the display. You mentioned resizing the IDLE window, to no effect. If you do print df.describe().to_string() does it fit on the IDLE window?

The terminal size is determined by pandas.util.terminal.get_terminal_size() (deprecated and removed), this returns a tuple containing the (width, height) of the display. Does the output match the size of your IDLE window? There might be an issue (there was one before when running a terminal in emacs).

Note that it is possible to bypass the autodetect, pandas.set_printoptions(max_rows=200, max_columns=10) will never switch to summary view if number of rows, columns does not exceed the given limits.


The 'max_colwidth' option helps in seeing untruncated form of each column.

TruncatedColumnDisplay

Meaning of 'const' last in a function declaration of a class?

These const mean that compiler will Error if the method 'with const' changes internal data.

class A
{
public:
    A():member_()
    {
    }

    int hashGetter() const
    {
        state_ = 1;
        return member_;
    }
    int goodGetter() const
    {
        return member_;
    }
    int getter() const
    {
        //member_ = 2; // error
        return member_;
    }
    int badGetter()
    {
        return member_;
    }
private:
    mutable int state_;
    int member_;
};

The test

int main()
{
    const A a1;
    a1.badGetter(); // doesn't work
    a1.goodGetter(); // works
    a1.hashGetter(); // works

    A a2;
    a2.badGetter(); // works
    a2.goodGetter(); // works
    a2.hashGetter(); // works
}

Read this for more information

Argument of type 'X' is not assignable to parameter of type 'X'

Also adding other Scenarios where you may see these Errors

  1. First Check you compiler version, Download latest Typescript compiler to support ES6 syntaxes

  2. typescript still produces output even with typing errors this doesn't actually block development,

When you see these errors Check for Syntaxes in initialization or when Calling these methods or variables,
Check whether the parameters of the functions are of wrong data Type,you initialized as 'string' and assigning a 'boolean' or 'number'

For Example

1.

 private errors: string;
    //somewhere in code you assign a boolean value to (string)'errors'
    this.errors=true
    or 
    this.error=5

2.

 private values: Array<number>;    
    this.values.push(value);  //Argument of type 'X' is not assignable to parameter of type 'X'

The Error message here is because the Square brackets for Array Initialization is missing, It works even without it, but VS Code red alerts.

private values: Array<number> = [];    
this.values.push(value);

Note:
Remember that Javascript typecasts according to the value assigned, So typescript notifies them but the code executes even with these errors highlighted in VS Code

Ex:

 var a=2;
 typeof(a) // "number"
 var a='Ignatius';
 typeof(a) // "string"

Windows batch: call more than one command in a FOR loop?

FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)

WCF service startup error "This collection already contains an address with scheme http"

I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.

Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.

How to create a HTML Cancel button that redirects to a URL

<input class="button" type="button" onclick="window.location.replace('your_url')" value="Cancel" />

Prompt for user input in PowerShell

Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.

   Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )

   $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

If you want to debug and see the value of the password you just read, use:

   write-host $pw

MySQL Workbench Dark Theme

It's not really a programming question, but it's a quick one so let me answer that. MySQL Workbench's themes are a collection of colors for certain main parts of the application. It is planned to allow customizing them in a later version. In order to get a dark theme as one of the templates please file a feature request at http://bugs.mysql.com. But keep in mind, not every UI element is colored according to the Workbench theme, e.g. text boxes still stay white as they use the Windows standard colors.

How to escape special characters of a string with single backslashes

We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr

How to show SVG file on React Native?

After trying many ways and libraries I decided to create a new font (with Glyphs or this tutorial) and add my SVG files to it, then use "Text" component with my custom font.

Hope this helps anyone that has the same problem with SVG in react-native.

Background color for Tk in Python

Its been updated so

root.configure(background="red")

is now:

root.configure(bg="red")

How to change date format in JavaScript

Use your mydate object and call getMonth() and getFullYear()

See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp

Show only two digit after decimal

I think the best and simplest solution is (KISS):

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

css divide width 100% to 3 column

A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

#c1, #c2 {
    width: 33%;
}

#c3 {
    width: auto;
}

Jinja2 template variable if None Object set a default value

You can simply add "default none" to your variable as the form below mentioned:

{{ your_var | default('NONE', boolean=true) }}

How to remove an element slowly with jQuery?

target.fadeOut(300, function(){ $(this).remove();});

or

$('#target_id').fadeOut(300, function(){ $(this).remove();});

Duplicate: How to "fadeOut" & "remove" a div in jQuery?

How to do a GitHub pull request

I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

  • Fork the repo in github
  • Get clone url by clicking on clone repo button
  • Go to terminal and run git clone <clone url you copied earlier>
  • Make a branch for changes you're makeing git checkout -b branch-name
  • Make necessary changes
  • Commit your changes git commit
  • Push your changes to your fork on GitHub git push origin branch-name
  • Go to your fork on GitHub to see a Compare and pull request button
  • Click on it and give necessary details

How to enable CORS in flask

If you want to enable CORS for all routes, then just install flask_cors extension (pip3 install -U flask_cors) and wrap app like this: CORS(app).

That is enough to do it (I tested this with a POST request to upload an image, and it worked for me):

from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # This will enable CORS for all routes

Important note: if there is an error in your route, let us say you try to print a variable that does not exist, you will get a CORS error related message which, in fact, has nothing to do with CORS.

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

PHP to write Tab Characters inside a file?

Use \t and enclose the string with double-quotes:

$chunk = "abc\tdef\tghi";

How to reset radiobuttons in jQuery so that none is checked

I know this is old and that this is a little off topic, but supposing you wanted to uncheck only specific radio buttons in a collection:

_x000D_
_x000D_
$("#go").click(function(){_x000D_
    $("input[name='correctAnswer']").each(function(){_x000D_
      if($(this).val() !== "1"){_x000D_
        $(this).prop("checked",false);_x000D_
      }_x000D_
    });_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>_x000D_
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>_x000D_
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>_x000D_
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>_x000D_
<input type="button" id="go" value="go">
_x000D_
_x000D_
_x000D_

And if you are dealing with a radiobutton list, you can use the :checked selector to get just the one you want.

$("#go").click(function(){
  $("input[name='correctAnswer']:checked").prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
<input type="button" id="go" value="go">

Error: 'int' object is not subscriptable - Python

'int' object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

list1 = [1, 2, 3]
print(list1[0][0])

If we run the code, you will receive the same TypeError in Python3.

TypeError: 'int' object is not subscriptable

Here the index of the list is out of range. If the code was modified to:

print(list1[0])

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

1

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

int([x[age1]])

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Hence, it's better to code this way:

name = input("What's your name? ")
age = int(input('How old are you? '))
twenty_one = 21 - age
if(twenty_one < 0):
    print('Hi {0}, you are above 21 years' .format(name))
elif(twenty_one == 0):
    print('Hi {0}, you are 21 years old' .format(name))
else:
    print('Hi {0}, you will be 21 years in {1} year(s)' .format(name, twenty_one))

The output:

What's your name? Steve
How old are you? 21
Hi Steve, you are 21 years old

How can I move all the files from one folder to another using the command line?

This command will move all the files in originalfolder to destinationfolder.

MOVE c:\originalfolder\* c:\destinationfolder

(However it wont move any sub-folders to the new location.)

To lookup the instructions for the MOVE command type this in a windows command prompt:

MOVE /?

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

Fatal error: Call to undefined function mb_detect_encoding()

For fedora/centos/redhat:

yum install php-mbstring

Then restart apache

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

Difference between maven scope compile and provided for JAR packaging

If jar file is like executable spring boot jar file then scope of all dependencies must be compile to include all jar files.

But if jar file used in other packages or applications then it does not need to include all dependencies in jar file because these packages or applications can provide other dependencies themselves.

Cannot implicitly convert type 'int?' to 'int'.

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

This statement should be typed as, OrdersPerHour = (int)dbcommand.ExecuteScalar();

How to do if-else in Thymeleaf?

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

In MySQL, can I copy one row to insert into the same table?

This is an additional solution to the answer by "Grim..." There have been some comments on it having a primary key as null. Some comments about it not working. And some comments on solutions. None of the solutions worked for us. We have MariaDB with the InnoDB table.

We could not set the primary key to allow null. Using 0 instead of NULL led to duplicate value error for the primary key. SET SQL_SAFE_UPDATES = 0; Did not work either.

The solution from "Grim..." did work IF we changed our PRIMARY KEY to UNIQUE instead

Remove Android App Title Bar

Simple way
getSupportActionBar().hide();

Kotlin: supportActionBar?.hide()

Is a LINQ statement faster than a 'foreach' loop?

LINQ is slower now, but it might get faster at some point. The good thing about LINQ is that you don't have to care about how it works. If a new method is thought up that's incredibly fast, the people at Microsoft can implement it without even telling you and your code would be a lot faster.

More importantly though, LINQ is just much easier to read. That should be enough reason.

Adding an item to an associative array

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

echo $data[$category]["test"];

which should print $question

1052: Column 'id' in field list is ambiguous

In your SELECT statement you need to preface your id with the table you want to choose it from.

SELECT tbl_names.id, name, section 
FROM tbl_names
INNER JOIN tbl_section 
   ON tbl_names.id = tbl_section.id

OR

SELECT tbl_section.id, name, section 
FROM tbl_names
INNER JOIN tbl_section 
   ON tbl_names.id = tbl_section.id

remove None value from a list without removing the 0 value

Using list comprehension this can be done as follows:

l = [i for i in my_list if i is not None]

The value of l is:

[0, 23, 234, 89, 0, 35, 9]

How can I throw a general exception in Java?

It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

jQuery Validate Required Select

<select class="design" id="sel" name="subject">
   <option value="0">- Please Select -</option>
   <option value="1"> Example1 </option>
   <option value="2"> Example2 </option>
   <option value="3"> Example3 </option>
   <option value="4"> Example4 </option>
</select>
<label class="error" id="select_error" style="color:#FC2727">
   <b> Warning : You have to Select One Item.</b>
</label>
<input type="submit" name="sub" value="Gönder" class="">

JQuery :

jQuery(function() {  
    jQuery('.error').hide(); // Hide Warning Label. 
    jQuery("input[name=sub]").on("click", function() {
        var returnvalue;
        if(jQuery("select[name=subject]").val() == 0) {
            jQuery("label#select_error").show(); // show Warning 
            jQuery("select#sel").focus();  // Focus the select box      
            returnvalue=false;   
        }
        return returnvalue;
    });
});  // you can change jQuery with $

How do you Sort a DataTable given column and direction?

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

AngularJS- Login and Authentication in each route and controller

I feel like this way is easiest, but perhaps it's just personal preference.

When you specify your login route (and any other anonymous routes; ex: /register, /logout, /refreshToken, etc.), add:

allowAnonymous: true

So, something like this:

$stateProvider.state('login', {
    url: '/login',
    allowAnonymous: true, //if you move this, don't forget to update
                          //variable path in the force-page check.
    views: {
        root: {
            templateUrl: "app/auth/login/login.html",
            controller: 'LoginCtrl'
        }
    }
    //Any other config
}

You don't ever need to specify "allowAnonymous: false", if not present, it is assumed false, in the check. In an app where most URLs are force authenticated, this is less work. And safer; if you forget to add it to a new URL, the worst that can happen is an anonymous URL is protected. If you do it the other way, specifying "requireAuthentication: true", and you forget to add it to a URL, you are leaking a sensitive page to the public.

Then run this wherever you feel fits your code design best.

//I put it right after the main app module config. I.e. This thing:
angular.module('app', [ /* your dependencies*/ ])
       .config(function (/* you injections */) { /* your config */ })

//Make sure there's no ';' ending the previous line. We're chaining. (or just use a variable)
//
//Then force the logon page
.run(function ($rootScope, $state, $location, User /* My custom session obj */) {
    $rootScope.$on('$stateChangeStart', function(event, newState) {
        if (!User.authenticated && newState.allowAnonymous != true) {
            //Don't use: $state.go('login');
            //Apparently you can't set the $state while in a $state event.
            //It doesn't work properly. So we use the other way.
            $location.path("/login");
        }
    });
});

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

Get a list of URLs from a site

The best on I have found is http://www.auditmypc.com/xml-sitemap.asp which uses Java, and has no limit on pages, and even lets you export results as a raw URL list.

It also uses sessions, so if you are using a CMS, make sure you are logged out before you run the crawl.

How to return a html page from a restful controller in spring boot?

You get only the name because you return only the name return "login";. It's @RestController and this controller returns data rather than a view; because of this, you get only content that you return from method.

If you want to show view with this name you need to use Spring MVC, see this example.

How to create a database from shell command?

You mean while the mysql environment?

create database testdb;

Or directly from command line:

mysql -u root -e "create database testdb"; 

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"