Programs & Examples On #Findinfiles

Assigning default value while creating migration file

You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...

def change
    change_column :widgets, :colour, :string, default: 'red'
end

Check if a user has scrolled to the bottom

i used this test to detect the scroll reached the bottom: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight

Why is pydot unable to find GraphViz's executables in Windows 8?

I found a manual solution: sudo apt-get install graphviz

graph.write('test.dot') dot -Tps test.dot -o outfile.ps

You can the files here: https://github.com/jecs89/LearningEveryDay/tree/master/GP

How to update/refresh specific item in RecyclerView

Add the changed text to your model data list

mdata.get(position).setSuborderStatusId("5");
mdata.get(position).setSuborderStatus("cancelled");
notifyItemChanged(position);

Linux delete file with size 0

On Linux, the stat(1) command is useful when you don't need find(1):

(( $(stat -c %s "$filename") )) || rm "$filename"

The stat command here allows us just to get the file size, that's the -c %s (see the man pages for other formats). I am running the stat program and capturing its output, that's the $( ). This output is seen numerically, that's the outer (( )). If zero is given for the size, that is FALSE, so the second part of the OR is executed. Non-zero (non-empty file) will be TRUE, so the rm will not be executed.

How to get current memory usage in android?

Here is a way to calculate memory usage of currently running application:

public static long getUsedMemorySize() {

    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return usedSize;

}

Turn off constraints temporarily (MS SQL)

You can actually disable all database constraints in a single SQL command and the re-enable them calling another single command. See:

I am currently working with SQL Server 2005 but I am almost sure that this approach worked with SQL 2000 as well

Copy Notepad++ text with formatting?

For those who do not see Plugins->NPPExport,

Download Plugin Manager from this. Extract contents and place under C/ProgramFile/NP++ installation, plugins & updater folder. Restart NP++. You should be able to see Plugins->Plugin Manager then. You can download any plugin, including NPPExport and install it to see the Copy command.

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

How do I convert csv file to rdd

For spark scala I typically use when I can't use the spark csv packages...

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val rawdata = sc.textFile("hdfs://example.host:8020/user/example/example.csv")
val header = rawdata.first()
val tbldata = rawdata.filter(_(0) != header(0))

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

Change NULL values in Datetime format to empty string

Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name

What is the difference between prefix and postfix operators?

It has to do with the way the post-increment operator works. It returns the value of i and then increments the value.

LaTeX source code listing like in professional books

For R code I use

\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}

And it looks exactly like this

enter image description here

How to get current foreground activity context in android?

For backwards compatibility:

ComponentName cn;
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
} else {
    //noinspection deprecation
    cn = am.getRunningTasks(1).get(0).topActivity;
}

Git push error: "origin does not appear to be a git repository"

If you are on HTTPS do this-

git remote add origin URL_TO_YOUR_REPO

Does Django scale?

I have been using Django for over a year now, and am very impressed with how it manages to combine modularity, scalability and speed of development. Like with any technology, it comes with a learning curve. However, this learning curve is made a lot less steep by the excellent documentation from the Django community. Django has been able to handle everything I have thrown at it really well. It looks like it will be able to scale well into the future.

BidRodeo Penny Auctions is a moderately sized Django powered website. It is a very dynamic website and does handle a good number of page views a day.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

For Ubuntu 18, after checking log file mentioned while install

Results logged to /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

with

less /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

I noticed that make is not found. So installed make by

sudo apt-get install make

everything worked.

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

C++: what regex library should I use?

Noone here said anything about the one that comes with C++0x. If you are using a compiler and the STL that supports C++0x you could just use that instead of having another lib in your project.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

Word-wrap in an HTML table

Change your code

word-wrap: break-word;

to

word-break:break-all;

Example

_x000D_
_x000D_
<table style="width: 100%;">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="word-break:break-all;">longtextwithoutspacelongtextwithoutspace Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content</div>_x000D_
    </td>_x000D_
    <td><span style="display: inline;">Short Content</span>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

What is the color code for transparency in CSS?

Or you could just put

background-color: rgba(0,0,0,0.0);

That should solve your problem.

Listing all extras of an Intent

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    tv = new TextView(this);
    tv.setText("Extras: \n\r");

    setContentView(tv);

    StringBuilder str = new StringBuilder();
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        Set<String> keys = bundle.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            str.append(key);
            str.append(":");
            str.append(bundle.get(key));
            str.append("\n\r");
        }
        tv.setText(str.toString());
    }
}

Convert MySQL to SQlite

I like the SQLite2009 Pro Enterprise Manager suggested by Jfly. However:

  • The MySQL datatype INT is not converted to SQlite datatype INTEGER (works with DBeaver )

  • It does not import foreign key constaints from MySQL (I could not find any tool that supports the transfer of foreign key constraints from MySQL to SQlite.)

Understanding implicit in Scala

WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)
  }

  def printText(text: Text): Unit = {
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")
}

Print commit message of a given commit in git

This will give you a very compact list of all messages for any specified time.

git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B > CHANGELOG.TXT

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

How is "mvn clean install" different from "mvn install"?

Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.

What is the best IDE for C Development / Why use Emacs over an IDE?

How come nobody mentions Bloodshed Devc++? Havent used it in a while, but i learnt c/c++ on it. very similar to MS Visual c++.

How does one set up the Visual Studio Code compiler/debugger to GCC?

There is a much easier way to compile and run C code using GCC, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your C code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:

"code-runner.executorMap": {
    "c": "gcc $fullFileName && ./a.out"
}

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I see that this question is already old but still...

We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.

I hope it helps :)

Fast ceiling of an integer division in C / C++

Sparky's answer is one standard way to solve this problem, but as I also wrote in my comment, you run the risk of overflows. This can be solved by using a wider type, but what if you want to divide long longs?

Nathan Ernst's answer provides one solution, but it involves a function call, a variable declaration and a conditional, which makes it no shorter than the OPs code and probably even slower, because it is harder to optimize.

My solution is this:

q = (x % y) ? x / y + 1 : x / y;

It will be slightly faster than the OPs code, because the modulo and the division is performed using the same instruction on the processor, because the compiler can see that they are equivalent. At least gcc 4.4.1 performs this optimization with -O2 flag on x86.

In theory the compiler might inline the function call in Nathan Ernst's code and emit the same thing, but gcc didn't do that when I tested it. This might be because it would tie the compiled code to a single version of the standard library.

As a final note, none of this matters on a modern machine, except if you are in an extremely tight loop and all your data is in registers or the L1-cache. Otherwise all of these solutions will be equally fast, except for possibly Nathan Ernst's, which might be significantly slower if the function has to be fetched from main memory.

Save text file UTF-8 encoded with VBA

I found the answer on the web:

Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk

Certainly not as I expected...

How to pass command line argument to gnuplot?

You can pass arguments to a gnuplot script since version 5.0, with the flag -c. These arguments are accessed through the variables ARG0 to ARG9, ARG0 being the script, and ARG1 to ARG9 string variables. The number of arguments is given by ARGC.

For example, the following script ("script.gp")

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

can be called as:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

or within gnuplot as

gnuplot> call 'script.gp' one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

In gnuplot 4.6.6 and earlier, there exists a call mechanism with a different (now deprecated) syntax. The arguments are accessed through $#, $0,...,$9. For example, the same script above looks like:

#!/usr/bin/gnuplot --persist

THIRD="$2"
print "first argument     : ", "$0"
print "second argument    : ", "$1"
print "third argument     : ", THIRD
print "number of arguments: ", "$#"

and it is called within gnuplot as (remember, version <4.6.6)

gnuplot> call 'script4.gp' one two three four five
first argument     : one
second argument    : two
third argument     : three
number of arguments: 5

Notice there is no variable for the script name, so $0 is the first argument, and the variables are called within quotes. There is no way to use this directly from the command line, only through tricks as the one suggested by @con-fu-se.

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Commenting here as this seems to be the most popular answer on the subject for searching for files whilst excluding certain directories in powershell.

To avoid issues with post filtering of results (i.e. avoiding permission issues etc), I only needed to filter out top level directories and that is all this example is based on, so whilst this example doesn't filter child directory names, it could very easily be made recursive to support this, if you were so inclined.

Quick breakdown of how the snippet works

$folders << Uses Get-Childitem to query the file system and perform folder exclusion

$file << The pattern of the file I am looking for

foreach << Iterates the $folders variable performing a recursive search using the Get-Childitem command

$folders = Get-ChildItem -Path C:\ -Directory -Name -Exclude Folder1,"Folder 2"
$file = "*filenametosearchfor*.extension"

foreach ($folder in $folders) {
   Get-Childitem -Path "C:/$folder" -Recurse -Filter $file | ForEach-Object { Write-Output $_.FullName }
}

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

Static image src in Vue.js template

declare new variable that the value contain the path of image

const imgLink = require('../../assets/your-image.png')

then call the variable

export default {
    name: 'onepage',
    data(){
        return{
            img: imgLink,
        }
    }
}

bind that on html, this the example:

<a href="#"><img v-bind:src="img" alt="" class="logo"></a>

hope it will help

How can I replace newline or \r\n with <br/>?

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Empty set literal?

There are few ways to create empty Set in Python :

  1. Using set() method
    This is the built-in method in python that creates Empty set in that variable.
  2. Using clear() method (creative Engineer Technique LOL)
    See this Example:

    sets={"Hi","How","are","You","All"}
    type(sets)  (This Line Output : set)
    sets.clear()
    print(sets)  (This Line Output : {})
    type(sets)  (This Line Output : set)

So, This are 2 ways to create empty Set.

Is there a "do ... while" loop in Ruby?

Here's another one:

people = []
1.times do
  info = gets.chomp
  unless info.empty? 
    people += [Person.new(info)]
    redo
  end
end

Custom Python list sorting

As a side note, here is a better alternative to implement the same sorting:

alist.sort(key=lambda x: x.foo)

Or alternatively:

import operator
alist.sort(key=operator.attrgetter('foo'))

Check out the Sorting How To, it is very useful.

shift a std_logic_vector of n bit to right or left

add_Pbl <= to_stdlogicvector(to_bitvector(dato_cu(25 downto 2)) sll 1);
add_Pbl is a std_logic_vector of 24 bit
dato_cu is a std_logic_vector of 32 bit

First, you need to convert the std_logic_vector with to_bitvector() function because sll statement works with logic 1 and 0 bits.

What is the difference between a schema and a table and a database?

Schemas contains Databases.

Databases are part of a Schema.

So, schemas > databases.

Schemas contains views, stored procedure(s), database(s), trigger(s) etc.

ReferenceError: fetch is not defined

If it has to be accessible with a global scope

global.fetch = require("node-fetch");

This is a quick dirty fix, please try to eliminate this usage in production code.

CSS disable hover effect

Add the following to add hover effect on disabled button:

.buttonDisabled:hover
  {
    /*your code goes here*/     
  }

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

After trying out ngGrid, ngTable, trNgGrid and Smart Table, I have come to the conclusion that Smart Table is by far the best implementation AngularJS-wise and Bootstrap-wise. It is built exactly the same way as you would build your own, naive table using standard angular. On top of that, they have added a few directives that help you do sorting, filtering etc. Their approach also makes it quite simple to extend yourself. The fact that they use the regular html tags for tables and the standard ng-repeat for the rows and standard bootstrap for formatting makes this my clear winner.

Their JS code depends on angular and your html can depend on bootstrap if you want to. The JS code is 4 kb in total and you can even easily pick stuff out of there if you want to reach an even smaller footprint.

Where the other grids will give you claustrophobia in different areas, Smart Table just feels open and to the point.

If you rely heavily on inline editing and other advanced features, you might get up and running quicker with ngTable for instance. However, you are free to add such features quite easily in Smart Table.

Don't miss Smart Table!!!

I have no relation to Smart Table, except from using it myself.

Binary search (bisection) in Python

This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):

Sorted Lists

  • O( n log n) to initially create the list (if it's unsorted data. O(n), if it's sorted )
  • O( log n) lookups (this is the binary search part)
  • O( n ) insert / delete (might be O(1) or O(log n) average case, depending on your pattern)

Whereas with a set(), you're incurring

  • O(n) to create
  • O(1) lookup
  • O(1) insert / delete

The thing a sorted list really gets you are "next", "previous", and "ranges" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index. If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall. set() incurs very little additional overhead in python.

.trim() in JavaScript not working in IE

var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

How to make html table vertically scrollable

The best way to do this is strictly separate your table into two different tables - header and body:

<div class="header">
  <table><tr><!-- th here --></tr></table>
</div>

<div class="body">
  <table><tr><!-- td here --></tr></table>
</div>

.body {
  height: 100px;
  overflow: auto
}

If your table has a big width (more than screen width), then you have to add scroll events for horizontal scrolling header and body synchroniously.

You should never touch table tags (table, tbody, thead, tfoot, tr) with CSS properties display and overflow. Dealing with DIV wrappers is much more preferable.

Illegal access: this web application instance has been stopped already

In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.

So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.

Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).

Not able to pip install pickle in python 3.6

$ pip install pickle5
import pickle5 as pickle

pb = pickle.PickleBuffer(b"foo")
data = pickle.dumps(pb, protocol=5)
assert pickle.loads(data) == b"foo"

This package backports all features and APIs added in the pickle module in Python 3.8.3, including the PEP 574 additions. It should work with Python 3.5, 3.6 and 3.7.

Basic usage is similar to the pickle module, except that the module to be imported is pickle5:

https://pypi.org/project/pickle5/

Radio buttons not checked in jQuery

if ( ! $("input").is(':checked') )

Doesn't work?

You might also try iterating over the elements like so:

var iz_checked = true;
$('input').each(function(){
   iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

React-Router open Link in new tab

In React Router version 5.0.1 and above, you can use:

<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />

gulp command not found - error after installing gulp

I had v0.12.3 of Nodejs on Win7 x64 and ran into similar issues when I tried installing gulp. This worked for me:

  1. Uninstalled Nodejs
  2. Installed Nodejs v0.10.29
  3. npm install -g npm
  4. npm install -g gulp

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

How can I be notified when an element is added to the page?

There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.

https://github.com/uzairfarooq/arrive/

Environment variable to control java.io.tmpdir?

Use

$ java -XshowSettings
Property settings:
    java.home = /home/nisar/javadev/javasuncom/jdk1.7.0_17/jre
    java.io.tmpdir = /tmp

Pod install is staying on "Setting up CocoaPods Master repo"

I Faced same problem but it work for.I executed the Pod Install Command Before 3 Hour ago after that its updated what i want. You just need to Keep tracking the "Activity Monitor" You can see their "git remote https" or "Git" in disk tab. It will download around 330 Mb then it shows 1 GB and After some minutes it will starts installing. No need to Execute extra command.

Note : during downloading your MAC need to in continuously Active mode.If your system goes in sleep mode then CPU stop the process and you will get a error Like Add manually.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

If you're like me running in a restricted environment without administrative privileges, that means your only way to get node up and running is to grab the executable (node.exe) without using the installer. You also cannot change the path variable which makes it that much more challenging.

Here's what I did (for Windows)

  1. Throw node.exe into its own folder (Downloaded the node.exe stand-alone )
  2. Grab an NPM release zip off of github: https://github.com/npm/npm/releases
  3. Create a folder named: node_modules in the node.exe folder
  4. Extract the NPM zip into the node_modules folder
  5. Make sure the top most folder is named npm (remove any of the versioning on the npm folder name ie: npm-2.12.1 --> npm)
  6. Copy npm.cmd out of the npm/bin folder into the top most folder with node.exe
  7. Open a command prompt to the node.exe directory (shift right-click "Open command window here")
  8. Now you will be able to run your npm installers via: npm install -g express

Running the installers through npm will now auto install packages where they need to be located (node_modules and the root)

Don't forget you will not be able to set the path variable if you do not have proper permissions. So your best route is to open a command prompt in the node.exe directory (shift right-click "Open command window here")

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

urllib2.HTTPError: HTTP Error 403: Forbidden

This will work in Python 3

import urllib.request

user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,} 

request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Look in HTML output for actual client ID

You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.

Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.

Memorize NamingContainer components and always give them a fixed ID

If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.

<h:form id="form">
    <p:commandLink update="result"> <!-- OK! -->
    <h:panelGroup id="result" />
</h:form>

If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.

<h:form id="form">
    <p:commandLink update="result"> <!-- FAIL! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- OK! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- FAIL! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>
<h:form id="form">
    <p:commandLink update=":otherform:result"> <!-- OK! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>

NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.

If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.

Solving your problem

So in your case of:

<p:tabView id="tabs"><!-- This is a NamingContainer -->
    <p:tab id="search"><!-- This is NOT a NamingContainer -->
        <h:form id="insTable"><!-- This is a NamingContainer -->
            <p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
                <h:panelGrid id="display">

The generated HTML output of <h:panelGrid id="display"> looks like this:

<table id="tabs:insTable:display">

You need to take exactly that id as client ID and then prefix with : for usage in update:

<p:commandLink update=":tabs:insTable:display">

Referencing outside include/tagfile/composite

If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:

<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">

Or, if this command link is inside a composite component and the target is outside it:

<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">

Or, if both the command link and target are inside same composite component:

<p:commandLink update=":#{cc.clientId}:display">

See also Get id of parent naming container in template for in render / update attribute

How does it work under the covers

This all is specified as "search expression" in the UIComponent#findComponent() javadoc:

A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:

  • Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
    • If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
    • Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
    • Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
    • Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
  • The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
    • If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
    • If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.

Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".

"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.

Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).

Never use prependId="false"

If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.

Referencing specific iteration round of iterating components

It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:

<h:form id="form">
    <ui:repeat id="list" value="#{['one','two','three']}" var="item">
        <h:outputText id="item" value="#{item}" /><br/>
    </ui:repeat>

    <h:commandButton value="Update second item">
        <f:ajax render=":form:list:1:item" />
    </h:commandButton>
</h:form>

However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).

This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.

When using PrimeFaces, consider Search Expressions or Selectors

PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:

  • @this: current component
  • @form: parent UIForm
  • @all: entire document
  • @none: nothing

PrimeFaces has enhanced this with new keywords and composite expression support:

  • @parent: parent component
  • @namingcontainer: parent UINamingContainer
  • @widgetVar(name): component as identified by given widgetVar

You can also mix those keywords in composite expressions such as @form:@parent, @this:@parent:@parent, etc.

PrimeFaces Selectors (PFS) as in @(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

How to setup Main class in manifest file in jar produced by NetBeans project

It is simple.

  • Right click on the project
  • Go to Properties
  • Go to Run in Categories tree
  • Set the Main Class in the right side panel.
  • Build the project

Thats it. Hope this helps.

Python script header


I'd suggest 3 things in the beginning of your script:

First, as already being said use environment:

#!/usr/bin/env python

Second, set your encoding:

# -*- coding: utf-8 -*-

Third, set some doc string:

"""This is a awesome
    python script!"""

And for sure I would use " " (4 spaces) for ident.
Final header will look like:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is a awesome
        python script!"""


Best wishes and happy coding.

C++ Object Instantiation

Treat heap as a very important real estate and use it very judiciously. The basic thumb rule is to use stack whenever possible and use heap whenever there is no other way. By allocating the objects on stack you can get many benefits such as:

(1). You need not have to worry about stack unwinding in case of exceptions

(2). You need not worry about memory fragmentation caused by the allocating more space than necessary by your heap manager.

Why is String immutable in Java?

String is given as immutable by Sun micro systems,because string can used to store as key in map collection. StringBuffer is mutable .That is the reason,It cannot be used as key in map object

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

You can't use a condition to change the structure of your query, just the data involved. You could do this:

update table set
    columnx = (case when condition then 25 else columnx end),
    columny = (case when condition then columny else 25 end)

This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.

The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.

How to handle checkboxes in ASP.NET MVC forms?

In case you're wondering WHY they put a hidden field in with the same name as the checkbox the reason is as follows :

Comment from the sourcecode MVCBetaSource\MVC\src\MvcFutures\Mvc\ButtonsAndLinkExtensions.cs

Render an additional <input type="hidden".../> for checkboxes. This addresses scenarios where unchecked checkboxes are not sent in the request. Sending a hidden input makes it possible to know that the checkbox was present on the page when the request was submitted.

I guess behind the scenes they need to know this for binding to parameters on the controller action methods. You could then have a tri-state boolean I suppose (bound to a nullable bool parameter). I've not tried it but I'm hoping thats what they did.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

How to select distinct rows in a datatable and store into an array

You can use like that:

data is DataTable

data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");  

but performance will be down. try to use below code:

data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();  

For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html

How to comment multiple lines in Visual Studio Code?

Shift+Alt+A

Here you can find all the keyboard shortcuts.

All VSCode Shortcuts

PS: I prefer Ctrl+Shift+/ for toggling block comments because Ctrl+/ is shortcut for toggling line comments so it's naturally easier to remember. To do so, just click on the settings icon in the bottom left of the screen and click 'Keyboard Shortcuts' and find "toggle block...". Then click and enter your desired combination.

Using WGET to run a cronjob PHP

You could tell wget to not download the contents in a couple of different ways:

wget --spider http://www.example.com/cronit.php

which will just perform a HEAD request but probably do what you want

wget -O /dev/null http://www.example.com/cronit.php

which will save the output to /dev/null (a black hole)

You might want to look at wget's -q switch too which prevents it from creating output

I think that the best option would probably be:

wget -q --spider http://www.example.com/cronit.php

that's unless you have some special logic checking the HTTP method used to request the page

Copy text from nano editor to shell

Relatively straightforward solution:

  1. From the first character you want to copy, hold Shift down and go all the way to the end.

  2. Press Ctrl+K, which cuts the text from the file.

  3. Press Ctrl+X, and then N to not save any changes.

  4. Paste the cut text anywhere you want.

Alternatively, if your text fits into the screen, you can simply use mouse to select and it automatically copies it to clipboard.

SQL query: Delete all records from the table except latest N?

You cannot delete the records that way, the main issue being that you cannot use a subquery to specify the value of a LIMIT clause.

This works (tested in MySQL 5.0.67):

DELETE FROM `table`
WHERE id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `table`
    ORDER BY id DESC
    LIMIT 42 -- keep this many records
  ) foo
);

The intermediate subquery is required. Without it we'd run into two errors:

  1. SQL Error (1093): You can't specify target table 'table' for update in FROM clause - MySQL doesn't allow you to refer to the table you are deleting from within a direct subquery.
  2. SQL Error (1235): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' - You can't use the LIMIT clause within a direct subquery of a NOT IN operator.

Fortunately, using an intermediate subquery allows us to bypass both of these limitations.


Nicole has pointed out this query can be optimised significantly for certain use cases (such as this one). I recommend reading that answer as well to see if it fits yours.

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

Compare two date formats in javascript/jquery

try with new Date(obj).getTime()

if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
    alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
    alert(fit_end_time + " is greater."); // your code
}
else
{
    alert("both are same!"); // your code
}

Doctrine findBy 'does not equal'

There is no built-in method that allows what you intend to do.

You have to add a method to your repository, like this:

public function getWhatYouWant()
{
    $qb = $this->createQueryBuilder('u');
    $qb->where('u.id != :identifier')
       ->setParameter('identifier', 1);

    return $qb->getQuery()
          ->getResult();
}

Hope this helps.

C# event with custom arguments

EventHandler receives EventArgs as a parameter. To resolve your problem, you can build your own MyEventArgs.

 public enum MyEvents
 { 
    Event1 
 }

 public class MyEventArgs : EventArgs
 {
    public MyEvents MyEvent { get; set; }
 }

 public static event EventHandler<MyEventArgs> EventTriggered; 

 public static void Trigger(MyEvents ev) 
 { 
     if (EventTriggered != null) 
     {
         EventTriggered(null, new MyEventArgs { MyEvent = ev });
     } 
 } 

How to create a new database after initally installing oracle database 11g Express Edition?

When you installed XE.... it automatically created a database called "XE". You can use your login "system" and password that you set to login.

Key info

server: (you defined)
port: 1521
database: XE
username: system
password: (you defined)

Also Oracle is being difficult and not telling you easily create another database. You have to use SQL or another tool to create more database besides "XE".

How can I make a multipart/form-data POST request using Java?

My code for sending files to server using post in multipart. Make use of multivalue map while making request for sending form data

  LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("FILE", new FileSystemResource(file));
        map.add("APPLICATION_ID", Number);

   httpService.post( map,headers);

At receiver end use

@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public ApiResponse AreaCsv(@RequestParam("FILE") MultipartFile file,@RequestHeader("clientId") ){
//code
}

JavaScript: How to pass object by value?

Using the spread operator like obj2 = { ...obj1 } Will have same values but different references

Function is not defined - uncaught referenceerror

How about removing the onclick attribute and adding an ID:

<input type="image" src="btn.png" alt="" id="img-clck" />

And your script:

$(document).ready(function(){
    function codeAddress() {
        var address = document.getElementById("formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
            }
        });
    }
    $("#img-clck").click(codeAddress);
});

This way if you need to change the function name or whatever no need to touch the html.

Search code inside a Github project

Update January 2013: a brand new search has arrived!, based on elasticsearch.org:

A search for stat within the ruby repo will be expressed as stat repo:ruby/ruby, and will now just workTM.
(the repo name is not case sensitive: test repo:wordpress/wordpress returns the same as test repo:Wordpress/Wordpress)

enter image description here

Will give:

enter image description here

And you have many other examples of search, based on followers, or on forks, or...


Update July 2012 (old days of Lucene search and poor code indexing, combined with broken GUI, kept here for archive):

The search (based on SolrQuerySyntax) is now more permissive and the dreaded "Invalid search query. Try quoting it." is gone when using the default search selector "Everything":)

(I suppose we can all than Tim Pease, which had in one of his objectives "hacking on improved search experiences for all GitHub properties", and I did mention this Stack Overflow question at the time ;) )

Here is an illustration of a grep within the ruby code: it will looks for repos and users, but also for what I wanted to search in the first place: the code!

GitHub more permissive search results


Initial answer and illustration of the former issue (Sept. 2012 => March 2012)

You can use the advanced search GitHub form:

  • Choose Code, Repositories or Users from the drop-down and
  • use the corresponding prefixes listed for that search type.

For instance, Use the repo:username/repo-name directive to limit the search to a code repository.
The initial "Advanced Search" page includes the section:

Code Search:

The Code search will look through all of the code publicly hosted on GitHub. You can also filter by :

  • the language language:
  • the repository name (including the username) repo:
  • the file path path:

So if you select the "Code" search selector, then your query grepping for a text within a repo will work:

Good Search selector


What is incredibly unhelpful from GitHub is that:

  • if you forget to put the right search selector (here "Code"), you will get an error message:
    "Invalid search query. Try quoting it."

Wrong selector for the code filer

  • the error message doesn't help you at all.
    No amount of "quoting it" will get you out of this error.

  • once you get that error message, you don't get the sections reminding you of the right association between the search selectors ("Repositories", "Users" or "Language") and the (right) search filters (here "repo:").
    Any further attempt you do won't display those associations (selectors-filters) back. Only the error message you see above...
    The only way to get back those arrays is by clicking the "Advance Search" icon:

Advance Search Icon on GitHub

  • the "Everything" search selector, which is the default, is actually the wrong one for all of the search filters! Except "language:"...
    (You could imagine/assume that "Everything" would help you to pick whatever search selector actually works with the search filter "repo:", but nope. That would be too easy)

  • you cannot specify the search selector you want through the "Advance Search" field alone!
    (but you can for "language:", even though "Search Language" is another combo box just below the "Search for" 'type' one...)

Wrong search selector


So, the user's experience usually is as follows:

  • you click "Advanced Search", glance over those sections of filters, and notice one you want to use: "repo:"
  • you make a first advanced search "repo:jruby/jruby stat", but with the default Search selector "Everything"
    => FAIL! (and the arrays displaying the association "Selectors-Filters" is gone)
  • you notice that "Search for" selector thingy, select the first choice "Repositories" ("Dah! I want to search within repositories...")
    => FAIL!
  • dejected, you select the next choice of selectors (here, "Users"), without even looking at said selector, just to give it one more try...
    => FAIL!
  • "Screw this, GitHub search is broken! I'm outta here!"
    ...
    (GitHub advanced search is actually not broken. Only their GUI is...)

So, to recap, if you want to "grep for something inside a Github project's code", as the OP Ben Humphreys, don't forget to select the "Code" search selector...

No restricted globals

/* eslint no-restricted-globals:0 */

is another alternate approach

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

How do you stop MySQL on a Mac OS install?

On my mac osx yosemite 10.10. This command worked:

sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysql.plist

You can find your mysql file in folder /Library/LaunchDaemons/ to run

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

Datetime current year and month in Python

You can write the accepted answer as a one-liner using date.replace:

datem = datetime.today().replace(day=1)

PHP Notice: Undefined offset: 1 with array when reading data

Update in 2020 in Php7:

there is a better way to do this using the Null coalescing operator by just doing the following:

$data[$parts[0]] = $parts[1] ?? null;

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

Fastest way to flatten / un-flatten nested JSON objects

3 ½ Years later...

For my own project I wanted to flatten JSON objects in mongoDB dot notation and came up with a simple solution:

/**
 * Recursively flattens a JSON object using dot notation.
 *
 * NOTE: input must be an object as described by JSON spec. Arbitrary
 * JS objects (e.g. {a: () => 42}) may result in unexpected output.
 * MOREOVER, it removes keys with empty objects/arrays as value (see
 * examples bellow).
 *
 * @example
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
 * flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
 * flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
 * // return {a: 1}
 * flatten({a: 1, b: [], c: {}})
 *
 * @param obj item to be flattened
 * @param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
 * @param {Object} [current={}] result of flatten during the recursion
 *
 * @see https://docs.mongodb.com/manual/core/document/#dot-notation
 */
function flatten (obj, prefix, current) {
  prefix = prefix || []
  current = current || {}

  // Remember kids, null is also an object!
  if (typeof (obj) === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
      this.flatten(obj[key], prefix.concat(key), current)
    })
  } else {
    current[prefix.join('.')] = obj
  }

  return current
}

Features and/or caveats

  • It only accepts JSON objects. So if you pass something like {a: () => {}} you might not get what you wanted!
  • It removes empty arrays and objects. So this {a: {}, b: []} is flattened to {}.

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

How do you allow spaces to be entered using scanf?

People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).

Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.

Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:

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

/* Maximum name size + 1. */

#define MAX_NAME_SZ 256

int main(int argC, char *argV[]) {
    /* Allocate memory and check if okay. */

    char *name = malloc(MAX_NAME_SZ);
    if (name == NULL) {
        printf("No memory\n");
        return 1;
    }

    /* Ask user for name. */

    printf("What is your name? ");

    /* Get the name, with size limit. */

    fgets(name, MAX_NAME_SZ, stdin);

    /* Remove trailing newline, if there. */

    if ((strlen(name) > 0) && (name[strlen (name) - 1] == '\n'))
        name[strlen (name) - 1] = '\0';

    /* Say hello. */

    printf("Hello %s. Nice to meet you.\n", name);

    /* Free memory and exit. */

    free (name);
    return 0;
}

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

How to write text in ipython notebook?

Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:

Esc then m then Enter so that you gain focus again and can start typing.

Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.

Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.

You can then move on to your next cells. :)

ConfigurationManager.AppSettings - How to modify and save?

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

How can I get phone serial number (IMEI)

try this

 final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

  String deviceid = tm.getDeviceId();

Listen to changes within a DIV and act accordingly

http://api.jquery.com/change/

change does only work on input form elements.

you could just trigger a function after your XML / XSL transformation or make a listener:

var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

What do we mean by org.hibernate.exception.SQLGrammarException?

Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).

and in my words there is a kind of Grammar mistake inside of your hibernate.cfg.xml configuration file,

it happens when you write wrong schema defination property name inside, like below example:

<property name="hibernate.connection.hbm2ddl.auto">create</property>

which supposed to be like:

<property name="hibernate.hbm2ddl.auto">create</property>

Jquery click not working with ipad

We have a similar problem: the click event on a button doesn't work, as long as the user has not scrolled the page. The bug appears only on iOS.

We solved it by scrolling the page a little bit:

$('#modal-window').animate({scrollTop:$("#next-page-button-anchor").offset().top}, 500);

(It doesn't answer the ultimate cause, though. Maybe some kind of bug in Safari mobile ?)

Executing a batch script on Windows shutdown

You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947

  1. Run gpedit.msc to open the Group Policy Editor,
  2. Navigate to Computer Configuration | Windows Settings | Scripts (Startup/Shutdown).

enter image description here

Failing to run jar file from command line: “no main manifest attribute”

You need to include "Main class" attribute in Manisfest.mf file in Jar

For example: Main-Class: MyClassName

Second thing, To add Manifest file in Your jar, You can manually create file in your workspace folder, and refresh in Eclipse Project explorer.

While exporting, Eclipse will create a Jar which will include your manifest.

Cheers !!

Clearing input in vuejs form

For reset all field in one form you can use event.target.reset()

_x000D_
_x000D_
const app = new Vue({_x000D_
    el: '#app',    _x000D_
    data(){_x000D_
 return{        _x000D_
            name : null,_x000D_
     lastname : null,_x000D_
     address : null_x000D_
 }_x000D_
    },_x000D_
    methods: {_x000D_
        submitForm : function(event){_x000D_
            event.preventDefault(),_x000D_
            //process...             _x000D_
            event.target.reset()_x000D_
        }_x000D_
    }_x000D_
_x000D_
});
_x000D_
form input[type=text]{border-radius:5px; padding:6px; border:1px solid #ddd}_x000D_
form input[type=submit]{border-radius:5px; padding:8px; background:#060; color:#fff; cursor:pointer; border:none}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>_x000D_
<div id="app">_x000D_
<form id="todo-field" v-on:submit="submitForm">_x000D_
        <input type="text" v-model="name"><br><br>_x000D_
        <input type="text" v-model="lastname"><br><br>_x000D_
        <input type="text" v-model="address"><br><br>_x000D_
        <input type="submit" value="Send"><br>_x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unable to access JSON property with "-" dash

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

How do I get a human-readable file size in bytes abbreviation using .NET?

This is not the most efficient way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
    order++;
    len = len/1024;
}

// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);

Paste in insert mode?

While in insert mode, you can use Ctrl-R {register}, where register can be:

  • + for the clipboard,
  • * for the X clipboard (last selected text in X),
  • " for the unnamed register (last delete or yank in Vim),
  • or a number of others (see :h registers).

Ctrl-R {register} inserts the text as if it were typed.

Ctrl-R Ctrl-O {register} inserts the text with the original indentation.

Ctrl-R Ctrl-P {register} inserts the text and auto-indents it.

Ctrl-O can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p can also be used, for example.

For more information, view the documentation with :h i_ctrl-r

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

SQL to generate a list of numbers from 1 to 100

If you want your integers to be bound between two integers (i.e. start with something other than 1), you can use something like this:

with bnd as (select 4 lo, 9 hi from dual)
select (select lo from bnd) - 1 + level r
from dual
connect by level <= (select hi-lo from bnd);

It gives:

4
5
6
7
8

how to set radio option checked onload with jQuery

I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

$("[name=gender]").val(["Male"]);

Note: Passing array is important.

Conditioned version:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}

HTML tag inside JavaScript

<div id="demo"></div>

<script type="text/javascript">
    if(document.getElementById('number1').checked) {
        var demo = document.getElementById("demo");    
        demo.innerHtml='<h1>Hello member</h1>';
    } else {
        demo.innerHtml='';
    }
</script>

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

Pass arguments to Constructor in VBA

When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId:

Attribute VB_PredeclaredId = False

Set it to True, save, and re-import the module into your VBA project.

Classes with a PredeclaredId have a "global instance" that you get for free - exactly like UserForm modules (export a user form, you'll see its predeclaredId attribute is set to true).

A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!

Instead, you leverage that default instance to implement your factory method:

[Employee class]

'@PredeclaredId
Option Explicit

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As Employee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

With that, you can do this:

Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)

Employee.Create is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.

Problem is, this is also perfectly legal:

Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)

And that sucks, because now you have a confusing API. You could use '@Description annotations / VB_Description attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.

Besides, the Property Let members are accessible, so your Employee instance is mutable:

empl.Name = "Jane" ' Johnny no more!

The trick is to make your class implement an interface that only exposes what needs to be exposed:

[IEmployee class]

Option Explicit

Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property

And now you make Employee implement IEmployee - the final class might look like this:

[Employee class]

'@PredeclaredId
Option Explicit
Implements IEmployee

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As IEmployee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

Private Property Get IEmployee_Name() As String
    IEmployee_Name = Name
End Property

Private Property Get IEmployee_Age() As Integer
    IEmployee_Age = Age
End Property

Notice the Create method now returns the interface, and the interface doesn't expose the Property Let members? Now calling code can look like this:

Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)

And since the client code is written against the interface, the only members empl exposes are the members defined by the IEmployee interface, which means it doesn't see the Create method, nor the Self getter, nor any of the Property Let mutators: so instead of working with the "concrete" Employee class, the rest of the code can work with the "abstract" IEmployee interface, and enjoy an immutable, polymorphic object.

Escaping single quote in PHP when inserting into MySQL

mysql_real_escape_string() or str_replace() function will help you to solve your problem.

http://phptutorial.co.in/php-echo-print/

Swift: Sort array of objects alphabetically

For those using Swift 3, the equivalent method for the accepted answer is:

movieArr.sorted { $0.Name < $1.Name }

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

How do I 'git diff' on a certain directory?

Not only you can add a path, but you can add git diff --relative to get result relative to that folder.

git -C a/folder diff --relative

And with Git 2.28 (Q3 2020), the commands in the "diff" family learned to honor the "diff.relative" configuration variable.

See commit c28ded8 (22 May 2020) by Laurent Arnoud (spk).
(Merged by Junio C Hamano -- gitster -- in commit e34df9a, 02 Jun 2020)

diff: add config option relative

Signed-off-by: Laurent Arnoud
Acked-by: Ðoàn Tr?n Công Danh

The diff.relative boolean option set to true shows only changes in the current directory/value specified by the path argument of the relative option and shows pathnames relative to the aforementioned directory.

Teach --no-relative to override earlier --relative

Add for git-format-patch(1) options documentation --relative and --no-relative

The documentation now includes:

diff.relative:

If set to 'true', 'git diff' does not show changes outside of the directory and show pathnames relative to the current directory.

Shell script - remove first and last quote (") from a variable

My version

strip_quotes() {
    while [[ $# -gt 0 ]]; do
        local value=${!1}
        local len=${#value}
        [[ ${value:0:1} == \" && ${value:$len-1:1} == \" ]] && declare -g $1="${value:1:$len-2}"
        shift
    done
}

The function accepts variable name(s) and strips quotes in place. It only strips a matching pair of leading and trailing quotes. It doesn't check if the trailing quote is escaped (preceded by \ which is not itself escaped).

In my experience, general-purpose string utility functions like this (I have a library of them) are most efficient when manipulating the strings directly, not using any pattern matching and especially not creating any sub-shells, or calling any external tools such as sed, awk or grep.

var1="\"test \\ \" end \""
var2=test
var3=\"test
var4=test\"
echo before:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done
strip_quotes var{1,2,3,4}
echo
echo after:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done

Could not find or load main class

First, put your file *.class (e.g Hello.class) into 1 folder (e.g C:\java). Then you try command and type cd /d C:\java. Now you can type "java Hello" !

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

Read file content from S3 bucket with boto3

boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines.

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

Simple way to transpose columns and rows in SQL?

I'd like to point out few more solutions to transposing columns and rows in SQL.

The first one is - using CURSOR. Although the general consensus in the professional community is to stay away from SQL Server Cursors, there are still instances whereby the use of cursors is recommended. Anyway, Cursors present us with another option to transpose rows into columns.

  • Vertical expansion

    Similar to the PIVOT, the cursor has the dynamic capability to append more rows as your dataset expands to include more policy numbers.

  • Horizontal expansion

    Unlike the PIVOT, the cursor excels in this area as it is able to expand to include newly added document, without altering the script.

  • Performance breakdown

    The major limitation of transposing rows into columns using CURSOR is a disadvantage that is linked to using cursors in general – they come at significant performance cost. This is because the Cursor generates a separate query for each FETCH NEXT operation.

Another solution of transposing rows into columns is by using XML.

The XML solution to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

  • Vertical expansion

    Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

  • Horizontal expansion

    Unlike the PIVOT, newly added documents can be displayed without altering the script.

  • Performance breakdown

    In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

How to modify JsonNode in Java?

Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):

Exception in thread "main" java.lang.ClassCastException: 
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

The solution is to get the 'parent' node, and perform a put, effectively replacing the entire node, regardless of original node type.

If you need to "modify" the node using the existing value of the node:

  1. get the value/array of the JsonNode
  2. Perform your modification on that value/array
  3. Proceed to call put on the parent.

Code, where the goal is to modify subfield, which is the child node of NodeA and Node1:

JsonNode nodeParent = someNode.get("NodeA")
                .get("Node1");

// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");

Credits:

I got this inspiration from here, thanks to wassgreen@

Populating a database in a Laravel migration file

Another clean way to do it is to define a private method which create instance et persist concerned Model.

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('label', 256);
        $table->timestamps();
        $table->softDeletes();
    });

    $this->postCreate('admin', 'user');
}

private function postCreate(string ...$roles)  {
    foreach ($roles as $role) {
        $model = new Role();
        $model->setAttribute('label', $role);
        $model->save();
    }
}

With this solution, timestamps fields will be generated by Eloquent.

EDIT: it's better to use seeder system to disctinct database structure generation and database population.

Android Debug Bridge (adb) device - no permissions

...the OP’s own answer is wrong in so far, that there are no “special system permissions”. – The “no permission” problem boils down to ... no permissions.

Unfortunately it is not easy to debug, because adb makes it a secret which device it tries to access! On Linux, it tries to open the “USB serial converter” device of the phone, which is e.g. /dev/bus/usb/001/115 (your bus number and device address will vary). This is sometimes linked and used from /dev/android_adb.

lsusb will help to find bus number and device address. Beware that the device address will change for sure if you re-plug, as might the bus number if the port gets confused about which speed to use (e.g. one physical port ends up on one logical bus or another).

An lsusb-line looks similar to this: Bus 001 Device 115: ID 4321:fedc bla bla bla

lsusb -v might help you to find the device if the “bla bla bla” is not hint enough (sometimes it does neither contain the manufacturer, nor the model of the phone).

Once you know the device, check with your own eyes that ls -a /dev/bus/usb/001/115 is really accessible for the user in question! Then check that it works with chmod and fix your udev setup.

PS1: /dev/android_adb can only point to one device, so make sure it does what you want.

PS2: Unrelated to this question, but less well known: adb has a fixed list of vendor ids it goes through. This list can be extended from ~/.android/adb_usb.ini, which should contain 0x4321 (if we follow my example lsusb line from above). – Not needed here, as you don’t even get a “no permissions” if the vendor id is not known.

On Duplicate Key Update same as insert

You may want to consider using REPLACE INTO syntax, but be warned, upon duplicate PRIMARY / UNIQUE key, it DELETES the row and INSERTS a new one.

You won't need to re-specify all the fields. However, you should consider the possible performance reduction (depends on your table design).

Caveats:

  • If you have AUTO_INCREMENT primary key, it will be given a new one
  • Indexes will probably need to be updated

How to pass arguments from command line to gradle

If you need to check and set one argument, your build.gradle file would be like this:

....

def coverageThreshold = 0.15

if (project.hasProperty('threshold')) {
    coverageThreshold = project.property('threshold').toString().toBigDecimal()
}

//print the value of variable
println("Coverage Threshold: $coverageThreshold")
...

And the Sample command in windows:

gradlew clean test -Pthreshold=0.25

Exception in thread "main" java.lang.Error: Unresolved compilation problems

For this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

There are problems with your import or package name.
You can delete the package name or fix import errors

no sqljdbc_auth in java.library.path

To resolve I did the following:

  1. Copied sqljdbc_auth.dll into dir: C:\Windows\System32
  2. Restarted my application

npm install Error: rollbackFailedOptional

The cause for this might be your current NPM registry. Try to check for a .npmrc file. These can be at various locations:

  • per-project config file (/path/to/my/project/.npmrc)
  • per-user config file (~/.npmrc)
  • global config file ($PREFIX/etc/npmrc)
  • npm builtin config file (/path/to/npm/npmrc)

Within these there can be something like

registry=https://mycustomregistry.example.org

which will take priority over the default one (http://registry.npmjs.org/). You can delete this line in the file or use the default registry like that:

npm <command> --registry http://registry.npmjs.org/

How do I get Flask to run on port 80?

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

How do you implement a circular buffer in C?

Extending adam-rosenfield's solution, i think the following will work for multithreaded single producer - single consumer scenario.

int cb_push_back(circular_buffer *cb, const void *item)
{
  void *new_head = (char *)cb->head + cb->sz;
  if (new_head == cb>buffer_end) {
      new_head = cb->buffer;
  }
  if (new_head == cb->tail) {
    return 1;
  }
  memcpy(cb->head, item, cb->sz);
  cb->head = new_head;
  return 0;
}

int cb_pop_front(circular_buffer *cb, void *item)
{
  void *new_tail = cb->tail + cb->sz;
  if (cb->head == cb->tail) {
    return 1;
  }
  memcpy(item, cb->tail, cb->sz);
  if (new_tail == cb->buffer_end) {
    new_tail = cb->buffer;
  }
  cb->tail = new_tail;
  return 0;
}

Insert an item into sorted list in Python

This is a possible solution for you:

a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
    if b[i] > c:
        break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]

Generating unique random numbers (integers) between 0 and 'x'

Here's a simple, one-line solution:

var limit = 10;
var amount = 3;

randoSequence(1, limit).slice(0, amount);

It uses randojs.com to generate a randomly shuffled array of integers from 1 through 10 and then cuts off everything after the third integer. If you want to use this answer, toss this within the head tag of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.

You have to call show() either in onProgressUpdate() or in onPostExecute().

For example:

class ExampleTask extends AsyncTask<String, String, String> {

    // Your onPreExecute method.

    @Override
    protected String doInBackground(String... params) {
        // Your code.
        if (condition_is_true) {
            this.publishProgress("Show the dialog");
        }
        return "Result";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        connectionProgressDialog.dismiss();
        downloadSpinnerProgressDialog.show();
    }
}

Transparent image - background color

If I understand you right, you can do this:

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

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

Automatically create an Enum based on values in a database lookup table?

I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:

public abstract class CustomEnum
{
    private readonly string _name;
    private readonly object _id;

    protected CustomEnum( string name, object id )
    {
        _name = name;
        _id = id;
    }

    public string Name
    {
        get { return _name; }
    }

    public object Id
    {
        get { return _id; }
    }

    public override string ToString()
    {
        return _name;
    }
}

public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
    where TEnumType : CustomEnum<TEnumType, TIdType>
{
    protected CustomEnum( string name, TIdType id )
        : base( name, id )
    { }

    public new TIdType Id
    {
        get { return (TIdType)base.Id; }
    }

    public static TEnumType FromName( string name )
    {
        try
        {
            return FromDelegate( entry => entry.Name.Equals( name ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static TEnumType FromId( TIdType id )
    {
        try
        {
            return FromDelegate( entry => entry.Id.Equals( id ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static IEnumerable<TEnumType> GetAll()
    {
        var elements = new Collection<TEnumType>();
        var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );

        foreach (var info in infoArray)
        {
            var type = info.GetValue( null ) as TEnumType;
            elements.Add( type );
        }

        return elements;
    }

    protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
    {
        if(predicate == null)
            throw new ArgumentNullException( "predicate" );

        foreach (var entry in GetAll())
        {
            if (predicate( entry ))
                return entry;
        }

        throw new ArgumentException( "Element not found while using predicate" );
    }
}

Now I just need to create my enum I want to use:

 public sealed class SampleEnum : CustomEnum<SampleEnum, int>
    {
        public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
        public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );

        private SampleEnum( string name, int id, string additionalText )
            : base( name, id )
        {
            AdditionalText = additionalText;
        }

        public string AdditionalText { get; private set; }
    }

At last I can use it like I want:

 static void Main( string[] args )
        {
            foreach (var element in SampleEnum.GetAll())
            {
                Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
                Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
                Console.WriteLine();
            }

            Console.ReadKey();
        }

And my output would be:

Element1: foo
Is 'Element2': False

Element2: bar
Is 'Element2': True    

Docker-Compose can't connect to Docker Daemon

I had this problem and did not want to mess things up using sudo. When investigating, I tried to get some info :

docker info

Surprinsingly, I had the following error :

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http:///var/run/docker.sock/v1.38/info: dial unix /var/run/docker.sock: connect: permission denied

For some reason I did not have enough privileges, the following command solved my problem :

sudo chown $USER /var/run/docker.sock

Et voilà !

What is the difference between angular-route and angular-ui-router?

ngRoute is a basic routing library, where you can specify just one view and controller for any route.

With ui-router, you can specify multiple views, both parallel and nested. So if your application requires (or may require in future) any kind of complex routing/views, then go ahead with ui-router.

This is best getting started guide for AngularUI Router.

Generate random password string with requirements in javascript

Based on @Ryan Shillington answer above you may find this enhancment helpfull too. Think this is more secured then what was requeted on the original request in the question above.

  1. Password generated with at least 1 number, 1 upper case character, 1 lower case character and 1 Special character
  2. Password length is dynamic

_x000D_
_x000D_
//Password generated with at least 1 number, 1 upper case character, 1 lower case character and 1 Special character
function generatePassword() 
{
      var passwordLength = randomIntFromInterval(10,20);    
      var numberChars = "0123456789";
      var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var lowerChars = "abcdefghijklmnopqrstuvwxyz";
      var specialChars = "~!#$%&*-+|";
      var allChars = numberChars + upperChars + lowerChars + specialChars;
      var randPasswordArray = Array(passwordLength);
      randPasswordArray[0] = numberChars;
      randPasswordArray[1] = upperChars;
      randPasswordArray[2] = lowerChars;
      randPasswordArray[3] = specialChars;
      randPasswordArray = randPasswordArray.fill(allChars, 4);
      if(window.crypto && window.crypto.getRandomValues)
      {
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');  
      }
      else if(window.msCrypto && window.msCrypto.getRandomValues) 
      {
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.msCrypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');
      }else{
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
      }
      
    }

    function shuffleArray(array) 
    {
      for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
     
     return array;
}

//generate random number in the range (min and max included)
function randomIntFromInterval(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
}
_x000D_
<input type='text' id='p9'/>
<input type='button' value ='pass generator' onclick='document.getElementById("p9").value = generatePassword()'>
_x000D_
_x000D_
_x000D_

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

In my case, none of the other suggestions worked, however recloning my repository made this issue disappear.

Simulating a click in jQuery/JavaScript on a link

Easy! Just use jQuery's click function:

$("#theElement").click();

Add Insecure Registry to Docker

I happened to encounter a similar kind of issue after setting up local internal JFrog Docker Private Registry on Amazon Linux.

THE followings I did to solve the issue:

Added "--insecure-registry xx.xx.xx.xx:8081" by modifying the OPTIONS variable in the /etc/sysconfig/docker file:

OPTIONS="--default-ulimit nofile=1024:40961 --insecure-registry hostname:8081"

Then restarted the docker.

I was then able to login to the local docker registry using:

docker login -u admin -p password hostname:8081

Relative div height

Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...

See this : percentage in height doesn’t work?

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

When tracing out variables in the console, How to create a new line?

The worst thing of using just

console.log({'some stuff': 2} + '\n' + 'something')

is that all stuff are converted to the string and if you need object to show you may see next:

[object Object]

Thus my variant is the next code:

console.log({'some stuff': 2},'\n' + 'something');

How to list all the files in a commit?

I use changed alias a quite often. To set it up:

git config --global alias.changed 'show --pretty="format:" --name-only'

then:

git changed (lists files modified in last commit)   
git changed bAda55 (lists files modified in this commit)
git changed bAda55..ff0021 (lists files modified between those commits)

Similar commands that may be useful:

git log --name-status --oneline (very similar, but shows what actually happened M/C/D)
git show --name-only

iOS download and save image inside app

That's the main concept. Have fun ;)

NSURL *url = [NSURL URLWithString:@"http://example.com/yourImage.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:@"/yourLocalImage.png"];
[data writeToFile:path atomically:YES];

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.

#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1

It's ok to have comment and blank lines before them.

Calling method using JavaScript prototype

No, you would need to give the do function in the constructor and the do function in the prototype different names.

Redirect to new Page in AngularJS using $location

Try entering the url inside the function

$location.url('http://www.google.com')

Drop-down box dependent on the option selected in another drop-down box

In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

[Edit 2021] or use data-attributes, something like:

_x000D_
_x000D_
document.addEventListener("change", checkSelect);

function checkSelect(evt) {
  const origin = evt.target;

  if (origin.dataset.dependentSelector) {
    const selectedOptFrom = origin.querySelector("option:checked")
      .dataset.dependentOpt || "n/a";
    const addRemove = optData => (optData || "") === selectedOptFrom 
      ? "add" : "remove";
    document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
      .forEach( opt => 
        opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
  }
}
_x000D_
[data-from-dependent] {
  display: none;
}

[data-from-dependent].display {
  display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
  <option>MANUAL</option>
  <option data-dependent-opt="ONLINE">ONLINE</option>
  <option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>

<select id="status" name="status">
  <option>OPEN</option>
  <option>DELIVERED</option>
  <option data-from-dependent="ONLINE">SHIPPED</option>
  <option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
  <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
_x000D_
_x000D_

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

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

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

END     
$$ LANGUAGE plpgsql;

Call:

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

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

  • I use dollar quoting to avoid quoting hell.

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

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

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

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Node.js - get raw request body using Express

// Change the way body-parser is used
const bodyParser = require('body-parser');

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}
app.use(bodyParser.json({ verify: rawBodySaver, extended: true }));




// Now we can access raw-body any where in out application as follows
request.rawBody;

How to get Django and ReactJS to work together?

I feel your pain as I, too, am starting out to get Django and React.js working together. Did a couple of Django projects, and I think, React.js is a great match for Django. However, it can be intimidating to get started. We are standing on the shoulders of giants here ;)

Here's how I think, it all works together (big picture, please someone correct me if I'm wrong).

  • Django and its database (I prefer Postgres) on one side (backend)
  • Django Rest-framework providing the interface to the outside world (i.e. Mobile Apps and React and such)
  • Reactjs, Nodejs, Webpack, Redux (or maybe MobX?) on the other side (frontend)

Communication between Django and 'the frontend' is done via the Rest framework. Make sure you get your authorization and permissions for the Rest framework in place.

I found a good boiler template for exactly this scenario and it works out of the box. Just follow the readme https://github.com/scottwoodall/django-react-template and once you are done, you have a pretty nice Django Reactjs project running. By no means this is meant for production, but rather as a way for you to dig in and see how things are connected and working!

One tiny change I'd like to suggest is this: Follow the setup instructions BUT before you get to the 2nd step to setup the backend (Django here https://github.com/scottwoodall/django-react-template/blob/master/backend/README.md), change the requirements file for the setup.

You'll find the file in your project at /backend/requirements/common.pip Replace its content with this

appdirs==1.4.0
Django==1.10.5
django-autofixture==0.12.0
django-extensions==1.6.1
django-filter==1.0.1
djangorestframework==3.5.3
psycopg2==2.6.1

this gets you the latest stable version for Django and its Rest framework.

I hope that helps.

Prevent browser caching of AJAX call result

JQuery's $.get() will cache the results. Instead of

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

$.ajax({url: "myurl", success: myCallback, cache: false});

Presenting a UIAlertController properly on an iPad using iOS 8

Update for Swift 3.0 and higher

    let actionSheetController: UIAlertController = UIAlertController(title: "SomeTitle", message: nil, preferredStyle: .actionSheet)

    let editAction: UIAlertAction = UIAlertAction(title: "Edit Details", style: .default) { action -> Void in

        print("Edit Details")
    }

    let deleteAction: UIAlertAction = UIAlertAction(title: "Delete Item", style: .default) { action -> Void in

        print("Delete Item")
    }

    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }

    actionSheetController.addAction(editAction)
    actionSheetController.addAction(deleteAction)
    actionSheetController.addAction(cancelAction)

//        present(actionSheetController, animated: true, completion: nil)   // doesn't work for iPad

    actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad

    present(actionSheetController, animated: true) {
        print("option menu presented")
    }

Installing Apache Maven Plugin for Eclipse

  1. In Eclipse Select Help -> Marketplace

  2. Enter "Maven" in Find box and click on Go button

  3. Click on "Install" button for Maven Integration for Eclipse (Juno and newer)

With this, maven should get install without any problem.

IntelliJ: Never use wildcard imports

enter image description here

IntelliJ IDEA 2018.1.4 (Ultimate Edition) built on May 16, 2018

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

Django: Calling .update() on a single model instance retrieved by .get()?

With the advent of Django 1.7, there is now a new update_or_create QuerySet method, which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.

Example from the documentation:

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.


Pre-Django 1.7:

Change the model field values as appropriate, then call .save() to persist the changes:

try:
    obj = Model.objects.get(field=value)
    obj.field = new_value
    obj.save()
except Model.DoesNotExist:
    obj = Model.objects.create(field=new_value)
# do something else with obj if need be

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

How can I use iptables on centos 7?

RHEL and CentOS 7 use firewall-cmd instead of iptables. You should use that kind of command:

# add ssh port as permanent opened port
firewall-cmd --zone=public --add-port=22/tcp --permanent

Then, you can reload rules to be sure that everything is ok

firewall-cmd --reload

This is better than using iptable-save, espacially if you plan to use lxc or docker containers. Launching docker services will add some rules that iptable-save command will prompt. If you save the result, you will have a lot of rules that should NOT be saved. Because docker containers can change them ip addresses at next reboot.

Firewall-cmd with permanent option is better for that.

Check "man firewall-cmd" or check the official firewalld docs to see options. There are a lot of options to check zones, configuration, how it works... man page is really complete.

I strongly recommand to not use iptables-service since Centos 7

What is the use of static constructors?

From Static Constructors (C# Programming Guide):

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Equivalent of LIMIT for DB2

Theres these available options:-

DB2 has several strategies to cope with this problem.
You can use the "scrollable cursor" in feature.
In this case you can open a cursor and, instead of re-issuing a query you can FETCH forward and backward.
This works great if your application can hold state since it doesn't require DB2 to rerun the query every time.
You can use the ROW_NUMBER() OLAP function to number rows and then return the subset you want.
This is ANSI SQL 
You can use the ROWNUM pseudo columns which does the same as ROW_NUMBER() but is suitable if you have Oracle skills.
You can use LIMIT and OFFSET if you are more leaning to a mySQL or PostgreSQL dialect.  

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

Vertical (rotated) text in HTML table

Have a look at this, i found this while looking for a solution for IE 7.

totally a cool solution for css only vibes

Thanks aiboy for the soultion

heres the link

and here is the stack-overflow link where i came across this link meow

         .vertical-text-vibes{

                /* this is for shity "non IE" browsers
                   that dosn't support writing-mode */
                -webkit-transform: translate(1.1em,0) rotate(90deg);
                   -moz-transform: translate(1.1em,0) rotate(90deg);
                     -o-transform: translate(1.1em,0) rotate(90deg);
                        transform: translate(1.1em,0) rotate(90deg);
                -webkit-transform-origin: 0 0;
                   -moz-transform-origin: 0 0;
                     -o-transform-origin: 0 0;
                        transform-origin: 0 0;  
             /* IE9+ */    ms-transform: none;    
                   -ms-transform-origin: none;    
        /* IE8+ */    -ms-writing-mode: tb-rl;    
   /* IE7 and below */    *writing-mode: tb-rl;

            }

How to stop console from closing on exit?

Add a Console.ReadKey call to your program to force it to wait for you to press a key before exiting.

Docker is installed but Docker Compose is not ? why?

Refered to the answers given above (I do not have enough reputation to refer separately to individual solutions, hence I do this collectively in this place), I want to supplement them with some important suggestions:

  1. docker-compose you can install from the repository (if you have this package in the repository, if not you can adding to system a repository with this package) or download binary with use curl - totourial on the official website of the project - src: https://docs.docker.com/compose/install /

  2. docker-compose from the repository is in version 1.8.0 (at least at me). This docker-compose version does not support configuration files in version 3. It only has version = <2 support. Inthe official site of the project is a recommendation to use container configuration in version 3 - src: https://docs.docker.com/compose/compose-file / compose-versioning /. From my own experience with work in the docker I recommend using container configurations in version 3 - there are more configuration options to use than in versions <3. If you want to use the configurations configurations in version 3 you have to do update / install docker-compose to the version of at least 1.17 - preferably the latest stable. The official site of the project is toturial how to do this process - src: https://docs.docker.com/compose/install/

  3. when you try to manually remove the old docker-compose binaries, you can have information about the missing file in the default path /usr/local/bin/docker-compose. At my case, docker-compose was in the default path /usr/bin/docker-compose. In this case, I suggest you use the find tool in your system to find binary file docker-compose - example syntax: sudo find / -name 'docker-compose'. It helped me. Thanks to this, I removed the old docker-compose version and added the stable to the system - I use the curl tool to download binary file docker-compose, putting it in the right path and giving it the right permissions - all this process has been described in the posts above.

Regards, Adam

How to use greater than operator with date?

In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example

SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';

How do I right align div elements?

Simple answer is here:

<div style="text-align: right;">
    anything:
    <select id="locality-dropdown" name="locality" class="cls" style="width: 200px; height: 28px; overflow:auto;">
    </select>
</div>

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Pandas Merging 101

In this answer, I will consider practical examples.

The first one, is of pandas.concat.

The second one, of merging dataframes from the index of one and the column of another one.


1. pandas.concat

Considering the following DataFrames with the same column names:

Preco2018 with size (8784, 5)

DataFrame 1

Preco 2019 with size (8760, 5)

DataFrame 2

That have the same column names.

You can combine them using pandas.concat, by simply

import pandas as pd

frames = [Preco2018, Preco2019]

df_merged = pd.concat(frames)

Which results in a DataFrame with the following size (17544, 5)

DataFrame result of the combination of two dataframes

If you want to visualize, it ends up working like this

How concat works

(Source)


2. Merge by Column and Index

In this part, I will consider a specific case: If one wants to merge the index of one dataframe and the column of another dataframe.

Let's say one has the dataframe Geo with 54 columns, being one of the columns the Date Data, which is of type datetime64[ns].

enter image description here

And the dataframe Price that has one column with the price and the index corresponds to the dates

enter image description here

In this specific case, to merge them, one uses pd.merge

merged = pd.merge(Price, Geo, left_index=True, right_on='Data')

Which results in the following dataframe

enter image description here

How to extract string following a pattern with grep, regex or perl

An HTML parser should be used for this purpose rather than regular expressions. A Perl program that makes use of HTML::TreeBuilder:

Program

#!/usr/bin/env perl

use strict;
use warnings;

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new_from_file( \*DATA );
my @elements = $tree->look_down(
    sub { defined $_[0]->attr('name') }
);

for (@elements) {
    print $_->attr('name'), "\n";
}

__DATA__
<table name="content_analyzer" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
  <type="global" />
</table>

Output

content_analyzer
content_analyzer2
content_analyzer_items

Python Pandas replicate rows in dataframe

df = df_try
for i in range(4):
   df = df.append(df_try)

# Here, we have df_try times 5

df = df.append(df)

# Here, we have df_try times 10

How get an apostrophe in a string in javascript

You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:

theAnchorText = 'I\'m home';

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

Regular Expression to match only alphabetic characters

[a-zA-Z] should do that just fine.

You can reference the cheat sheet.

Submit form on pressing Enter with AngularJS

If you only have one input you can use the form tag.

<form ng-submit="myFunc()" ...>

If you have more than one input, or don't want to use the form tag, or want to attach the enter-key functionality to a specific field, you can inline it to a specific input as follows:

<input ng-keyup="$event.keyCode == 13 && myFunc()" ...>

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Javascript - get array of dates between 2 dates

This may help someone,

You can get the row output from this and format the row_date object as you want.

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Gather multiple sets of columns

This could be done using reshape. It is possible with dplyr though.

  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
  colnames(df)[2] <- "Date"
  res <- reshape(df, idvar=c("id", "Date"), varying=3:8, direction="long", sep="_")
  row.names(res) <- 1:nrow(res)
  
   head(res)
  #  id       Date time       Q3.2       Q3.3
  #1  1 2009-01-01    1  1.3709584  0.4554501
  #2  2 2009-01-02    1 -0.5646982  0.7048373
  #3  3 2009-01-03    1  0.3631284  1.0351035
  #4  4 2009-01-04    1  0.6328626 -0.6089264
  #5  5 2009-01-05    1  0.4042683  0.5049551
  #6  6 2009-01-06    1 -0.1061245 -1.7170087

Or using dplyr

  library(tidyr)
  library(dplyr)
  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))

  df %>%
     gather(loop_number, "Q3", starts_with("Q3")) %>% 
     separate(loop_number,c("L1", "L2"), sep="_") %>% 
     spread(L1, Q3) %>%
     select(-L2) %>%
     head()
  #  id       time       Q3.2       Q3.3
  #1  1 2009-01-01  1.3709584  0.4554501
  #2  1 2009-01-01  1.3048697  0.2059986
  #3  1 2009-01-01 -0.3066386  0.3219253
  #4  2 2009-01-02 -0.5646982  0.7048373
  #5  2 2009-01-02  2.2866454 -0.3610573
  #6  2 2009-01-02 -1.7813084 -0.7838389

Update

With new version of tidyr, we can use pivot_longer to reshape multiple columns. (Using the changed column names from gsub above)

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(cols = starts_with("Q3"), 
          names_to = c(".value", "Q3"), names_sep = "_") %>% 
    select(-Q3)
# A tibble: 30 x 4
#      id time         Q3.2    Q3.3
#   <int> <date>      <dbl>   <dbl>
# 1     1 2009-01-01  0.974  1.47  
# 2     1 2009-01-01 -0.849 -0.513 
# 3     1 2009-01-01  0.894  0.0442
# 4     2 2009-01-02  2.04  -0.553 
# 5     2 2009-01-02  0.694  0.0972
# 6     2 2009-01-02 -1.11   1.85  
# 7     3 2009-01-03  0.413  0.733 
# 8     3 2009-01-03 -0.896 -0.271 
#9     3 2009-01-03  0.509 -0.0512
#10     4 2009-01-04  1.81   0.668 
# … with 20 more rows

NOTE: Values are different because there was no set seed in creating the input dataset