Lightweight Javascript DB for use in Node.js
NeDB seems to be what you are looking for. From the blurb:
Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore.
Can't find AVD or SDK manager in Eclipse
I had similar problem after updating SDK from r20 to r21, but all I missed was the SDK/AVD Manager and running into this post while searching for the answer.
I managed to solve it by going to Window -> Customize Perspective
, and under Command Groups Availability tab check the Android SDK and AVD Manager (not sure why it became unchecked because it was there before). I'm using Mac by the way, in case the menu option looks different.
Sequel Pro Alternative for Windows
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
How do I see the extensions loaded by PHP?
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
Using helpers in model: how do I include helper dependencies?
I wouldn't recommend any of these methods. Instead, put it within its own namespace.
class Post < ActiveRecord::Base
def clean_input
self.input = Helpers.sanitize(self.input, :tags => %w(b i u))
end
module Helpers
extend ActionView::Helpers::SanitizeHelper
end
end
What are the differences between a program and an application?
When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same.
The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(
Spring Boot - Handle to Hibernate SessionFactory
You can accomplish this with:
SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory is an JPA EntityManagerFactory
.
package net.andreaskluth.hibernatesample;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SomeService {
private SessionFactory hibernateFactory;
@Autowired
public SomeService(EntityManagerFactory factory) {
if(factory.unwrap(SessionFactory.class) == null){
throw new NullPointerException("factory is not a hibernate factory");
}
this.hibernateFactory = factory.unwrap(SessionFactory.class);
}
}
Python conversion between coordinates
You can use the cmath module.
If the number is converted to a complex format, then it becomes easier to just call the polar method on the number.
import cmath
input_num = complex(1, 2) # stored as 1+2j
r, phi = cmath.polar(input_num)
std::thread calling method of class
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
How to integrate sourcetree for gitlab
Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.
Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively
The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.
That's why each element has six DOM properties for your convenience: offsetWidth
, offsetHeight
, clientWidth
, clientHeight
, scrollWidth
and scrollHeight
. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).
Let's go through them in detail:
offsetWidth
, offsetHeight
: The size of the visual box incuding all borders. Can be calculated by adding width
/height
and paddings and borders, if the element has display: block
clientWidth
, clientHeight
: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.
scrollWidth
, scrollHeight
: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.
Since offsetWidth
takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula
scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth
Unfortunately, we may get rounding errors, since offsetWidth
and clientWidth
are always integers, while the actual sizes may be fractional with zoom levels other than 1.
Note that this
scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth
does not work reliably in Chrome, since Chrome returns width
with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)
Why am I getting "Thread was being aborted" in ASP.NET?
For a web service hosted in ASP.NET, the configuration property is executionTimeout:
<configuration> <system.web>
<httpRuntime executionTimeout="360" />
</system.web>
</configuration>
Set this and the thread abort exception will go away :)
Closing Bootstrap modal onclick
If the button tag is inside the div element who contains the modal, you can do something like:
<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>
Apache is downloading php files instead of displaying them
This might be happening due to the missing modules required for your php.
Assuming you have php7 installed, search available php7 modules using
sudo apt-cache search php7-*
Above command will list all available PHP7 modules for installation.
You can begin installation of modules like,
sudo apt-get install libapache2-mod-php7.0 php7.0-mysql php7.0-curl php7.0-json
How to find all occurrences of an element in a list
A solution using list.index
:
def indices(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
It's much faster than the list comprehension with enumerate
, for large lists. It is also much slower than the numpy
solution if you already have the array, otherwise the cost of converting outweighs the speed gain (tested on integer lists with 100, 1000 and 10000 elements).
NOTE: A note of caution based on Chris_Rands' comment: this solution is faster than the list comprehension if the results are sufficiently sparse, but if the list has many instances of the element that is being searched (more than ~15% of the list, on a test with a list of 1000 integers), the list comprehension is faster.
React JS get current date
OPTION 1:
if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2:
or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
Append a single character to a string or char array in java?
public class lab {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a string:");
String s1;
s1 = input.nextLine();
int k = s1.length();
char s2;
s2=s1.charAt(k-1);
s1=s2+s1+s2;
System.out.println("The new string is\n" +s1);
}
}
Here's the output you'll get.
*
Enter a string
CAT
The new string is
TCATT
*
It prints the the last character of the string to the first and last place. You can do it with any character of the String.
Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time
Regarding number of days in month just use static switch command and check if (year % 4 == 0)
in which case February will have 29 days.
Minute, hour, day etc:
var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));
JavaScript OR (||) variable assignment explanation
It means that if x
is set, the value for z
will be x
, otherwise if y
is set then its value will be set as the z
's value.
it's the same as
if(x)
z = x;
else
z = y;
It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false
is returned.
Can git undo a checkout of unstaged files
I just had that happen to me, I checked out an entire folder containing hours of work! Fortunately I found out that my IDE Netbeans keeps an history of each file, that allowed me to recuperate 99% of the stuff even though I needed to fix a few things manually.
Caesar Cipher Function in Python
This solution is more intuitively without the use of ord
function:
def caesar_cipher(raw_text, key):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
cipher_text = ""
for i in range(len(raw_text)):
char = raw_text[i]
idx = alphabet.find(char.upper())
if idx == -1:
cipher_text = cipher_text + char
elif char.islower():
cipher_text = cipher_text + shifted_alphabet[idx].lower()
else:
cipher_text = cipher_text + shifted_alphabet[idx]
return(cipher_text)
And an example:
plain_text = "The quick brown fox jumps over the lazy dog!"
caesar_cipher(plain_text,3)
And we get:
'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'
If we want to decrypt it:
caesar_cipher(caesar_cipher(plain_text,3),26-3)
and we get:
'The quick brown fox jumps over the lazy dog!'
More details here:https://predictivehacks.com/caesar-cipher-in-python/
How to change the MySQL root account password on CentOS7?
For CentOS 7 and MariaDB 10.4, I had success with the following commands:
su -
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --user=mysql"
systemctl restart mariadb
mysql -u root
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
flush privileges;
quit
systemctl unset-environment MYSQLD_OPTS
systemctl restart mariadb
How to disable horizontal scrolling of UIScrollView?
Disable horizontal scrolling by overriding contentOffset
property in subclass.
override var contentOffset: CGPoint {
get {
return super.contentOffset
}
set {
super.contentOffset = CGPoint(x: 0, y: newValue.y)
}
}
Type datetime for input parameter in procedure
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
How do I clear the content of a div using JavaScript?
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
How can I delete all cookies with JavaScript?
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie
. It's not available through the HTTP Cookie header either!
However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:
function clearCookie(name, domain, path){
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
Check if a record exists in the database
The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = @user)" , conn);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}
How do I raise an exception in Rails so it behaves like other Rails exceptions?
You can do it like this:
class UsersController < ApplicationController
## Exception Handling
class NotActivated < StandardError
end
rescue_from NotActivated, :with => :not_activated
def not_activated(exception)
flash[:notice] = "This user is not activated."
Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
redirect_to "/"
end
def show
// Do something that fails..
raise NotActivated unless @user.is_activated?
end
end
What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.
Best wishes,
Fabian
Rename a dictionary key
I am using @wim 's answer above, with dict.pop() when renaming keys, but I found a gotcha. Cycling through the dict to change the keys, without separating the list of old keys completely from the dict instance, resulted in cycling new, changed keys into the loop, and missing some existing keys.
To start with, I did it this way:
for current_key in my_dict:
new_key = current_key.replace(':','_')
fixed_metadata[new_key] = fixed_metadata.pop(current_key)
I found that cycling through the dict in this way, the dictionary kept finding keys even when it shouldn't, i.e., the new keys, the ones I had changed! I needed to separate the instances completely from each other to (a) avoid finding my own changed keys in the for loop, and (b) find some keys that were not being found within the loop for some reason.
I am doing this now:
current_keys = list(my_dict.keys())
for current_key in current_keys:
and so on...
Converting the my_dict.keys() to a list was necessary to get free of the reference to the changing dict. Just using my_dict.keys() kept me tied to the original instance, with the strange side effects.
Wait until all promises complete even if some rejected
Promise.all
with using modern async/await
approach
const promise1 = //...
const promise2 = //...
const data = await Promise.all([promise1, promise2])
const dataFromPromise1 = data[0]
const dataFromPromise2 = data[1]
Raw_Input() Is Not Defined
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
Pure JavaScript Send POST Data Without a Form
You can use the XMLHttpRequest
object as follows:
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
That code would post someStuff
to url
. Just make sure that when you create your XMLHttpRequest
object, it will be cross-browser compatible. There are endless examples out there of how to do that.
Code coverage for Jest built on top of Jasmine
I had the same issue and I fixed it as below.
- install yarn
npm install --save-dev yarn
- install jest-cli
npm install --save-dev jest-cli
- add this to the package.json
"jest-coverage": "yarn run jest -- --coverage"
After you write the tests, run the command npm run jest-coverage
. This will create a coverage folder in the root directory. /coverage/icov-report/index.html has the HTML view of the code coverage.
How to find and replace string?
// replaced text will be in buffer.
void Replace(char* buffer, const char* source, const char* oldStr, const char* newStr)
{
if(buffer==NULL || source == NULL || oldStr == NULL || newStr == NULL) return;
int slen = strlen(source);
int olen = strlen(oldStr);
int nlen = strlen(newStr);
if(olen>slen) return;
int ix=0;
for(int i=0;i<slen;i++)
{
if(oldStr[0] == source[i])
{
bool found = true;
for(int j=1;j<olen;j++)
{
if(source[i+j]!=oldStr[j])
{
found = false;
break;
}
}
if(found)
{
for(int j=0;j<nlen;j++)
buffer[ix++] = newStr[j];
i+=(olen-1);
}
else
{
buffer[ix++] = source[i];
}
}
else
{
buffer[ix++] = source[i];
}
}
}
Select the values of one property on all objects of an array in PowerShell
To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.
Outside of a pipeline[1], use (PSv3+): $objects.Name
as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.
Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.
Alternatively, in PSv2, use the foreach
statement, whose output you can also assign directly to a variable:
$results = foreach ($obj in $objects) { $obj.Name }
If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:
(Get-ChildItem -File | Where-Object Length -lt 1gb).Name
Tradeoffs:
- Both the input collection and output array must fit into memory as a whole.
- If the input collection is itself the result of a command (pipeline) (e.g.,
(Get-ChildItem).Name
), that command must first run to completion before the resulting array's elements can be accessed.
In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use: $objects | Select-Object -ExpandProperty Name
- The need for
-ExpandProperty
is explained in Scott Saad's answer (you need it to get only the property value).
- You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
- Tradeoff:
- Use of the pipeline is comparatively slow.
For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.
Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object
syntax called an operation statement (again, PSv3+):
; e.g., the following PSv3+ solution is easy to append to an existing command:
$objects | % Name # short for: $objects | ForEach-Object -Process { $_.Name }
The PSv4+ .ForEach()
array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:
# By property name (string):
$objects.ForEach('Name')
# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.
For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).
The script-block variant ({ ... }
) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object
cmdlet (%
).
Note: The .ForEach()
array method, like its .Where()
sibling (the in-memory equivalent of Where-Object
), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]
), even if only one output object is produced.
By contrast, member enumeration, Select-Object
, ForEach-Object
and Where-Object
return a single output object as-is, without wrapping it in a collection (array).
Comparing the performance of the various approaches
Here are sample timings for the various approaches, based on an input collection of 10,000
objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:
Important
The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem
) or [pscustomobject]
instances (e.g., as output by Convert-FromCsv
).
The reason is that [pscustomobject]
properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.
The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.
For brevity, alias %
is used for the ForEach-Object
cmdlet.
General conclusions, applicable to both regular .NET type and [pscustomobject]
input:
The member-enumeration ($collection.Name
) and foreach ($obj in $collection)
solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.
Surprisingly, % Name
performs much worse than % { $_.Name }
- see this GitHub issue.
PowerShell Core consistently outperforms Windows Powershell here.
Timings with regular .NET types:
- PowerShell Core v7.0.0-preview.3
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.005
1.06 foreach($o in $objects) { $o.Name } 0.005
6.25 $objects.ForEach('Name') 0.028
10.22 $objects.ForEach({ $_.Name }) 0.046
17.52 $objects | % { $_.Name } 0.079
30.97 $objects | Select-Object -ExpandProperty Name 0.140
32.76 $objects | % Name 0.148
- Windows PowerShell v5.1.18362.145
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.012
1.32 foreach($o in $objects) { $o.Name } 0.015
9.07 $objects.ForEach({ $_.Name }) 0.105
10.30 $objects.ForEach('Name') 0.119
12.70 $objects | % { $_.Name } 0.147
27.04 $objects | % Name 0.312
29.70 $objects | Select-Object -ExpandProperty Name 0.343
Conclusions:
- In PowerShell Core,
.ForEach('Name')
clearly outperforms .ForEach({ $_.Name })
. In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.
Timings with [pscustomobject]
instances:
- PowerShell Core v7.0.0-preview.3
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.006
1.11 foreach($o in $objects) { $o.Name } 0.007
1.52 $objects.ForEach('Name') 0.009
6.11 $objects.ForEach({ $_.Name }) 0.038
9.47 $objects | Select-Object -ExpandProperty Name 0.058
10.29 $objects | % { $_.Name } 0.063
29.77 $objects | % Name 0.184
- Windows PowerShell v5.1.18362.145
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.008
1.14 foreach($o in $objects) { $o.Name } 0.009
1.76 $objects.ForEach('Name') 0.015
10.36 $objects | Select-Object -ExpandProperty Name 0.085
11.18 $objects.ForEach({ $_.Name }) 0.092
16.79 $objects | % { $_.Name } 0.138
61.14 $objects | % Name 0.503
Conclusions:
Note how with [pscustomobject]
input .ForEach('Name')
by far outperforms the script-block based variant, .ForEach({ $_.Name })
.
Similarly, [pscustomobject]
input makes the pipeline-based Select-Object -ExpandProperty Name
faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name })
, but in PowerShell Core still about 50% slower.
In short: With the odd exception of % Name
, with [pscustomobject]
the string-based methods of referencing the properties outperform the scriptblock-based ones.
Source code for the tests:
Note:
$count = 1e4 # max. input object count == 10,000
$runs = 10 # number of runs to average
# Note: Using [pscustomobject] instances rather than instances of
# regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false
# Create sample input objects.
if ($useCustomObjectInput) {
# Use [pscustomobject] instances.
$objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
# Use instances of a regular .NET type.
# Note: The actual count of files and folders in your file-system
# may be less than $count
$objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}
Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."
# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
{ $objects | % Name },
{ $objects | % { $_.Name } },
{ $objects.ForEach('Name') },
{ $objects.ForEach({ $_.Name }) },
{ $objects.Name },
{ foreach($o in $objects) { $o.Name } }
# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*
[1] Technically, even a command without |
, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use |
and therefore involve multiple commands connected by a pipeline.
Angular, content type is not being sent with $http
$http({
method: 'GET',
url:'/http://localhost:8080/example/test' + toto,
data: '',
headers: {
'Content-Type': 'application/json'
}
}).then(
function(response) {
return response.data;
},
function(errResponse) {
console.error('Error !!');
return $q.reject(errResponse);
}
How to get HttpRequestMessage data
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
char initial value in Java
Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.
If you want the char
equivalent of 0, it's just Unicode 0, which can be written as
char c = '\0';
That's also the default value for an instance (or static) variable of type char
.
How to get the input from the Tkinter Text Widget?
I think this is a better way-
variable1=StringVar() # Value saved here
def search():
print(variable1.get())
return ''
ttk.Entry(mainframe, width=7, textvariable=variable1).grid(column=2, row=1)
ttk.Label(mainframe, text="label").grid(column=1, row=1)
ttk.Button(mainframe, text="Search", command=search).grid(column=2, row=13)
On pressing the button, the value in the text field would get printed.
But make sure You import the ttk separately.
The full code for a basic application is-
from tkinter import *
from tkinter import ttk
root=Tk()
mainframe = ttk.Frame(root, padding="10 10 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
variable1=StringVar() # Value saved here
def search():
print(variable1.get())
return ''
ttk.Entry(mainframe, width=7, textvariable=variable1).grid(column=2, row=1)
ttk.Label(mainframe, text="label").grid(column=1, row=1)
ttk.Button(mainframe, text="Search", command=search).grid(column=2, row=13)
root.mainloop()
JQuery Number Formatting
http://locutus.io/php/strings/number_format/
module.exports = function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-enter code hereline camelcase
// discuss at: http://locutus.io/php/number_format/
// original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// improved by: Kevin van Zonneveld (http://kvz.io)
// improved by: davook
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Theriault (https://github.com/Theriault)
// improved by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Michael White (http://getsprink.com)
// bugfixed by: Benjamin Lupton
// bugfixed by: Allan Jensen (http://www.winternet.no)
// bugfixed by: Howard Yeend
// bugfixed by: Diogo Resende
// bugfixed by: Rival
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// revised by: Luke Smith (http://lucassmith.name)
// input by: Kheang Hok Chin (http://www.distantia.ca/)
// input by: Jay Klehr
// input by: Amir Habibi (http://www.residence-mixte.com/)
// input by: Amirouche
// example 1: number_format(1234.56)
// returns 1: '1,235'
// example 2: number_format(1234.56, 2, ',', ' ')
// returns 2: '1 234,56'
// example 3: number_format(1234.5678, 2, '.', '')
// returns 3: '1234.57'
// example 4: number_format(67, 2, ',', '.')
// returns 4: '67,00'
// example 5: number_format(1000)
// returns 5: '1,000'
// example 6: number_format(67.311, 2)
// returns 6: '67.31'
// example 7: number_format(1000.55, 1)
// returns 7: '1,000.6'
// example 8: number_format(67000, 5, ',', '.')
// returns 8: '67.000,00000'
// example 9: number_format(0.9, 0)
// returns 9: '1'
// example 10: number_format('1.20', 2)
// returns 10: '1.20'
// example 11: number_format('1.20', 4)
// returns 11: '1.2000'
// example 12: number_format('1.2000', 3)
// returns 12: '1.200'
// example 13: number_format('1 000,50', 2, '.', ' ')
// returns 13: '100 050.00'
// example 14: number_format(1e-8, 8, '.', '')
// returns 14: '0.00000001'
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
if (('' + n).indexOf('e') === -1) {
return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
} else {
var arr = ('' + n).split('e')
var sig = ''
if (+arr[1] + prec > 0) {
sig = '+'
}
return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
}
}
// @todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
On design patterns: When should I use the singleton?
One of the ways you use a singleton is to cover an instance where there must be a single "broker" controlling access to a resource. Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively. For something like logging, they provide a way of abstracting away the writes to something like a log file -- you could wrap a caching mechanism to your singleton, etc...
Also think of a situation where you have an application with many windows/threads/etc, but which needs a single point of communication. I once used one to control jobs that I wanted my application to launch. The singleton was responsible for serializing the jobs and displaying their status to any other part of the program which was interested. In this sort of scenario, you can look at a singleton as being sort of like a "server" class running inside your application... HTH
Checkout another branch when there are uncommitted changes on the current branch
Preliminary notes
This answer is an attempt to explain why Git behaves the way it does. It is not a recommendation to engage in any particular workflows. (My own preference is to just commit anyway, avoiding git stash
and not trying to be too tricky, but others like other methods.)
The observation here is that, after you start working in branch1
(forgetting or not realizing that it would be good to switch to a different branch branch2
first), you run:
git checkout branch2
Sometimes Git says "OK, you're on branch2 now!" Sometimes, Git says "I can't do that, I'd lose some of your changes."
If Git won't let you do it, you have to commit your changes, to save them somewhere permanent. You may want to use git stash
to save them; this is one of the things it's designed for. Note that git stash save
or git stash push
actually means "Commit all the changes, but on no branch at all, then remove them from where I am now." That makes it possible to switch: you now have no in-progress changes. You can then git stash apply
them after switching.
Sidebar: git stash save
is the old syntax; git stash push
was introduced in Git version 2.13, to fix up some problems with the arguments to git stash
and allow for new options. Both do the same thing, when used in the basic ways.
You can stop reading here, if you like!
If Git won't let you switch, you already have a remedy: use git stash
or git commit
; or, if your changes are trivial to re-create, use git checkout -f
to force it. This answer is all about when Git will let you git checkout branch2
even though you started making some changes. Why does it work sometimes, and not other times?
The rule here is simple in one way, and complicated/hard-to-explain in another:
You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.
That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git add
s, git rm
s and such—suppose you are on branch1
. A git checkout branch2
would have to do this:
- For every file that is in
branch1
and not in branch2
,1 remove that file.
- For every file that is in
branch2
and not in branch1
, create that file (with appropriate contents).
- For every file that is in both branches, if the version in
branch2
is different, update the working tree version.
Each of these steps could clobber something in your work-tree:
- Removing a file is "safe" if the version in the work-tree is the same as the committed version in
branch1
; it's "unsafe" if you've made changes.
- Creating a file the way it appears in
branch2
is "safe" if it does not exist now.2 It's "unsafe" if it does exist now but has the "wrong" contents.
- And of course, replacing the work-tree version of a file with a different version is "safe" if the work-tree version is already committed to
branch1
.
Creating a new branch (git checkout -b newbranch
) is always considered "safe": no files will be added, removed, or altered in the work-tree as part of this process, and the index/staging-area is also untouched. (Caveat: it's safe when creating a new branch without changing the new branch's starting-point; but if you add another argument, e.g., git checkout -b newbranch different-start-point
, this might have to change things, to move to different-start-point
. Git will then apply the checkout safety rules as usual.)
1This requires that we define what it means for a file to be in a branch, which in turn requires defining the word branch properly. (See also What exactly do we mean by "branch"?) Here, what I really mean is the commit to which the branch-name resolves: a file whose path is P
is in branch1
if git rev-parse branch1:P
produces a hash. That file is not in branch1
if you get an error message instead. The existence of path P
in your index or work-tree is not relevant when answering this particular question. Thus, the secret here is to examine the result of git rev-parse
on each branch-name:path
. This either fails because the file is "in" at most one branch, or gives us two hash IDs. If the two hash IDs are the same, the file is the same in both branches. No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches.
The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen. We are, at least initially, looking only at the mismatches between two frozen commits. Unfortunately, we—or Git—also have to deal with files that aren't in the commit you're going to switch away from and are in the commit you're going to switch to. This leads to the remaining complications, since files can also exist in the index and/or in the work-tree, without having to exist these two particular frozen commits we're working with.
2It might be considered "sort-of-safe" if it already exists with the "right contents", so that Git does not have to create it after all. I recall at least some versions of Git allowing this, but testing just now shows it to be considered "unsafe" in Git 1.8.5.4. The same argument would apply to a modified file that happens to be modified to match the to-be-switch-to branch. Again, 1.8.5.4 just says "would be overwritten", though. See the end of the technical notes as well: my memory may be faulty as I don't think the read-tree rules have changed since I first started using Git at version 1.5.something.
Does it matter whether the changes are staged or unstaged?
Yes, in some ways. In particular, you can stage a change, then "de-modify" the work tree file. Here's a file in two branches, that's different in branch1
and branch2
:
$ git show branch1:inboth
this file is in both branches
$ git show branch2:inboth
this file is in both branches
but it has more stuff in branch2 now
$ git checkout branch1
Switched to branch 'branch1'
$ echo 'but it has more stuff in branch2 now' >> inboth
At this point, the working tree file inboth
matches the one in branch2
, even though we're on branch1
. This change is not staged for commit, which is what git status --short
shows here:
$ git status --short
M inboth
The space-then-M means "modified but not staged" (or more precisely, working-tree copy differs from staged/index copy).
$ git checkout branch2
error: Your local changes ...
OK, now let's stage the working-tree copy, which we already know also matches the copy in branch2
.
$ git add inboth
$ git status --short
M inboth
$ git checkout branch2
Switched to branch 'branch2'
Here the staged-and-working copies both matched what was in branch2
, so the checkout was allowed.
Let's try another step:
$ git checkout branch1
Switched to branch 'branch1'
$ cat inboth
this file is in both branches
The change I made is lost from the staging area now (because checkout writes through the staging area). This is a bit of a corner case. The change is not gone, but the fact that I had staged it, is gone.
Let's stage a third variant of the file, different from either branch-copy, then set the working copy to match the current branch version:
$ echo 'staged version different from all' > inboth
$ git add inboth
$ git show branch1:inboth > inboth
$ git status --short
MM inboth
The two M
s here mean: staged file differs from HEAD
file, and, working-tree file differs from staged file. The working-tree version does match the branch1
(aka HEAD
) version:
$ git diff HEAD
$
But git checkout
won't allow the checkout:
$ git checkout branch2
error: Your local changes ...
Let's set the branch2
version as the working version:
$ git show branch2:inboth > inboth
$ git status --short
MM inboth
$ git diff HEAD
diff --git a/inboth b/inboth
index ecb07f7..aee20fb 100644
--- a/inboth
+++ b/inboth
@@ -1 +1,2 @@
this file is in both branches
+but it has more stuff in branch2 now
$ git diff branch2 -- inboth
$ git checkout branch2
error: Your local changes ...
Even though the current working copy matches the one in branch2
, the staged file does not, so a git checkout
would lose that copy, and the git checkout
is rejected.
Technical notes—only for the insanely curious :-)
The underlying implementation mechanism for all of this is Git's index. The index, also called the "staging area", is where you build the next commit: it starts out matching the current commit, i.e., whatever you have checked-out now, and then each time you git add
a file, you replace the index version with whatever you have in your work-tree.
Remember, the work-tree is where you work on your files. Here, they have their normal form, rather than some special only-useful-to-Git form like they do in commits and in the index. So you extract a file from a commit, through the index, and then on into the work-tree. After changing it, you git add
it to the index. So there are in fact three places for each file: the current commit, the index, and the work-tree.
When you run git checkout branch2
, what Git does underneath the covers is to compare the tip commit of branch2
to whatever is in both the current commit and the index now. Any file that matches what's there now, Git can leave alone. It's all untouched. Any file that's the same in both commits, Git can also leave alone—and these are the ones that let you switch branches.
Much of Git, including commit-switching, is relatively fast because of this index. What's actually in the index is not each file itself, but rather each file's hash. The copy of the file itself is stored as what Git calls a blob object, in the repository. This is similar to how the files are stored in commits as well: commits don't actually contain the files, they just lead Git to the hash ID of each file. So Git can compare hash IDs—currently 160-bit-long strings—to decide if commits X and Y have the same file or not. It can then compare those hash IDs to the hash ID in the index, too.
This is what leads to all the oddball corner cases above. We have commits X and Y that both have file path/to/name.txt
, and we have an index entry for path/to/name.txt
. Maybe all three hashes match. Maybe two of them match and one doesn't. Maybe all three are different. And, we might also have another/file.txt
that's only in X or only in Y and is or is not in the index now. Each of these various cases requires its own separate consideration: does Git need to copy the file out from commit to index, or remove it from index, to switch from X to Y? If so, it also has to copy the file to the work-tree, or remove it from the work-tree. And if that's the case, the index and work-tree versions had better match at least one of the committed versions; otherwise Git will be clobbering some data.
(The complete rules for all of this are described in, not the git checkout
documentation as you might expect, but rather the git read-tree
documentation, under the section titled "Two Tree Merge".)
what is the use of fflush(stdin) in c programming
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered
data for the given output or update stream via the stream's underlying
write function. For input streams, fflush() discards any buffered data
that has been fetched from the underlying file, but has not been
consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
Change Bootstrap input focus blue glow
To disable the blue glow (but you can modify the code to change color, size, etc), add this to your css:
.search-form input[type="search"] {
-webkit-box-shadow: none;
outline: -webkit-focus-ring-color auto 0px;
}
Here's a screencapture showing the effect: before and after:
Maven: Failed to retrieve plugin descriptor error
I had the same issue in Windows
and it worked since my proxy configuration in settings.xml
file was changed
So locate and edit the file inside the \conf
folder, for example : C:\Program Files\apache-maven-3.2.5\conf
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>jorgesys</username>
<password>supercalifragilisticoespialidoso</password>
<host>proxyjorgesys</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
- In my case i had to chage from port
80
to 8080
- If you can´t edit this file that is located inside
/program files
you can make a copy, edit the file and replace the file located into /program files
folder.
How to switch to another domain and get-aduser
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
How to set text size of textview dynamically for different screens
There is probably no need to use the ldpi
, mdpi
or hdpi
qualifiers in this case.
When you define a dimension in a resource file you include the measurement unit. If you use sp units they are scaled according to the screen density so text at 15sp should appear roughly the same size on screens of differing density.
(The real screen density of the device isn't going to exactly match as Android generalises screen density into 120, 160, 240, 320, 480 and 640 dpi
groups.)
When calling getResources().getDimension(R.dimen.textsize)
it will return the size in pixels. If using sp it will scaled by the screen density,
Calling setText(float)
sets the size in sp units
. This is where the issue is,
i.e you have pixels measurements on one hand and sp unit
on the other to fix do this:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
Note you can also use
getResources().getDimensionPixelSize(R.dimen.textSize);
instead of getDimension()
and it will round and convert to an non fractional value.
Docker - Bind for 0.0.0.0:4000 failed: port is already allocated
I solved it this way:
First, I stopped all running containers:
docker-compose down
Then I executed a lsof
command to find the process using the port (for me it was port 9000)
sudo lsof -i -P -n | grep 9000
Finally, I "killed" the process (in my case, it was a VSCode extension):
kill -9 <process id>
Which Python memory profiler is recommended?
Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.
Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.
Set focus on TextBox in WPF from view model
First off i would like to thank Avanka for helping me solve my focus problem. There is however a bug in the code he posted, namely in the line:
if (e.OldValue == null)
The problem I had was that if you first click in your view and focus the control, e.oldValue is no longer null. Then when you set the variable to focus the control for the first time, this results in the lostfocus and gotfocus handlers not being set.
My solution to this was as follows:
public static class ExtensionFocus
{
static ExtensionFocus()
{
BoundElements = new List<string>();
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
typeof(ExtensionFocus), new FrameworkPropertyMetadata(false, IsFocusedChanged));
private static List<string> BoundElements;
public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus GetIsFocused called with null element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus SetIsFocused called with null element");
}
element.SetValue(IsFocusedProperty, value);
}
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)d;
// OLD LINE:
// if (e.OldValue == null)
// TWO NEW LINES:
if (BoundElements.Contains(fe.Name) == false)
{
BoundElements.Add(fe.Name);
fe.LostFocus += OnLostFocus;
fe.GotFocus += OnGotFocus;
}
if (!fe.IsVisible)
{
fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
}
if ((bool)e.NewValue)
{
fe.Focus();
}
}
private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;
if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
{
fe.IsVisibleChanged -= fe_IsVisibleChanged;
fe.Focus();
}
}
private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, false);
}
}
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, true);
}
}
}
What does "res.render" do, and what does the html file look like?
What does res.render do and what does the html file look like?
res.render()
function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.
Answering Edit 2 part.
// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');
// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');
// here you render `orders` template
response.render("orders", {orders: orders_json});
So, the template path is views/
(first part) + orders
(second part) + .ejs
(third part) === views/orders.ejs
Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.
Passing data to a jQuery UI Dialog
Ok the first issue with the div tag was easy enough:
I just added a style="display:none;"
to it and then before showing the dialog I added this in my dialog script:
$("#dialog").css("display", "inherit");
But for the post version I'm still out of luck.
Why can't C# interfaces contain fields?
Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties
interface IEmployee
{
string Name
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
public static int numberOfEmployees;
private string _name;
public string Name // read-write instance property
{
get => _name;
set => _name = value;
}
private int _counter;
public int Counter // read-only instance property
{
get => _counter;
}
// constructor
public Employee() => _counter = ++numberOfEmployees;
}
Splitting String and put it on int array
Change the order in which you are doing things just a bit. You seem to be dividing by 2 for no particular reason at all.
While your application does not guarantee an input string of semi colon delimited variables you could easily make it do so:
package com;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Good practice to initialize before use
Scanner keyboard = new Scanner(System.in);
String input = "";
// it's also a good idea to prompt the user as to what is going on
keyboardScanner : for (;;) {
input = keyboard.next();
if (input.indexOf(",") >= 0) { // Realistically we would want to use a regex to ensure [0-9],...etc groupings
break keyboardScanner; // break out of the loop
} else {
keyboard = new Scanner(System.in);
continue keyboardScanner; // recreate the scanner in the event we have to start over, just some cleanup
}
}
String strarray[] = input.split(","); // move this up here
int intarray[] = new int[strarray.length];
int count = 0; // Declare variables when they are needed not at the top of methods as there is no reason to allocate memory before it is ready to be used
for (count = 0; count < intarray.length; count++) {
intarray[count] = Integer.parseInt(strarray[count]);
}
for (int s : intarray) {
System.out.println(s);
}
}
}
Creating a custom JButton in Java
You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:
try {
SynthLookAndFeel synth = new SynthLookAndFeel();
Class aClass = MainFrame.class;
InputStream stream = aClass.getResourceAsStream("\\default.xml");
if (stream == null) {
System.err.println("Missing configuration file");
System.exit(-1);
}
synth.load(stream, aClass);
UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
System.err.println("Bad configuration file");
pe.printStackTrace();
System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
System.err.println("Old JRE in use. Get a new one");
System.exit(-3);
}
From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.
The xml file might look like this:
<synth>
<style id="button">
<font name="DIALOG" size="12" style="BOLD"/>
<state value="MOUSE_OVER">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
<state value="ENABLED">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
</style>
<bind style="button" type="name" key="dirt"/>
</synth>
The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").
And a couple of useful links:
http://javadesktop.org/articles/synth/
http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html
Renaming Column Names in Pandas Groupby function
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary,
e.g., m.x is equivalent to m.dict["x"]
jQuery - multiple $(document).ready ...?
It is important to note that each jQuery()
call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.
This applies regardless of syntax. You can use jQuery()
, jQuery(function() {})
, $(document).ready()
, whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.
This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.
Find UNC path of a network drive?
This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:
https://pathcopycopy.github.io/
Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:
Transpose list of lists
matrix = [[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3]]
rows = len(matrix)
cols = len(matrix[0])
transposed = []
while len(transposed) < cols:
transposed.append([])
while len(transposed[-1]) < rows:
transposed[-1].append(0)
for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]
for i in transposed:
print(i)
Python: instance has no attribute
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
How do I add an element to a list in Groovy?
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
Redirecting a page using Javascript, like PHP's Header->Location
You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)
You can use window.location to change your current page.
$('.entry a:first').click(function() {
window.location = "http://google.ca";
});
Setting an environment variable before a command in Bash is not working for the second command in a pipe
Use env
.
For example, env FOO=BAR command
. Note that the environment variables will be restored/unchanged again when command
finishes executing.
Just be careful about about shell substitution happening, i.e. if you want to reference $FOO
explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env
.
$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR
JavaScript code to stop form submission
Just use a simple button
instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script
tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
ImportError: No module named 'Tkinter'
For windows 10, it is important to check in the Python install the optional feature "tcl/tk and IDLE". Otherwise you get a ModuleNotFoundError: No module named 'tkinter'. In my case, it was not possible to install tkinter after the Python install with something like "pip install tkinter"
C# Version Of SQL LIKE
there are several good answers here. to summarize what is already here and correct: using contains, startswith, endswith are good answers for most needs. regular expressions are what you want for more advanced needs.
something that is not mentioned in these answers, though, is that for a collection of strings, linq can be used to apply these filters in a call to the where method.
Normalization in DOM parsing with java - how does it work?
As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node
interface in com.sun.org.apache.xerces.internal.dom.ParentNode
looks like, gives you the idea how it actually works.
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid, next;
for (kid = firstChild; kid != null; kid = next) {
next = kid.nextSibling;
// If kid is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but kid is
// an empty text node.
if ( kid.getNodeType() == Node.TEXT_NODE )
{
// If an adjacent text node, merge it with kid
if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
{
((Text)kid).appendData(next.getNodeValue());
removeChild( next );
next = kid; // Don't advance; there might be another.
}
else
{
// If kid is empty, remove it
if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
removeChild( kid );
}
}
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
kid.normalize();
}
}
// We must also normalize all of the attributes
if ( attributes!=null )
{
for( int i=0; i<attributes.getLength(); ++i )
{
Node attr = attributes.item(i);
attr.normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
isNormalized(true);
}
Hope this saves you some time.
Get selected option from select element
Using the selectedOptions property (HTML5) you can get the selected option(s)
document.getElementbyId("id").selectedOptions;
With JQuery can be achieved by doing this
$("#id")[0].selectedOptions;
or
$("#id").prop("selectedOptions");
The property contains an HTMLCollection array similitar to this
one selected option
[<option value=?"1">?ABC</option>]
or multiple selections
[<option value=?"1">?ABC</option>, <option value=?"2">?DEF</option> ...]
SELECT CASE WHEN THEN (SELECT)
I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.
summing two columns in a pandas dataframe
If "budget" has any NaN values but you don't want it to sum to NaN then try:
def fun (b, a):
if math.isnan(b):
return a
else:
return b + a
f = np.vectorize(fun, otypes=[float])
df['variance'] = f(df['budget'], df_Lp['actual'])
Browser/HTML Force download of image from src="data:image/jpeg;base64..."
Simply replace image/jpeg
with application/octet-stream
. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.
A simple JavaScript solution would be:
//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element,
Another method is to use a blob:
URI:
var img = document.images[0];
img.onclick = function() {
   // atob to base64_decode the data-URI
   var image_data = atob(img.src.split(',')[1]);
// Use typed arrays to convert the binary data to a Blob
   var arraybuffer = new ArrayBuffer(image_data.length);
   var view = new Uint8Array(arraybuffer);
   for (var i=0; i<image_data.length; i++) {
     view[i] = image_data.charCodeAt(i) & 0xff;
   }
try {
// This is the recommended method:
var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
} catch (e) {
// The BlobBuilder API has been deprecated in favour of Blob, but older
// browsers don't know about the Blob constructor
// IE10 also supports BlobBuilder, but since the `Blob` constructor
// also works, there's no need to add `MSBlobBuilder`.
var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
   bb.append(arraybuffer);
   var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
}
// Use the URL object to create a temporary URL
  var url = (window.webkitURL || window.URL).createObjectURL(blob);
   location.href = url; // <-- Download!
};
Relevant documentation
What is VanillaJS?
Using "VanillaJS" means using plain JavaScript without any additional libraries like jQuery.
People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries.
Here's a funny site that jokingly talks about this: http://vanilla-js.com/
How to search for a string in an arraylist
The Best Order I've seen :
// SearchList is your List
// TEXT is your Search Text
// SubList is your result
ArrayList<String> TempList = new ArrayList<String>(
(SearchList));
int temp = 0;
int num = 0;
ArrayList<String> SubList = new ArrayList<String>();
while (temp > -1) {
temp = TempList.indexOf(new Object() {
@Override
public boolean equals(Object obj) {
return obj.toString().startsWith(TEXT);
}
});
if (temp > -1) {
SubList.add(SearchList.get(temp + num++));
TempList.remove(temp);
}
}
Wildcards in a Windows hosts file
I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.
If you read the man page, it says:
DESCRIPTION
The hosts file contains information regarding the known hosts on the net-
work. For each host a single line should be present with the following
information:
Internet address
Official host name
Aliases
Although it does say,
Host names may contain any printable character other than a field delim-
iter, newline, or comment character.
that is not true from a practical level.
Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.
The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.
How to: Install Plugin in Android Studio
- Launch Android Studio application
- Choose Project Settings
- Choose Plugin from disk, if on disk then choose that location of *.jar, in my case is GenyMotion jar
- Click on Apply and OK.
- Then Android studio will ask for Restart.
That's all Folks!
Python Flask, how to set content type
I like and upvoted @Simon Sapin's answer. I ended up taking a slightly different tack, however, and created my own decorator:
from flask import Response
from functools import wraps
def returns_xml(f):
@wraps(f)
def decorated_function(*args, **kwargs):
r = f(*args, **kwargs)
return Response(r, content_type='text/xml; charset=utf-8')
return decorated_function
and use it thus:
@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
xml = 'foo'
return xml
I think this is slightly more comfortable.
How to detect the physical connected state of a network cable/connector?
tail -f /var/log/syslog | grep -E 'link (up|down)'
or for me faster gets:
tail -f /var/log/syslog | grep 'link \(up\|down\)'
It will listen to the syslog file.
Result (if disconnect and after 4 seconds connect again):
Jan 31 13:21:09 user kernel: [19343.897157] r8169 0000:06:00.0 enp6s0: link down
Jan 31 13:21:13 user kernel: [19347.143506] r8169 0000:06:00.0 enp6s0: link up
How to pass parameters to a Script tag?
Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.
Stop a gif animation onload, on mouseover start the activation
I realise this answer is late, but I found a rather simple, elegant, and effective solution to this problem and felt it necessary to post it here.
However one thing I feel I need to make clear is that this doesn't start gif animation on mouseover, pause it on mouseout, and continue it when you mouseover it again. That, unfortunately, is impossible to do with gifs. (It is possible to do with a string of images displayed one after another to look like a gif, but taking apart every frame of your gifs and copying all those urls into a script would be time consuming)
What my solution does is make an image looks like it starts moving on mouseover. You make the first frame of your gif an image and put that image on the webpage then replace the image with the gif on mouseover and it looks like it starts moving. It resets on mouseout.
Just insert this script in the head section of your HTML:
$(document).ready(function()
{
$("#imgAnimate").hover(
function()
{
$(this).attr("src", "GIF URL HERE");
},
function()
{
$(this).attr("src", "STATIC IMAGE URL HERE");
});
});
And put this code in the img tag of the image you want to animate.
id="imgAnimate"
This will load the gif on mouseover, so it will seem like your image starts moving. (This is better than loading the gif onload because then the transition from static image to gif is choppy because the gif will start on a random frame)
for more than one image just recreate the script create a function:
<script type="text/javascript">
var staticGifSuffix = "-static.gif";
var gifSuffix = ".gif";
$(document).ready(function() {
$(".img-animate").each(function () {
$(this).hover(
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(staticGifSuffix, gifSuffix));
},
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(gifSuffix, staticGifSuffix));
}
);
});
});
</script>
</head>
<body>
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
</body>
That code block is a functioning web page (based on the information you have given me) that will display the static images and on hover, load and display the gif's. All you have to do is insert the url's for the static images.
How to use custom packages
For a project hosted on GitHub, here's what people usually do:
github.com/
laike9m/
myproject/
mylib/
mylib.go
...
main.go
mylib.go
package mylib
...
main.go
import "github.com/laike9m/myproject/mylib"
...
What is a 'Closure'?
In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.
def n_times(a_thing)
return lambda{|n| a_thing * n}
end
in the above code, lambda(|n| a_thing * n}
is the closure because a_thing
is referred by the lambda (an anonymous function creator).
Now, if you put the resulting anonymous function in a function variable.
foo = n_times(4)
foo will break the normal scoping rule and start using 4 internally.
foo.call(3)
returns 12.
Set the Value of a Hidden field using JQuery
If you have a hidden field like this
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>
Now you can use your value like this
$(this).parent().find('input[type=hidden]').val()
Spring Boot not serving static content
This solution works for me:
First, put a resources folder under webapp/WEB-INF, as follow structure
-- src
-- main
-- webapp
-- WEB-INF
-- resources
-- css
-- image
-- js
-- ...
Second, in spring config file
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resource/**").addResourceLocations("WEB-INF/resources/");
}
}
Then, you can access your resource content, such as
http://localhost:8080/resource/image/yourimage.jpg
How do I fix maven error The JAVA_HOME environment variable is not defined correctly?
This is how I fixed this issue on Windows 10:
My JDK is located in C:\Program Files\Java\jdk-11.0.2
and the problem I had was the space in Program Files
. If I set JAVA_HOME using set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
then Maven had an issue with the double quotes:
C:\Users>set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
C:\Users>echo %JAVA_HOME%
"C:\Program Files\Java\jdk-11.0.2"
C:\Users>mvn -version
Files\Java\jdk-11.0.2""=="" was unexpected at this time.
Referring to Program Files
as PROGRA~1
didn't help either. The solution is using the PROGRAMFILES variable inside of JAVA_HOME:
C:\Users>echo %PROGRAMFILES%
C:\Program Files
C:\Program Files>set JAVA_HOME=%PROGRAMFILES%\Java\jdk-11.0.2
C:\Program Files>echo %JAVA_HOME%
C:\Program Files\Java\jdk-11.0.2
C:\Program Files>mvn -version
Apache Maven 3.6.2 (40f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T17:06:16+02:00)
Maven home: C:\apache-maven-3.6.2\bin\..
Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-11.0.2
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
Apache server keeps crashing, "caught SIGTERM, shutting down"
from this page:
I found this info:
The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.
What this implies to me is that if Database I/O, or some other part of the CGI script, fails to respond in a timely fashion (ie getting slower with data-volume growth), that mod_fastcgi is killing the script......is that how other people interpret these docs or what am I missing..
Sleep function in ORACLE
If executed within "sqlplus", you can execute a host operating system command "sleep" :
!sleep 1
or
host sleep 1
Stateless vs Stateful
Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...
HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...
Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...
Python 3 print without parenthesis
Although you need a pair of parentheses to print in Python 3, you no longer need a space after print
, because it's a function. So that's only a single extra character.
If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print
and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print
shortcut in Python 3.
Python 2:
>>> p = print
File "<stdin>", line 1
p = print
^
SyntaxError: invalid syntax
Python 3:
>>> p = print
>>> p('hello')
hello
It'll make your code less readable, but you'll save those few characters every time you print something.
How to change workspace and build record Root Directory on Jenkins?
The variables you need are explained here in the jenkins wiki: https://wiki.jenkins.io/display/JENKINS/Features+controlled+by+system+properties
The default variable ITEM_ROOTDIR points to a directory inside the jenkins installation. As you already found out you need:
- Workspace Root Directory:
E:/myJenkinsRootFolderOnE/${ITEM_FULL_NAME}/workspace
- Build Record Root Directory: E:/myJenkinsRootFolderOnE/${ITEM_FULL_NAME}/builds
You need to achieve this through config.xml nowerdays. Citing from the wiki page linked above:
This used to be a UI setting, but was removed in 2.119 as it did not
support migration of existing build records and could lead to
build-related errors until restart.
xlsxwriter: is there a way to open an existing worksheet in my workbook?
After searching a bit about the method to open the existing sheet in xlxs, i discovered
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
You can now append/write any data to the open worksheet.
I hope it helps.
Thanks
Attempt to set a non-property-list object as an NSUserDefaults
I had this problem trying save a dictionary to NSUserDefaults
. It turns out it wouldn't save because it contained NSNull
values. So I just copied the dictionary into a mutable dictionary removed the nulls then saved to NSUserDefaults
NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary_trying_to_save];
[dictionary removeObjectForKey:@"NullKey"];
[[NSUserDefaults standardUserDefaults] setObject:dictionary forKey:@"key"];
In this case I knew which keys might be NSNull
values.
Convert Python dictionary to JSON array
ensure_ascii=False really only defers the issue to the decoding stage:
>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte
Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.
>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',}
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}
Java sending and receiving file (byte[]) over sockets
Here is the server
Open a stream to the file and send it overnetwork
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 5501;
public final static String FILE_TO_SEND = "file.txt";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
} catch (IOException ex) {
System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
}
}finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null)
servsock.close();
}
}
}
Here is the client
Recive the file being sent overnetwork
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 5501;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "file-rec.txt";
public final static int FILE_SIZE = Integer.MAX_VALUE;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
Setting Environment Variables for Node to retrieve
As expansion of @ctrlplusb answer,
I would suggest you to also take a look to the env-dot-prop
package.
It allows you to set/get properties from process.env
using a dot-path
.
Let's assume that your process.env
contains the following:
process.env = {
FOO_BAR: 'baz'
'FOO_': '42'
}
Then you can manipulate the environment variables like that:
const envDotProp = require('env-dot-prop');
console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42'}
envDotProp.get('foo');
//=> {bar: 'baz', '': '42'}
envDotProp.get('foo.');
//=> '42'
envDotProp.get('foo.', {parse: true});
//=> 42
envDotProp.set('baz.foo', 'bar');
envDotProp.get('', {parse: true});
//=> {foo: {bar: 'baz', '': 42}, baz: {foo: 'bar'}}
console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42', BAZ_FOO: 'bar'}
envDotProp.delete('foo');
envDotProp.get('');
//=> {baz: {foo: 'bar'}}
console.log(process.env);
//=> {BAZ_FOO: 'bar'}
This helps you to parse the environment variables and use them as a config object in your app.
It also helps you implement a 12-factor configuration.
How to pass parameters to maven build using pom.xml?
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me.
Thanks
SQL Server: Invalid Column Name
Following procedure helped me solve this issue but i don't know why.
- Cut the code in question given by the lines in the message
- Save the query (e.g. to file)
- Paste the code to where it was before
- Again save the query
Even if it seems to be the same query executing it did not throw this error
PHP MySQL Google Chart JSON - Complete Example
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be:
replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes
--> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
TypeError: 'dict_keys' object does not support indexing
Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:
next(iter(keys))
Or, if you want to iterate over all items, you can use:
items = iter(keys)
while True:
try:
item = next(items)
except StopIteration as e:
pass # finish
method in class cannot be applied to given types
generateNumbers()
expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
How do I UPDATE a row in a table or INSERT it if it doesn't exist?
If you're OK with using a library that writes the SQL for you, then you can use Upsert (currently Ruby and Python only):
Pet.upsert({:name => 'Jerry'}, :breed => 'beagle')
Pet.upsert({:name => 'Jerry'}, :color => 'brown')
That works across MySQL, Postgres, and SQLite3.
It writes a stored procedure or user-defined function (UDF) in MySQL and Postgres. It uses INSERT OR REPLACE
in SQLite3.
Connect to external server by using phpMyAdmin
at version 4.0 or above, we need to create one 'config.inc.php' or rename the 'config.sample.inc.php' to 'config.inc.php';
In my case, I also work with one mysql server for each environment (dev and production):
/* others code*/
$whoIam = gethostname();
switch($whoIam) {
case 'devHost':
$cfg['Servers'][$i]['host'] = 'localhost';
break;
case 'MasterServer':
$cfg['Servers'][$i]['host'] = 'masterMysqlServer';
break;
} /* others code*/
How to find the process id of a running Java process on Windows? And how to kill the process alone?
This is specific to Windows.
I was facing the same issue where I have to kill one specific java program using taskkill. When I run the java program, tasklist was showing the same program with Image name set as java.exe.
But killing it using taskkill /F java.exe
will stop all other java applications other than intended one which is not required.
So I run the same java program using:
start "MyProgramName" java java-program..
Here start command will open a new window and run the java program with window's title set to MyProgramName.
Now to kill this java-program use the following taskkill command:
taskkill /fi "MyProgramName"
Your Java program will be killed only. Rest will be unaffected.
How to save password when using Subversion from the console
In ~/.subversion/config
, you probably have store-passwords = no
. Change it to yes
(or just comment it out because it defaults to yes), and the next time you give Subversion your password it should save it.
You might want to ensure that the owner and permissions of ~/.subversion/config
are correct (no public or group access; 600).
do <something> N times (declarative syntax)
Given a function something
:
function something() { console.log("did something") }
And a new method times
added to the Array
prototype:
Array.prototype.times = function(f){
for(v of this)
for(var _ of Array(v))
f();
}
This code:
[1,2,3].times(something)
Outputs this:
did something
did something
did something
did something
did something
did something
Which I think answers your updated question (5 years later) but I wonder how useful it is to have this work on an array? Wouldn't the effect be the same as calling [6].times(something)
, which in turn could be written as:
for(_ of Array(6)) something();
(although the use of _
as a junk variable will probably clobber lodash or underscore if you're using it)
How to use Google fonts in React.js?
If anyone looking for a solution with (.less) try below. Open your main or common less file and use like below.
@import (css) url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
body{
font-family: "Open Sans", sans-serif;
}
Node - how to run app.js?
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
New lines inside paragraph in README.md
Interpreting newlines as <br />
used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.
Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change
a
b
c
into
a__
b__
c
(where _
is a blank space).
Or, you can add explicit <br />
tags.
a <br />
b <br />
c
jQuery - Increase the value of a counter when a button is clicked
I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.
$(document).ready(function() {
$("#image1").onfocus(function() {
var count;
if (count == undefined || count == "" || count == 0) {
var count = 0;
}
count++;
$("#counter1").html("Image Views: " + count);
}
});
Then, outside the script tags and in the desired place in the body I'll add:
<div id="counter1"></div>
How to POST JSON Data With PHP cURL?
Try this example.
<?php
$url = 'http://localhost/test/page2.php';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$ch=curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Your page2.php code
<?php
$datastring = $_POST['customer'];
$data = json_decode( urldecode( $datastring));
?>
How to display UTF-8 characters in phpMyAdmin?
The function and file names don't match those in newer versions of phpMyAdmin. Here is how to fix in the newer PHPMyAdmins:
Find file:
phpmyadmin/libraries/DatabaseInterface.php
In function: public function query
Right after the opening {
add this:
if($link != null){
mysqli_query($link, "SET SESSION CHARACTER_SET_RESULTS =latin1;");
mysqli_query($link, "SET SESSION CHARACTER_SET_CLIENT =latin1;");
}
That's it. Works like a charm.
No Android SDK found - Android Studio
These days, Android Studio setup do not provide SDK as the part of original package.
In the context of windows, when you start Android Studio 1.3.1, you see the error message saying no sdk found. You just have to proceed and provide the path where sdk can be downloaded. And you are done.
Setting PayPal return URL and making it auto return?
Sharing this as I've recently encountered issues similar to this thread
For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !
The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.
Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.
Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!
You may also find this helpful
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Why does IE9 switch to compatibility mode on my website?
As an aside on more modern websites, if you are using conditional statements on your html tag as per boilerplate, this will for some reason cause ie9 to default to compatibility mode. The fix here is to move your conditional statements off the html tag and add them to the body tag, in other words out of the head section. That way you can still use those classes in your style sheet to target older browsers.
How do I loop through rows with a data reader in C#?
There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
string value1 = rdr.GetString(0);
string value2 = rdr.GetString(1);
string value3 = rdr.GetString(2);
}
}
What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....
using extern template (C++11)
Wikipedia has the best description
In C++03, the compiler must instantiate a template whenever a fully specified template is
encountered in a translation unit. If the template is instantiated with the same types in
many translation units, this can dramatically increase compile times. There is no way to
prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern
data declarations.
C++03 has this syntax to oblige the compiler to instantiate a template:
template class std::vector<MyClass>;
C++11 now provides this syntax:
extern template class std::vector<MyClass>;
which tells the compiler not to instantiate the template in this translation unit.
The warning: nonstandard extension used...
Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.
Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.
What is the correct way to do a CSS Wrapper?
Centering content has so many avenues that it can't really be explored in a single answer. If you would like to explore them, CSS Zen Garden is an enjoyable-if-old resource exploring the many, many ways to layout content in a way even old browsers will tolerate.
The correct way, if you don't have any mitigating requirements, is to just apply margin: auto
to the sides, and a width
. If your page has no content that needs to go outside those margins, just apply it to the body:
body {
padding: 0;
margin: 15px auto;
width: 500px;
}
https://jsfiddle.net/b9chris/62wgq8nk/
So here we've got a 500px wide set of content centered at all* sizes. The padding 0 is to deal with some browsers that like to apply some default padding and throw us off a bit. In the example I do wrap the content in an article
tag to be nice to Screen Readers, Pocket, etc so for example the blind can jump past the nav you likely have (which should be in nav
) and straight to the content.
I say all* because below 500px this will mess up - we're not being Responsive. To get Responsive, you could just use Bootstrap etc, but building it yourself you use a Media Query like:
body {
padding: 0;
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
Note that this is SCSS/SASS syntax - if you're using plain CSS, it's inverted:
body {
padding: 0;
margin: 15px;
}
@media (min-width: 500px) {
body {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/6/
It's common however to want to center just one chunk of a page, so let's apply this to only the article tag in a final example.
body {
padding: 0;
margin: 0;
}
nav {
width: 100%;
box-sizing: border-box;
padding: 15px;
}
article {
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/17/
Note that this final example also uses CSS Flexbox in the nav, which is also one of the newer ways you could center things. So, that's fun.
But, there are special circumstances where you need to use other approaches to center content, and each of those is probably worth its own question (many of them already asked and answered here on this site).
git replace local version with remote version
I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).
Simply do
git checkout remote/branch -- a/file b/another/file
If you want to do this for extensive subtrees and instead wish to affect the index directly use
git read-tree remote/branch:subdir/
You can then (optionally) update your working copy by doing
git checkout-index -u --force
MySQL show current connection info
You can use the status command in MySQL client.
mysql> status;
--------------
mysql Ver 14.14 Distrib 5.5.8, for Win32 (x86)
Connection id: 1
Current database: test
Current user: ODBC@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.5.8 MySQL Community Server (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: gbk
Conn. characterset: gbk
TCP port: 3306
Uptime: 7 min 16 sec
Threads: 1 Questions: 21 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.48
--------------
mysql>
Add quotation at the start and end of each line in Notepad++
- Place your cursor at the end of the text.
- Press SHIFT and ->. The cursor will move to the next line.
- Press CTRL-F and type , in "Replace with:" and press ENTER.
You will need to put a quote at the beginning of your first text and the end of your last.
I have never set any passwords to my keystore and alias, so how are they created?
All these answers and there is STILL just one missing. When you create your auth credential in the Google API section of the dev console, make sure (especially if it is your first one) that you have clicked on the 'consent screen' option. If you don't have the 'title' and any other required field filled out the call will fail with this option.
Attach the Java Source Code
Hold ctrl key and then click on class of which you want to see the inner working (for ex: String
) then you will find there button "Attach Source". Click on it. Then click on External Folder. Then browse to your jdk location, per instance C:\Program Files\Java\jdk1.6.0
. That's it.
How to get the first non-null value in Java?
How about:
firstNonNull = FluentIterable.from(
Lists.newArrayList( a, b, c, ... ) )
.firstMatch( Predicates.notNull() )
.or( someKnownNonNullDefault );
Java ArrayList conveniently allows null entries and this expression is consistent regardless of the number of objects to be considered. (In this form, all the objects considered need to be of the same type.)
Automapper missing type map configuration or unsupported mapping - Error
I know this is a rather old question as of now, but I had found the proper solution was that I was not declaring the assembly attribute.
My code is:
using AutoMapper;
...
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
This was fixed by adding the following line before my namespace declaration:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
The full code is:
using AutoMapper;
...
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
Angular2 module has no exported member
You do not need the line:
import { SigninComponent, RegisterComponent } from './auth/auth.module';
in your app.component.ts
as you already included the AuthModule
in your app.module.ts
. AutModule
import is sufficient to use your component in the app.
The error that you get is a TypeScript error, not a Angular one, and it is correct in stating that there is no exported member, as it searches for a valid EC6 syntax for export, not angular module export. This line would thus work in your app.component.ts
:
import { SigninComponent } from './auth/components/signin.component';
Call a function on click event in Angular 2
Exact transfer to Angular2+ is as below:
<button (click)="myFunc()"></button>
also in your component file:
import { Component, OnInit } from "@angular/core";
@Component({
templateUrl:"button.html" //this is the component which has the above button html
})
export class App implements OnInit{
constructor(){}
ngOnInit(){
}
myFunc(){
console.log("function called");
}
}
How to make a transparent HTML button?
The solution is pretty easy actually:
<button style="border:1px solid black; background-color: transparent;">Test</button>
This is doing an inline style. You're defining the border to be 1px, solid line, and black in color. The background color is then set to transparent.
UPDATE
Seems like your ACTUAL question is how do you prevent the border after clicking on it. That can be resolved with a CSS pseudo selector: :active
.
button {
border: none;
background-color: transparent;
outline: none;
}
button:focus {
border: none;
}
JSFiddle Demo
How do you loop in a Windows batch file?
Conditionally perform a command several times.
syntax-FOR-Files
FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
FOR /F ["options"] %%parameter IN (filenameset) DO command
or
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
syntax-FOR-Command Results
FOR /F ["options"] %%parameter IN ('command to process') DO command
It
- Take a set of data
- Make a FOR Parameter
%%G
equal to some part of that data
- Perform a command (optionally using the parameter as part of the command).
- --> Repeat for each item of data
If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G
instead of %%G
.
FOR Parameters
The first parameter has to be defined using a single character, for example the letter G.
FOR %%G IN
...
In each iteration of a FOR loop, the IN ( ....)
clause is evaluated and %%G
set to a different value
If this clause results in a single value then %%G is set equal to that value and the command is performed.
If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J
...(implicit parameter definition)
If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.
You can of course pick any letter of the alphabet other than %%G
. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.
jQuery append and remove dynamic table row
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>`enter code here`
$(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
$('tr').each(function () {
var sum = $(this).find('td.combat').text();
var combat = $(this).find('input.combat').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total-combat').html(result);
});
});
$('.add').click(function(){
var sno = $(this).parent().siblings('.sno').text();
var cust = $(this).parent().siblings('.cust').text();
var price = $(this).parent().siblings('td.combat').text();
var rowValue = [];
$(this).closest('tr').find("input").each(function() {
rowValue.push($(this).val());
return $(this).val();
});
var rowValue1 = [];
$(this).closest('tr').find("span").each(function() {
rowValue1.push($(this).text());
return $(this).val();
});
var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";
var rightcol = $(this).closest('tr').find(".cust");
var row_count = $('.tbl1 tbody tr').length;
alert(row_count);
if (row_count == 0) {
$(".tbl1 tbody").append(markup);
}
else
{
var tes=0;
$('.tbl1 tbody tr').each(function(){
var leftcol = $(this).find(".custname");
if(rightcol.html() == leftcol.html()) {
alert(leftcol.html()+"-----------------"+rightcol.html());
$(this).find('.sno').text(sno);
$(this).find('.custname').text(cust);
$(this).find('.price').text(price);
$(this).find('.newtext').val(rowValue[0]);
$(this).find('.total').text(rowValue1[0]);
tes++;
}
});
if(tes==0){
$(".tbl1 tbody").append(markup);
}
}
});
$(".tb").on("click", ".update", function(e) {
var rowValues = [];
$(this).closest('tr').find("input").each(function() {
rowValues.push($(this).val());
return $(this).val();
});
var total=$(this).closest('tr').find('.total').text();
var right_cols = $(this).closest('tr').find(".custname");
$('.tbl tbody tr').each(function(){
var row = $(this);
var left_cols = $(this).find(".cust");
if(left_cols.html() == right_cols.html()) {
$(this).find('.text').val(rowValues[0]);
$(this).find('.total-combat').text(total);
}
});
});
$(".tb").on("keyup", "input", function() {
$('tr').each(function () {
var sum = $(this).find('td.price').text();
var combat = $(this).find('input.newtext').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total').html(result);
});
});
$(".tb").on("click", ".del", function() {
$(this).closest('tr').remove();
});
});
</script>
<style>
.table_style {
width: 500px;
margin: 0px auto;
}
table{
width: 100%;
border-collapse: collapse;
}
table tr td{
width: 50%;
border: 5px solid #ff751a;
padding: 5px;
}
table tr th{
border: 5px solid #79ff4d;
padding: 5px;
}
input{
width:35px;
}
.tbl1{
margin-top: 50px;
border: 0px solid #cdcdcd;
}
.btn{
float:left;
}
</style>
<title>E-Commerce-Table</title>
</head>
<body>
<div class="table_style">
<caption>Price-List</caption>
<table class="tbl">
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
<tbody>
<tr>
<td class="sno">1</td>
<td class="cust">A</td>
<td class="combat">5</td>
<td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">2</td>
<td class="cust">B</td>
<td class="combat">8</td>
<td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">3</td>
<td class="cust">C</td>
<td class="combat">7</td>
<td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">4</td>
<td class="cust">D</td>
<td class="combat">2</td>
<td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
</tbody>
</table>
<table class="tbl1">
<thead>
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
</thead>
<tbody class="tb">
</tbody>
</table>
<button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>
</body>
</html>
How to properly add cross-site request forgery (CSRF) token using PHP
Security Warning: md5(uniqid(rand(), TRUE))
is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.
Looks like you need an else with your if.
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
}
else
{
$token = $_SESSION['token'];
}
static files with express.js
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
Regular Expression to get all characters before "-"
This is something like the regular expression you need:
([^-]*)-
Quick tests in JavaScript:
/([^-]*)-/.exec('text-1')[1] // 'text'
/([^-]*)-/.exec('foo-bar-1')[1] // 'foo'
/([^-]*)-/.exec('-1')[1] // ''
/([^-]*)-/.exec('quux')[1] // explodes
Removing object from array in Swift 3
In Swift 3 and 4
var array = ["a", "b", "c", "d", "e", "f"]
for (index, element) in array.enumerated().reversed() {
array.remove(at: index)
}
From Swift 4.2 you can use more advanced approach(faster and memory efficient)
array.removeAll(where: { $0 == "c" })
instead of
array = array.filter { !$0.hasPrefix("c") }
Read more here
sql set variable using COUNT
You can use SELECT
as lambacck said
or add parentheses:
SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');