Getting visitors country from their IP
I have a short answer which I have used in a project.
In my answer, I consider that you have visitor IP address.
$ip = "202.142.178.220";
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
//get ISO2 country code
if(property_exists($ipdat, 'geoplugin_countryCode')) {
echo $ipdat->geoplugin_countryCode;
}
//get country full name
if(property_exists($ipdat, 'geoplugin_countryName')) {
echo $ipdat->geoplugin_countryName;
}
How to allow CORS in react.js?
Suppose you want to hit https://yourwebsitedomain/app/getNames from http://localhost:3000 then just make the following changes:
packagae.json :
"name": "version-compare-app",
"proxy": "https://yourwebsitedomain/",
....
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
...
In your component use it as follows:
import axios from "axios";
componentDidMount() {
const getNameUrl =
"app/getNames";
axios.get(getChallenge).then(data => {
console.log(data);
});
}
Stop your local server and re run npm start. You should be able to see the data in browser's console logged
Run certain code every n seconds
def update():
import time
while True:
print 'Hello World!'
time.sleep(5)
That'll run as a function. The while True:
makes it run forever. You can always take it out of the function if you need.
Volley - POST/GET parameters
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder
and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8"));
to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams()
method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
Most efficient method to groupby on an array of objects
You can do it with Alasql JavaScript library:
var data = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }];
var res = alasql('SELECT Phase, Step, SUM(CAST([Value] AS INT)) AS [Value] \
FROM ? GROUP BY Phase, Step',[data]);
Try this example at jsFiddle.
BTW: On large arrays (100000 records and more) Alasql faster tham Linq. See test at jsPref.
Comments:
- Here I put Value in square brackets, because VALUE is a keyword in SQL
- I have to use CAST() function to convert string Values to number type.
What is the difference between JavaScript and ECMAScript?
What is ECMAScript i.e. ES?
ECMAScript is a standard for a scripting language and the
Javascript language is based on the ECMAScript standard.
Is Javascript exactly the same as ECMAScript?
- No, Javascript is not exactly equivalent to ECMAScript.
- The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard.
JavaScript = ECMAScript + DOM API;
DOM API like: document.getElementById('id');
Do other languages use the ECMAScript standard?
- Yes, there are languages other than JavaScript that also implement the ECMAScript Standard as their core.
- ActionScript (used by Adobe Flash) and JScript (used by Microsoft) are both languages that implement the ECMAScript standard.
Why is it called ECMAScript?
- Javascript was originally created at Netscape, and they wanted to standardize the language. So, they submitted the language to the European Computer Manufacturer’s Association (ECMA) for standardization.
- But, there were trademark issues with the name Javascript, and the standard became called ECMAScript, which is the name it holds today as well.
- Because of trademark issues, Microsoft’s version of the language is called JScript – even though JScript is, at its core, the same language as Javascript.
Catch a thread's exception in the caller thread in Python
What im doing is, simple overriding join and run method of the Thread:
class RaisingThread(threading.Thread):
def run(self):
self._exc = None
try:
super().run()
except Exception as e:
self._exc = e
def join(self):
super().join()
if self._exc:
raise self._exc
Used as followed:
def foo():
time.sleep(2)
print('hi, from foo!')
raise Exception('exception from foo')
t = RaisingThread(target=foo)
t.start()
try:
t.join()
except Exception as e:
print(e)
Result:
hi, from foo!
exception from foo!
Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
I've wrote such a simple class:
public static class WatermarkExtension
{
public static MvcHtmlString WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var watermark = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
var htmlEncoded = HttpUtility.HtmlEncode(watermark);
return new MvcHtmlString(htmlEncoded);
}
}
The usage as such:
@Html.TextBoxFor(model => model.AddressSuffix, new {placeholder = Html.WatermarkFor(model => model.AddressSuffix)})
And property in a viewmodel:
[Display(ResourceType = typeof (Resources), Name = "AddressSuffixLabel", Prompt = "AddressSuffixPlaceholder")]
public string AddressSuffix
{
get { return _album.AddressSuffix; }
set { _album.AddressSuffix = value; }
}
Notice Prompt parameter. In this case I use strings from resources for localization but you can use just strings, just avoid ResourceType parameter.
Securely storing passwords for use in python script
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
How do I get a list of all subdomains of a domain?
If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.
How to embed a YouTube channel into a webpage
In order to embed your channel, all you need to do is copy then paste the following code in another web-page.
<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
Make sure to replace the YourChannelName with your actual channel name.
For example: if your channel name were CaliChick94066 your channel embed code would be:
<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
Please look at the following links:
YouTube on your site
Embed YouTube Channel
You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps
How to justify a single flexbox item (override justify-content)
If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.
_x000D_
_x000D_
.space-between {_x000D_
border: 1px solid red;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
border: 1px solid blue;_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
<div class="child">1</div>_x000D_
<div class="default-flex">_x000D_
<div class="child">2</div>_x000D_
<div class="child">3</div>_x000D_
<div class="child">4</div>_x000D_
<div class="child">5</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.
Python 2,3 Convert Integer to "bytes" Cleanly
Answer 1:
To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encode
method. If you don't supply an encoding parameter 'ascii'
is used, which will always be good enough for numeric digits.
s = str(n).encode()
In Python 2 str(n)
already produces bytes; the encode
will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.
Answer 2:
Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I'll answer that question too. If you want to convert 10
to b'10'
use the answer above, but if you want to convert 10
to b'\x0a\x00\x00\x00'
then keep reading.
The struct
module was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack
. There's a format parameter fmt
that determines which conversion it should perform. For a 4-byte integer, that would be i
for signed numbers or I
for unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.
import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'
Display A Popup Only Once Per User
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
Check if a string matches a regex in Bash script
You can use the test construct, [[ ]]
, along with the regular expression match operator, =~
, to check if a string matches a regex pattern.
For your specific case, you can write:
[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
Or more a accurate test:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
# | | ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ |
# | | | | |
# | | \ | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 end of line
# start of line or 10,11,12 or 10..29
# or 30, 31
That is, you can define a regex in Bash matching the format you want. This way you can do:
[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
where commands after &&
are executed if the test is successful, and commands after ||
are executed if the test is unsuccessful.
Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
In other shells you can use grep. If your shell is POSIX compliant, do
(echo "$date" | grep -Eq ^regex$) && echo "matched" || echo "did not match"
In fish, which is not POSIX-compliant, you can do
echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"
How do I get the value of text input field using JavaScript?
If your input
is in a form
and you want to get value after submit you can do like
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
Benefit of this way: Example your page have 2 form
for input sender
and receiver
information.
If you don't use form
for get value then
- You can set 2 different id
(or tag
or name
...) for each field like sender-name
and receiver-name
, sender-address
and receiver-address
, ...
- If you set same value for 2 input, then after getElementsByName
(or getElementsByTagName
...) you need to remember 0 or 1 is sender
or receiver
. Later if you change the order of 2 form
in html, you need to check this code again
If you use form
, then you can use name
, address
, ...
twig: IF with multiple conditions
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
I found elegant work around for me to remove symbols and continue to keep string as string in follows:
yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')
It's important to notice that using the ignore option is dangerous because it silently drops any unicode(and internationalization) support from the code that uses it, as seen here (convert unicode):
>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'
HTML5 video won't play in Chrome only
Try this
<video autoplay loop id="video-background" muted plays-inline>
<source src="https://player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761" type="video/mp4">
</video>
Thanks
how to convert image to byte array in java?
BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.
if you want the data from DataBufferByte, use:
public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
now you can process these bytes by hiding text in lsb for example, or process it the way you want.
How do I scroll to an element using JavaScript?
You can use an anchor to "focus" the div. I.e:
<div id="myDiv"></div>
and then use the following javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
Request Monitoring in Chrome
Open up your DevTools and press F1 to access the settings. Look for the console section and check the checkbox for "Log XMLHttpRequests".
Now all of your ajax and other similar requests will be logged in the console.
I prefer this method because it usually allows me to see everything that I'm looking for in the console without having to go to the network tab.
Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
In Xcode 8.0 you can simply do it by changing insets
in size inspector.
Select the UIButton -> Attributes Inspector -> go to size inspector and modify the content, image and title insets.
And if you want to change image on right side you can simply change the semantic property to Force Right-to-left
in Attribute inspector .
Capturing "Delete" Keypress with jQuery
event.key === "Delete"
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (.keyCode
and .which
) are Deprecated.
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Delete") {
// Do things
}
});
Mozilla Docs
Supported Browsers
WPF MVVM: How to close a window
I just completed a blog post on this very topic. In a nutshell, add an Action
property to your ViewModel with get
and set
accessors. Then define the Action
from your View
constructor. Finally, invoke your action in the bound command that should close the window.
In the ViewModel:
public Action CloseAction { get; set;}
and in the View
constructor:
private View()
{
InitializeComponent();
ViewModel vm = new ViewModel();
this.DataContext = vm;
if ( vm.CloseAction == null )
vm.CloseAction = new Action(this.Close);
}
Finally, in whatever bound command that should close the window, we can simply invoke
CloseAction(); // Calls Close() method of the View
This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.
npm - how to show the latest version of a package
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
glob exclude pattern
Compare with glob
, I recommend pathlib
, filter one pattern is very simple.
from pathlib import Path
p = Path(YOUR_PATH)
filtered = [x for x in p.glob("**/*") if not x.name.startswith("eph")]
and if you want to filter more complex pattern, you can define a function to do that, just like:
def not_in_pattern(x):
return (not x.name.startswith("eph")) and not x.name.startswith("epi")
filtered = [x for x in p.glob("**/*") if not_in_pattern(x)]
use that code, you can filter all files that start with eph
or start with epi
.
How can I permanently enable line numbers in IntelliJ?
IntelliJ IDEA 15
5 approaches
Global change
File > Settings... > Editor > General > Appearance > Show line numbers
Hit Shift twice > write "line numbers" > Show Line Numbers (that one that has the toggle) > change the toggle to ON
Change for the Active Editor
Right click on the left side bar > Show Line Numbers
Hit Shift twice > write "line" > Show Line Numbers (the line doesn't have the toggle)
Ctrl + Shift + A > write "Show line" > Active Editor: Show Line Numbers > change the toggle to ON
Boolean operators && and ||
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, &&
and ||
only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{}
construction and to direct program control rather than construct new vectors.. The &
and the |
operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to &&
or ||
are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
MongoDB: Is it possible to make a case-insensitive query?
You can use Case Insensitive Indexes:
The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode
/* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
To use the index, queries must specify the same collation.
db.users.insert( [ { name: "Oguz" },
{ name: "oguz" },
{ name: "OGUZ" } ] )
// does not use index, finds one result
db.users.find( { name: "oguz" } )
// uses the index, finds three results
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 2 } )
// does not use the index, finds three results (different strength)
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 1 } )
or you can create a collection with default collation:
db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation
How to extract a single value from JSON response?
Only suggestion is to access your resp_dict
via .get()
for a more graceful approach that will degrade well if the data isn't as expected.
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
Number of regex matches
For those moments when you really want to avoid building lists:
import re
import operator
from functools import reduce
count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string)))
Sometimes you might need to operate on huge strings. This might help.
How to add a ScrollBar to a Stackpanel
It works like this:
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
<StackPanel Name="stackPanel1" Width="311">
</StackPanel>
</ScrollViewer>
TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);
Freeze screen in chrome debugger / DevTools panel for popover inspection?
UPDATE:
As Brad Parks wrote in his comment there is a much better and easier solution with only one line of JS code:
run setTimeout(function(){debugger;},5000);
, then go show your element and wait until it breaks into the Debugger
Original answer:
I just had the same problem, and I think I found an "universal" solution. (assuming the site uses jQuery)
Hope it helps someone!
- Go to elements tab in inspector
- Right click
<body>
and click "Edit as HTML"
- Add the following element after
<body>
then press Ctrl+Enter:
<div id="debugFreeze" data-rand="0"></div>
- Right click this new element, and select "Break on..." -> "Attributes modifications"
- Now go to Console view and run the following command:
setTimeout(function(){$("#debugFreeze").attr("data-rand",Math.random())},5000);
- Now go back to the browser window and you have 5 seconds to find your element and click/hover/focus/etc it, before the breakpoint will be hit and the browser will "freeze".
- Now you can inspect your clicked/hovered/focused/etc element in peace.
Of course you can modify the javascript and the timing, if you get the idea.
java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
Make div (height) occupy parent remaining height
Abstract
I didn't find a fully satisfying answer so I had to find it out myself.
My requirements:
- the element should take exactly the remaining space either when its content size is smaller or bigger than the remaining space size (in the second case scrollbar should be shown);
- the solution should work when the parent height is computed, and not specified;
calc()
should not be used as the remaining element shouldn't know anything about another element sizes;
- modern and familar layout technique such as flexboxes should be used.
The solution
- Turn into flexboxes all direct parents with computed height (if any) and the next parent whose height is specified;
- Specify
flex-grow: 1
to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;
- Specify
flex-shrink: 0
to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;
- Specify
overflow: hidden
to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;
- Specify
overflow: auto
to the element to enable scrolling inside it.
JSFiddle (element has direct parents with computed height)
JSFiddle (simple case: no direct parents with computed height)
Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=
equivalent of vbCrLf in c#
try this:
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);
or
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);
How do I get an object's unqualified (short) class name?
Quoting php.net:
On Windows, both slash (/) and backslash () are used as directory separator character. In other environments, it is the forward slash (/).
Based on this info and expanding from arzzzen answer this should work on both Windows and Nix* systems:
<?php
if (basename(str_replace('\\', '/', get_class($object))) == 'Name') {
// ... do this ...
}
Note: I did a benchmark of ReflectionClass
against basename+str_replace+get_class
and using reflection is roughly 20% faster than using the basename approach, but YMMV.
Adding extra zeros in front of a number using jQuery?
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
How to update Ruby with Homebrew?
To upgrade Ruby with rbenv: Per the rbenv README
- Update first:
brew upgrade rbenv ruby-build
- See list of Ruby versions: versions available:
rbenv install -l
- Install:
rbenv install <selected version>
Get current value when change select option - Angular2
For me, passing ($event.target.value) as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2
<select (change)="onItemChange($event.value)">
<option *ngFor="#value of values" [value]="value.key">
{{value.value}}
</option>
</select>
compareTo() vs. equals()
The 2 main differences are that:
equals
will take any Object as a parameter, but compareTo
will only take Strings.
equals
only tells you whether they're equal or not, but compareTo
gives information on how the Strings compare lexicographically.
I took a look at the String class code, and the algorithm within compareTo and equals looks basically the same. I believe his opinion was just a matter of taste, and I agree with you -- if all you need to know is the equality of the Strings and not which one comes first lexicographically, then I would use equals
.
How to draw a line in android
this code adds horizontal line to a linear layout
View view = new View(this);
LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1); // --> horizontal
view.setLayoutParams(lpView);
view.setBackgroundColor(Color.DKGRAY);
linearLayout.addView(view);
How to get the GL library/headers?
Some of the answers above, in regards to linux, are either incomplete, or flat out wrong.
For example, /usr/include/GL/gl.h is not part of mesa-common-dev or has not
been for many years.
At any rate, for a more current answer, these two packages are important:
https://mesa.freedesktop.org/archive/mesa-20.1.2.tar.xz
ftp://ftp.freedesktop.org/pub/mesa/glu/glu-9.0.1.tar.xz
The glu.h is part of glu itself:
GL/glu.h
GL/glu_mangle.h
Mesa is evidently significantly larger. Its headers are
a bit variable, I suppose, depending on the flags given
to meson, but should include these typically:
KHR/khrplatform.h
EGL/eglplatform.h
EGL/eglext.h
EGL/eglextchromium.h
EGL/eglmesaext.h
EGL/egl.h
vulkan/vulkan_intel.h
gbm.h
GLES3/gl31.h
GLES3/gl3ext.h
GLES3/gl3.h
GLES3/gl32.h
GLES3/gl3platform.h
xa_composite.h
xa_tracker.h
xa_context.h
GLES2/gl2.h
GLES2/gl2platform.h
GLES2/gl2ext.h
GLES/gl.h
GLES/glplatform.h
GLES/glext.h
GLES/egl.h
GL/gl.h
GL/glx.h
GL/osmesa.h
GL/internal
GL/internal/dri_interface.h
GL/glcorearb.h
GL/glxext.h
GL/glext.h
Hope that helps anyone finding an answer this question in
the future; compiling dosbox needs this, for instance, due
to SDL opengl.
How can I transform string to UTF-8 in C#?
Use the below code snippet to get bytes from csv file
protected byte[] GetCSVFileContent(string fileName)
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
string allines = sb.ToString();
UTF8Encoding utf8 = new UTF8Encoding();
var preamble = utf8.GetPreamble();
var data = utf8.GetBytes(allines);
return data;
}
Call the below and save it as an attachment
Encoding csvEncoding = Encoding.UTF8;
//byte[] csvFile = GetCSVFileContent(FileUpload1.PostedFile.FileName);
byte[] csvFile = GetCSVFileContent("Your_CSV_File_NAme");
string attachment = String.Format("attachment; filename={0}.csv", "uomEncoded");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
//Response.BinaryWrite(csvEncoding.GetPreamble());
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
Fetch API with Cookie
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include'
and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include'
for the first /api/auth
call too.
Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7
These steps are working on CentOS 6.5 so they should work on CentOS 7 too:
(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)
yum remove mariadb mariadb-server
rm -rf /var/lib/mysql
If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysql
rm /etc/my.cnf
the file might have already been deleted at step 1
- Optional step:
rm ~/.my.cnf
yum install mariadb mariadb-server
[EDIT] - Update for MariaDB 10.1 on CentOS 7
The steps above worked for CentOS 6.5 and MariaDB 10.
I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.
Step 1 would become:
yum remove MariaDB-server MariaDB-client
Step 5 would become:
yum install MariaDB-server MariaDB-client
The other steps remain the same.
Convert HttpPostedFileBase to byte[]
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
Force flex item to span full row width
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
_x000D_
_x000D_
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
Return index of greatest value in an array
Unless I'm mistaken, I'd say it's to write your own function.
function findIndexOfGreatest(array) {
var greatest;
var indexOfGreatest;
for (var i = 0; i < array.length; i++) {
if (!greatest || array[i] > greatest) {
greatest = array[i];
indexOfGreatest = i;
}
}
return indexOfGreatest;
}
Assign null to a SqlParameter
If you use the conditional(ternary) operator the compiler needs an implicit conversion between both types, otherwise you get an exception.
So you could fix it by casting one of both to System.Object
:
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;
But since the result is not really pretty and you always have to remember this casting, you could use such an extension method instead:
public static object GetDBNullOrValue<T>(this T val)
{
bool isDbNull = true;
Type t = typeof(T);
if (Nullable.GetUnderlyingType(t) != null)
isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
else if (t.IsValueType)
isDbNull = false;
else
isDbNull = val == null;
return isDbNull ? DBNull.Value : (object) val;
}
Then you can use this concise code:
planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();
Text not wrapping inside a div element
This may help a small percentage of people still scratching their heads. Text copied from clipboard into VSCode may have an invisible hard space character preventing wrapping. Check it with HTML inspector
Jquery Change Height based on Browser Size/Resize
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
Scrollbars etc have an effect on the window size so you may want to tweak to desired size.
OpenCV - Saving images to a particular folder of choice
Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.
Not working in Ubuntu and working in Windows
import cv2
img = cv2.imread('1.jpg', 1)
path = '/tmp'
cv2.imwrite(str(path) + 'waka.jpg',img)
cv2.waitKey(0)
I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.
Example:
import os
final_path = os.path.join(path_1,path_2,path_3......)
working in Ubuntu and Windows
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
that code works fine on both Windows and Ubuntu :)
When tracing out variables in the console, How to create a new line?
In ES6/ES2015 you can use string literal syntax called template literals. Template strings use backtick character instead of single quote ' or double quote marks ". They also preserve new line and tab
_x000D_
_x000D_
const roleName = 'test1';_x000D_
const role_ID = 'test2';_x000D_
const modal_ID = 'test3';_x000D_
const related = 'test4';_x000D_
_x000D_
console.log(`_x000D_
roleName = ${roleName}_x000D_
role_ID = ${role_ID}_x000D_
modal_ID = ${modal_ID}_x000D_
related = ${related}_x000D_
`);
_x000D_
_x000D_
_x000D_
Stop and Start a service via batch or cmd file?
Syntax always gets me.... so...
Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver
sc \\ip.ip.ip.ip stop p4_1
In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.
For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'
sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance
How to clear a chart from a canvas so that hover events cannot be triggered?
This worked very well for me
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata});
LineGraph.destroy();
Use .destroy this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.
How to return value from Action()?
You can use Func<T, TResult>
generic delegate. (See MSDN)
Func<MyType, ReturnType> func = (db) => { return new MyType(); }
Also there are useful generic delegates which considers a return value:
Converter<TInput, TOutput>
(MSDN)
Predicate<TInput>
- always return bool (MSDN)
Method:
public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)
Generic delegate:
Func<InputArgumentType, MyType> createInstance = db => return new MyType();
Execute:
MyType myTypeInstance = SimpleUsing.DoUsing(
createInstance(new InputArgumentType()));
OR explicitly:
MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());
Create an Array of Arraylists
I totally do not get it, why everyone is suggesting the genric type over the array particularly for this question.
What if my need is to index n
different arraylists.
With declaring List<List<Integer>>
I need to create n
ArrayList<Integer>
objects manually or put a for loop to create n
lists or some other way, in any way it will always be my duty to create n
lists.
Isn't it great if we declare it through casting as List<Integer>[] = (List<Integer>[]) new List<?>[somenumber]
. I see it as a good design where one do not have to create all the indexing object (arraylists) by himself
Can anyone enlighten me why this (arrayform) will be a bad design and what are its disadvantages?
cartesian product in pandas
If you have no overlapping columns, don't want to add one, and the indices of the data frames can be discarded, this may be easier:
df1.index[:] = df2.index[:] = 0
df_cartesian = df1.join(df2, how='outer')
df_cartesian.index[:] = range(len(df_cartesian))
Programmatically go back to the previous fragment in the backstack
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.
On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !
Inside activities on back pressed put this:
Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");
if (home instanceof FragmentDetailedPizza && home.isVisible()) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
//Primary fragment
moveTaskToBack(true);
}
And launch the other fragment like this:
Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();
Number of elements in a javascript object
The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.
Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.
jump to line X in nano editor
The shortcut is: CTRL+shift+- ("shift+-" results in "_")
After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.
How do I comment out a block of tags in XML?
Here for commenting we have to write like below:
<!-- Your comment here -->
Shortcuts for IntelliJ Idea and Eclipse
For Windows & Linux:
Shortcut for Commenting a single line:
Ctrl
+ /
Shortcut for Commenting multiple lines:
Ctrl
+ Shift
+ /
For Mac:
Shortcut for Commenting a single line:
cmnd
+ /
Shortcut for Commenting multiple lines:
cmnd
+ Shift
+ /
One thing you have to keep in mind that, you can't comment an attribute of an XML tag. For Example:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!--android:text="Hello.."-->
android:textStyle="bold" />
Here, TextView
is a XML Tag and text
is an attribute of that tag. You can't comment attributes of an XML Tag. You have to comment the full XML Tag. For Example:
<!--<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello.."
android:textStyle="bold" />-->
Codesign error: Provisioning profile cannot be found after deleting expired profile
I was having issues because I updated my AdHoc provisioning profile with some new devices for use on TestFlight. Assumedly this is happening because Xcode has an old reference to your provisioning profile in either the codesigning build settings for the project or the targets. The way I fixed mine was to:
- Go to both target build settings and project build settings, Under code signing change all the provisioning profiles to something else.
- Go to devices/provisioning profiles in the Organizer delete the offending profiles, then click the refresh button in the bottom right.
- Go back to to the target and project build settings and set your provisioning profiles to the appropriate (hopefully) newly refreshed provisioning profiles.
How to check if an element exists in the xml using xpath?
Use the boolean()
XPath function
The boolean function converts its
argument to a boolean as follows:
a number is true if and only if
it is neither positive or negative
zero nor NaN
a node-set is true if and only if
it is non-empty
a string is true if and only if
its length is non-zero
an object of a type other than
the four basic types is converted to a
boolean in a way that is dependent on
that type
If there is an AttachedXml in the CreditReport of primary Consumer, then it will return true()
.
boolean(/mc:Consumers
/mc:Consumer[@subjectIdentifier='Primary']
//mc:CreditReport/mc:AttachedXml)
foreach for JSON array , syntax
You can do something like
for(var k in result) {
console.log(k, result[k]);
}
which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use
typeof result[k] === "object"
to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.
What does EntityManager.flush do and why do I need to use it?
So when you call EntityManager.persist()
, it only makes the entity get managed by the EntityManager
and adds it (entity instance) to the Persistence Context
. An Explicit flush()
will make the entity now residing in the Persistence Context
to be moved to the database (using a SQL).
Without flush(), this (moving of entity from Persistence Context
to the database) will happen when the Transaction to which this Persistence Context
is associated is committed.
caching JavaScript files
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
How do I reference tables in Excel using VBA?
In addition, it's convenient to define variables referring to objects. For instance,
Sub CreateTable()
Dim lo as ListObject
Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
lo.Name = "Table1"
lo.TableStyle = "TableStyleLight2"
...
End Sub
You will probably find it advantageous at once.
CSS: center element within a <div> element
If you want to use CSS3:
position:absolute;
left:calc(50% - PutTheSizeOfTheHalfOfYourElementpx);
You might want to do further searches to figure out how to get the percentage to fit your element's width.
Why doesn't Git ignore my specified file?
Please use this command
git rm -rf --cached .
git add .
Sometimes .gitignore files don't work even though they're correct. The reason Git ignores files is that they are not added to the repository. If you added a file that you want to ignore before, it will be tracked by Git, and any skipping matching rules will be skipped. Git does this because the file is already part of the repository.
Unable to find a @SpringBootConfiguration when doing a JpaTest
The test slice provided in Spring Boot 1.4 brought feature oriented test capabilities.
For example,
@JsonTest provides a simple Jackson environment to test the json serialization and deserialization.
@WebMvcTest provides a mock web environment, it can specify the controller class for test and inject the MockMvc in the test.
@WebMvcTest(PostController.class)
public class PostControllerMvcTest{
@Inject MockMvc mockMvc;
}
@DataJpaTest will prepare an embedded database and provides basic JPA environment for the test.
@RestClientTest provides REST client environment for the test, esp the RestTemplateBuilder etc.
These annotations are not composed with SpringBootTest, they are combined with a series of AutoconfigureXXX
and a @TypeExcludesFilter
annotations.
Have a look at @DataJpaTest
.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {}
You can add your @AutoconfigureXXX annotation to override the default config.
@AutoConfigureTestDatabase(replace=NONE)
@DataJpaTest
public class TestClass{
}
Let's have a look at your problem,
- Do not mix
@DataJpaTest
and @SpringBootTest
, as said above @DataJpaTest
will build the configuration in its own way(eg. by default, it will try to prepare an embedded H2 instead) from the application configuration inheritance. @DataJpaTest
is designated for test slice.
- If you want to customize the configuration of
@DataJpaTest
, please read this official blog entry from Spring.io for this topic,(a little tedious).
- Split the configurations in
Application
into smaller configurations by features, such as WebConfig
, DataJpaConfig
etc. A full featured configuration(mixed web, data, security etc) also caused your test slice based tests to be failed. Check the test samples in my sample.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
What are the most common font-sizes for H1-H6 tags
Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.
How to convert .pfx file to keystore with private key?
I found this page which tells you how to import a PFX to JKS (Java Key Store):
keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME
How do I install boto?
While trying out the
pip install boto
command, I encounter the error
ImportError: No module named pkg_resources
To resolve this, issue another command to handle the setuptools using curl
curl https://bootstrap.pypa.io/ez_setup.py | python
After doing that, the following command will work perfectly.
pip install boto
Proper MIME type for OTF fonts
Ignore the chrome warning. There is no standard MIME type for OTF fonts.
font/opentype may silence the warning, but that doesn't make it the "right" thing to do.
Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.
Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.
Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf
SQL query return data from multiple tables
Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)
I'll be posting some of the frequently asked questions in MySQL
tag.
Trick No. 1 (rows that matches to multiple conditions)
Given this schema
CREATE TABLE MovieList
(
ID INT,
MovieName VARCHAR(25),
CONSTRAINT ml_pk PRIMARY KEY (ID),
CONSTRAINT ml_uq UNIQUE (MovieName)
);
INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');
CREATE TABLE CategoryList
(
MovieID INT,
CategoryName VARCHAR(25),
CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);
INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');
QUESTION
Find all movies that belong to at least both Comedy
and Romance
categories.
Solution
This question can be very tricky sometimes. It may seem that a query like this will be the answer:-
SELECT DISTINCT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName = 'Comedy' AND
b.CategoryName = 'Romance'
which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName
on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND
operator, both condition should be true; otherwise, it will be false. Another query is like this,
SELECT DISTINCT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName IN ('Comedy','Romance')
and the result is still incorrect because it matches to record that has at least one match on the categoryName
. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.
SELECT a.MovieName
FROM MovieList a
INNER JOIN CategoryList b
ON a.ID = b.MovieID
WHERE b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2
Trick No. 2 (maximum record for each entry)
Given schema,
CREATE TABLE Software
(
ID INT,
SoftwareName VARCHAR(25),
Descriptions VARCHAR(150),
CONSTRAINT sw_pk PRIMARY KEY (ID),
CONSTRAINT sw_uq UNIQUE (SoftwareName)
);
INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');
CREATE TABLE VersionList
(
SoftwareID INT,
VersionNo INT,
DateReleased DATE,
CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);
INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');
QUESTION
Find the latest version on each software. Display the following columns: SoftwareName
,Descriptions
,LatestVersion
(from VersionNo column),DateReleased
Solution
Some SQL developers mistakenly use MAX()
aggregate function. They tend to create like this,
SELECT a.SoftwareName, a.Descriptions,
MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM Software a
INNER JOIN VersionList b
ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID
(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by
clause) the result produces the correct LatestVersion
on each software but obviously the DateReleased
are incorrect. MySQL
doesn't support Window Functions
and Common Table Expression
yet as some RDBMS do already. The workaround on this problem is to create a subquery
which gets the individual maximum versionNo
on each software and later on be joined on the other tables.
SELECT a.SoftwareName, a.Descriptions,
b.LatestVersion, c.DateReleased
FROM Software a
INNER JOIN
(
SELECT SoftwareID, MAX(VersionNO) LatestVersion
FROM VersionList
GROUP BY SoftwareID
) b ON a.ID = b.SoftwareID
INNER JOIN VersionList c
ON c.SoftwareID = b.SoftwareID AND
c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID
So that was it. I'll be posting another soon as I recall any other FAQ on MySQL
tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.
UPDATE 1
Trick No. 3 (Finding the latest record between two IDs)
Given Schema
CREATE TABLE userList
(
ID INT,
NAME VARCHAR(20),
CONSTRAINT us_pk PRIMARY KEY (ID),
CONSTRAINT us_uq UNIQUE (NAME)
);
INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');
CREATE TABLE CONVERSATION
(
ID INT,
FROM_ID INT,
TO_ID INT,
MESSAGE VARCHAR(250),
DeliveryDate DATE
);
INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');
QUESTION
Find the latest conversation between two users.
Solution
SELECT b.Name SenderName,
c.Name RecipientName,
a.Message,
a.DeliveryDate
FROM Conversation a
INNER JOIN userList b
ON a.From_ID = b.ID
INNER JOIN userList c
ON a.To_ID = c.ID
WHERE (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
SELECT LEAST(FROM_ID, TO_ID) minFROM,
GREATEST(FROM_ID, TO_ID) maxTo,
MAX(DeliveryDate) maxDate
FROM Conversation
GROUP BY minFROM, maxTo
)
"No X11 DISPLAY variable" - what does it mean?
Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.
Download this app xming:
http://sourceforge.net/project/downloading.php?
Install, then use settings on this link:
http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:
Installing/Configuring PuTTy and Xming
Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.
Configuring Xming
Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:
- select Default entries on Display Settings windows, click next
- click next on Session Type window.
- click next on Additional parameters window(Notice clipboard checkbox is true)
- save configuration and click to finish.
Configuring PuTTy
After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:
This shows creating a login profile then saving it.
- On ssh -> X11, click on checkbox to enable X11 forwarding.
- on X display location textbox, type localhost:0.0
save profile then connect remotely to server to test.
Cheers!!!
Retrieving a Foreign Key value with django-rest-framework serializers
Just use a related field without setting many=True
.
Note that also because you want the output named category_name
, but the actual field is category
, you need to use the source
argument on the serializer field.
The following should give you the output you need...
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.RelatedField(source='category', read_only=True)
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
What is a Data Transfer Object (DTO)?
In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.
|-----------| |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------| |--------------|
In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.
I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:
|------------| |------------------| |------------|
-> Form | | -> Form | | -> Entity | |
| Controller | | Service / Facade | | Repository |
<- View | | <- View | | <- Entity / Projection View | |
|------------| |------------------| |------------|
Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)
Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.
User Service ----> XX CANNOT CALL XX ----> Order Service
Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.
For instance this is our User entity:
@Entity
public final class User {
private String id;
private String firstname;
private String lastname;
private String phone;
private String fax;
private String address;
// Accessors ...
}
But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.
public final class UserListItemView {
private String id;
private String firstname;
private String lastname;
// Accessors ...
}
You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.
List<UserListItemView> find(Pageable pageable);
Don't worry for other conversion operations BeanUtils.copy
method works just fine.
Does Eclipse have line-wrap
From Bug 35779 - Comment 187:
A workaround, that I use for the last years now, is to use the eclipse wiki markup editor for editing text files. This supports word wrap, and this is enough for me. Maybe this information could be of help to some of you.
How do I find my host and username on mysql?
You should be able to access the local database by using the name localhost
. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect
. See http://php.net/manual/en/function.mysql-connect.php.
Select multiple columns using Entity Framework
Here is a code sample:
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new PInfo
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username
}) AsEnumerable().
Select(y => new PInfo
{
ServerName = y.ServerName,
ProcessID = y.ProcessID,
UserName = y.UserName
}).ToList();
Get ID of element that called a function
Pass a reference to the element into the function when it is called:
<area id="nose" onmouseover="zoom(this);" />
<script>
function zoom(ele) {
var id = ele.id;
console.log('area element id = ' + id);
}
</script>
git still shows files as modified after adding to .gitignore
Using git rm --cached *file*
is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.
I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.
Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.
Anyway, all it requires is git update-index --assume-unchanged *path/to/file*
.
As far as I understand, this is the most notable thing to keep in mind:
Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.
Combine two columns of text in pandas dataframe
Let us suppose your dataframe
is df
with columns Year
and Quarter
.
import pandas as pd
df = pd.DataFrame({'Quarter':'q1 q2 q3 q4'.split(), 'Year':'2000'})
Suppose we want to see the dataframe;
df
>>> Quarter Year
0 q1 2000
1 q2 2000
2 q3 2000
3 q4 2000
Finally, concatenate the Year
and the Quarter
as follows.
df['Period'] = df['Year'] + ' ' + df['Quarter']
You can now print
df
to see the resulting dataframe.
df
>>> Quarter Year Period
0 q1 2000 2000 q1
1 q2 2000 2000 q2
2 q3 2000 2000 q3
3 q4 2000 2000 q4
If you do not want the space between the year and quarter, simply remove it by doing;
df['Period'] = df['Year'] + df['Quarter']
comparing two strings in SQL Server
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
- you can wraps this via a UDF using CREATE FUNCTION etc
- you may need NULL handling (in my code above, any NULL will report 1)
- str1 and str2 will be column names or @variables
Oracle date to string conversion
The data in COL1 is in dd-mon-yy
No it's not. A DATE
column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.
If COL1 is really a DATE
column using to_date()
on it is useless because to_date()
converts a string to a DATE.
You only need to_char(), nothing else:
SELECT TO_CHAR(col1, 'mm/dd/yyyy')
FROM TABLE1
What happens in your case is that calling to_date()
converts the DATE
into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.
Edit
So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.
The best (and to be honest: only sensible) solution is to convert that column to a DATE
. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.
But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR
instead of YY
:
SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1
should do the trick. Note that I also changed mon
to mm
as your example is 27-11-89
which has a number for the month, not an "word" (like NOV)
For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215
Why cannot cast Integer to String in java?
No, Integer
and String
are different types. To convert an integer to string use: String.valueOf(integer)
, or Integer.toString(integer)
for primitive, or Integer.toString()
for the object.
how to get current month and year
If you have following two labels:
<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />
Than you can use following code just need to set the Text Property for these labels like:
MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();
Implement specialization in ER diagram
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Dynamic tabs with user-click chosen components
I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.
'@angular/core': {
main: 'bundles/core.umd.js',
defaultExtension: 'js'
},
'@angular/compiler': {
main: 'bundles/compiler.umd.js',
defaultExtension: 'js'
},
'@angular/common': {
main: 'bundles/common.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
main: 'bundles/platform-browser-dynamic.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser': {
main: 'bundles/platform-browser.umd.js',
defaultExtension: 'js'
},
https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview
NodeJS: How to decode base64 encoded string back to binary?
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
How do I sort a two-dimensional (rectangular) array in C#?
Can I check - do you mean a rectangular array ([,]
)or a jagged array ([][]
)?
It is quite easy to sort a jagged array; I have a discussion on that here. Obviously in this case the Comparison<T>
would involve a column instead of sorting by ordinal - but very similar.
Sorting a rectangular array is trickier... I'd probably be tempted to copy the data out into either a rectangular array or a List<T[]>
, and sort there, then copy back.
Here's an example using a jagged array:
static void Main()
{ // could just as easily be string...
int[][] data = new int[][] {
new int[] {1,2,3},
new int[] {2,3,4},
new int[] {2,4,1}
};
Sort<int>(data, 2);
}
private static void Sort<T>(T[][] data, int col)
{
Comparer<T> comparer = Comparer<T>.Default;
Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col]));
}
For working with a rectangular array... well, here is some code to swap between the two on the fly...
static T[][] ToJagged<T>(this T[,] array) {
int height = array.GetLength(0), width = array.GetLength(1);
T[][] jagged = new T[height][];
for (int i = 0; i < height; i++)
{
T[] row = new T[width];
for (int j = 0; j < width; j++)
{
row[j] = array[i, j];
}
jagged[i] = row;
}
return jagged;
}
static T[,] ToRectangular<T>(this T[][] array)
{
int height = array.Length, width = array[0].Length;
T[,] rect = new T[height, width];
for (int i = 0; i < height; i++)
{
T[] row = array[i];
for (int j = 0; j < width; j++)
{
rect[i, j] = row[j];
}
}
return rect;
}
// fill an existing rectangular array from a jagged array
static void WriteRows<T>(this T[,] array, params T[][] rows)
{
for (int i = 0; i < rows.Length; i++)
{
T[] row = rows[i];
for (int j = 0; j < row.Length; j++)
{
array[i, j] = row[j];
}
}
}
How can I test that a variable is more than eight characters in PowerShell?
You can also use -match against a Regular expression. Ex:
if ($dbUserName -match ".{8}" )
{
Write-Output " Please enter more than 8 characters "
$dbUserName=read-host " Re-enter database user name"
}
Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.
jQuery get mouse position within an element
This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):
function getXY(evt) {
var element = document.getElementById('elementId'); //replace elementId with your element's Id.
var rect = element.getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop?
document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?
document.documentElement.scrollLeft:document.body.scrollLeft;
var elementLeft = rect.left+scrollLeft;
var elementTop = rect.top+scrollTop;
if (document.all){ //detects using IE
x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
y = event.clientY+scrollTop-elementTop;
}
else{
x = evt.pageX-elementLeft;
y = evt.pageY-elementTop;
}
Node.js global proxy setting
Unfortunately, it seems that proxy information must be set on each call to http.request
. Node does not include a mechanism for global proxy settings.
The global-tunnel-ng
module on NPM appears to handle this, however:
var globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: '10.0.0.10',
port: 8080,
proxyAuth: 'userId:password', // optional authentication
sockets: 50 // optional pool size for each http and https
});
After the global settings are establish with a call to initialize
, both http.request
and the request
library will use the proxy information.
The module can also use the http_proxy
environment variable:
process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();
Angular2 - Http POST request parameters
These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"
With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append()
syntax to achieve multiple params in the body since we are working with an immutable object:
login(userName: string, password: string): Promise<boolean> {
if (!userName || !password) {
return Promise.resolve(false);
}
let body: HttpParams = new HttpParams();
body = body.append('grant_type', 'password');
body = body.append('username', userName);
body = body.append('password', password);
return this.http.post(this.url, body)
.map(res => {
if (res) {
return true;
}
return false;
})
.toPromise();
}
Angular 4 - get input value
If you dont want to use two way data binding. You can do this.
In HTML
<form (ngSubmit)="onSubmit($event)">
<input name="player" value="Name">
</form>
In component
onSubmit(event: any) {
return event.target.player.value;
}
Find a pair of elements from an array whose sum equals a given number
Another solution in Swift: the idea is to create an hash that store values of (sum - currentValue) and compare this to the current value of the loop. The complexity is O(n).
func findPair(list: [Int], _ sum: Int) -> [(Int, Int)]? {
var hash = Set<Int>() //save list of value of sum - item.
var dictCount = [Int: Int]() //to avoid the case A*2 = sum where we have only one A in the array
var foundKeys = Set<Int>() //to avoid duplicated pair in the result.
var result = [(Int, Int)]() //this is for the result.
for item in list {
//keep track of count of each element to avoid problem: [2, 3, 5], 10 -> result = (5,5)
if (!dictCount.keys.contains(item)) {
dictCount[item] = 1
} else {
dictCount[item] = dictCount[item]! + 1
}
//if my hash does not contain the (sum - item) value -> insert to hash.
if !hash.contains(sum-item) {
hash.insert(sum-item)
}
//check if current item is the same as another hash value or not, if yes, return the tuple.
if hash.contains(item) &&
(dictCount[item] > 1 || sum != item*2) // check if we have item*2 = sum or not.
{
if !foundKeys.contains(item) && !foundKeys.contains(sum-item) {
foundKeys.insert(item) //add to found items in order to not to add duplicated pair.
result.append((item, sum-item))
}
}
}
return result
}
//test:
let a = findPair([2,3,5,4,1,7,6,8,9,5,3,3,3,3,3,3,3,3,3], 14) //will return (8,6) and (9,5)
How to check if a column exists in a datatable
It is much more accurate to use IndexOf:
If dt.Columns.IndexOf("ColumnName") = -1 Then
'Column not exist
End If
If the Contains is used it would not differentiate between ColumName and ColumnName2.
Javascript - Get Image height
I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.
Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:
<script type="text/javascript">
var imgHeight;
var imgWidth;
function findHHandWW() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
}
</script>
Thanks,
Binod Suman
http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html
How do I execute a bash script in Terminal?
This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...
The Executing a Command Line Script Tutorial!
Q: How do I execute this in Terminal?
Confusions and Conflicts:
- You do not need an 'extension' (like .sh or .py or anything else), but it helps to keep track of things. It won't hurt. If the script name contains an extension, however, you must use it.
- You do not need to be in any certain directory at all for any reason.
- You do not need to type out the name of the program that runs the file (BASH or Python or whatever) unless you want to. It won't hurt.
- You do not need
sudo
to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Great post here.
(A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your ~/bin folder. You can get there by typing cd ~/bin
or cd $HOME/bin
from the terminal prompt. You will have full permissions in that folder.)
To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:
Tell the system the location of the script. (pick one)
- Type the full path with the script name (e.g.
/path/to/script.sh
). You can verify the full path by typing pwd
or echo $PWD
in the terminal.
- Execute from the same directory and use
./
for the path (e.g. ./script.sh
). Easy.
- Place the script in a directory that is on the system
PATH
and just type the name (e.g. script.sh
). You can verify the system PATH
by typing echo $PATH
or echo -e ${PATH//:/\\n}
if you want a neater list.
Tell the system that the script has permission to execute. (pick one)
- Set the "execute bit" by typing
chmod +x /path/to/script.sh
in the terminal.
- You can also use
chmod 755 /path/to/script.sh
if you prefer numbers. There is a great discussion with a cool chart here.
Tell the system the type of script. (pick one)
- Type the name of the program before the script. (e.g.
BASH /path/to/script.sh
or PHP /path/to/script.php
) If the script has an extension, such as .php or .py, it is part of the script name and you must include it.
- Use a shebang, which I see you have (
#!/bin/bash
) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions.
- Use a "portable" shebang. You can also have the system choose the version of the program that is first in the
PATH
by using #!/usr/bin/env
followed by the program name (e.g. #!/usr/bin/env bash
or #!/usr/bin/env python3
). There are pros and cons as thoroughly discussed here.
How can I "disable" zoom on a mobile web page?
<script type="text/javascript">
document.addEventListener('touchmove', function (event) {
if (event.scale !== 1) { event.preventDefault(); }
}, { passive: false });
</script>
Please Add the Script to Disable pinch, tap, focus Zoom
Python argparse: default value or specified value
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
JavaFX How to set scene background image
I know this is an old Question
But in case you want to do it programmatically or the java way
For Image Backgrounds; you can use BackgroundImage class
BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));
For Paint or Fill Backgrounds; you can use BackgroundFill class
BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));
Keeps your java alive && your css dead..
Share Text on Facebook from Android App via ACTION_SEND
EDITED: with the new release of the official Facebook app for Android (July 14 2011) IT WORKS!!!
OLD: The examples above do not work if the user chooses the Facebook app for sharing, but they do work if the user chooses the Seesmic app to post to Facebook. I guess Seesmic have a better implementation of the Facebook API than Facebook!
Android Google Maps API V2 Zoom to Current Location
check this out:
fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
val request = LocationRequest()
// request.interval = 10000
// request.fastestInterval = 5000
request.numUpdates = 1
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val client = LocationServices.getFusedLocationProviderClient(context)
val permission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION )
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
if (location != null)
callback.invoke(location)
}
}, null)
}
}
and
fun zoomOnMe() {
requestMyGpsLocation(this) { location ->
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude,location.longitude ), 13F ))
}
}
ReCaptcha API v2 Styling
You can use some CSS for Google reCAPTCHA v2 styling on your website:
– Change background, color of Google reCAPTCHA v2 widget:
.rc-anchor-light {
background: #fff!important;
color: #fff!important; }
or
.rc-anchor-normal{
background: #000 !important;
color: #000 !important; }
– Resize the Google reCAPTCHA v2 widget by using this snippet:
.rc-anchor-light {
transform:scale(0.9);
-webkit-transform:scale(0.9); }
– Responsive your Google reCAPTCHA v2:
@media only screen and (min-width: 768px) {
.rc-anchor-light {
transform:scale(0.85);
-webkit-transform:scale(0.85); }
}
All elements, property of CSS above that’s just for your reference. You can change them by yourself (only using CSS class selector).
Refer on OIW Blog - How To Edit CSS of Google reCAPTCHA (Re-style, Change Position, Resize reCAPTCHA Badge)
You can also find out Google reCAPTCHA v3's styling there.
Make $JAVA_HOME easily changable in Ubuntu
You need to put variable definition in the ~/.bashrc
file.
From bash man page:
When an interactive shell that is
not a login shell is started, bash
reads and executes commands from
/etc/bash.bashrc and ~/.bashrc, if
these files exist.
how can the textbox width be reduced?
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
How to keep environment variables when using sudo
First you need to export HTTP_PROXY
. Second, you need to read man sudo
carefully, and pay attention to the -E
flag. This works:
$ export HTTP_PROXY=foof
$ sudo -E bash -c 'echo $HTTP_PROXY'
Here is the quote from the man page:
-E, --preserve-env
Indicates to the security policy that the user wishes to preserve their
existing environment variables. The security policy may return an error
if the user does not have permission to preserve the environment.
How to combine 2 plots (ggplot) into one plot?
Just combine them. I think this should work but it's untested:
p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() +
geom_smooth(fill="blue", colour="darkblue", size=1)
p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) +
geom_smooth(data=visual2, fill="red", colour="red", size=1)
print(p)
Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
Is there a good JSP editor for Eclipse?
"Web Page Editor (optional)" package from the Eclipse Galileo/Helios update site has the following very minor quirks in a JSP editor:
- Auto-commenting in Java code fragments does not work (Ctrl /); [fixed in Helios SR2]
- [present in Galileo, fixed in Eclipse Helios SR1] If a Java code fragment has errors that are already fixed, the editor does not remove the error marks until you modify the erroneous place or close/reopen the file being edited;
This was valid at Dec 7, 2010.
Objective-C ARC: strong vs retain and weak vs assign
Strong:
- Property will not Destroy but Only once you set the property to nil will the object get destroyed
- By default all instance variables and local variables are strong pointers.
- You use strong only if you need to retain the object.
- We generally use strong for UIViewControllers (UI item's parents)
- IOS 4 (non-ARC) We Can Use Retain KeyWord
- IOS 5(ARC) We Can Use Strong Keyword
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Weak
By Default automatically get and set to nil
- We generally use weak for IBOutlets (UIViewController's Childs) and delegate
- the same thing as assign, no retain or release
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
How/When does Execute Shell mark a build as failure in Jenkins?
In my opinion, turning off the -e
option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e
Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.
If you have a line in your script where failure is expected, like a grep or a find, then just add || true
to the end of that line. That ensures that line will always return success.
If you need to use that exit code, you can either hoist the command into your if statement:
grep foo bar; if [ $? == 0 ]; then ... --> if grep foo bar; then ...
Or you can capture the return code in your ||
clause:
grep foo bar || ret=$?
get path for my .exe
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
How to enable PHP short tags?
For docker add this step to Dockerfile
ARG phpIniPath=/path/to/your/php.ini
RUN sed -i -e 's/^short_open_tag\s*=.*/short_open_tag = On/' $phpIniPath
The identity used to sign the executable is no longer valid
These were the reasons I had this error:
The App ID didn't have my iOS Developer Certificate checked (I'm a member of an Enterprise program) and I had 2 provisioning profiles with the same App ID in my Mac. I deleted one.
Hopefully this helps someone.
How to use lodash to find and return an object from Array?
The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}
.
var delete_id = _.result(_.find(savedViews, function(obj) {
return obj.description === view;
}), 'id');
Yet another alternative from the docs you linked to (lodash v3):
_.find(savedViews, 'description', view);
Lodash v4:
_.find(savedViews, ['description', view]);
Upload Image using POST form data in Python-requests
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
@app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
Converting NSString to NSDate (and back again)
NSString *mystr=@"Your string date";
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [dateFormatter dateFromString:mystr];
Nslog(@"%@",now);
If you want set the format use below code:
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is important - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
Nslog(@"%@",[dateFormatter dateFromString:dateString]);
android layout with visibility GONE
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
GIT clone repo across local file system in windows
While UNC path is supported since Git 2.21 (Feb. 2019, see below), Git 2.24 (Q4 2019) will allow
git clone file://192.168.10.51/code
No more file:////xxx
, 'file://
' is enough to refer to an UNC path share.
See "Git Fetch Error with UNC".
Note, since 2016 and the MingW-64 git.exe
packaged with Git for Windows, an UNC path is supported.
(See "How are msys, msys2, and MinGW-64 related to each other?")
And with Git 2.21 (Feb. 2019), this support extends even in in an msys2 shell (with quotes around the UNC path).
See commit 9e9da23, commit 5440df4 (17 Jan 2019) by Johannes Schindelin (dscho
).
Helped-by: Kim Gybels (Jeff-G
).
(Merged by Junio C Hamano -- gitster
-- in commit f5dd919, 05 Feb 2019)
Before Git 2.21, due to a quirk in Git's method to spawn git-upload-pack
, there is a
problem when passing paths with backslashes in them: Git will force the
command-line through the shell, which has different quoting semantics in
Git for Windows (being an MSYS2 program) than regular Win32 executables
such as git.exe
itself.
The symptom is that the first of the two backslashes in UNC paths of the
form \\myserver\folder\repository.git
is stripped off.
This is mitigated now:
mingw: special-case arguments to sh
The MSYS2 runtime does its best to emulate the command-line wildcard expansion and de-quoting which would be performed by the calling Unix shell on Unix systems.
Those Unix shell quoting rules differ from the quoting rules applying to Windows' cmd and Powershell, making it a little awkward to quote command-line parameters properly when spawning other processes.
In particular, git.exe
passes arguments to subprocesses that are not intended to be interpreted as wildcards, and if they contain backslashes, those are not to be interpreted as escape characters, e.g. when passing Windows paths.
Note: this is only a problem when calling MSYS2 executables, not when calling MINGW executables such as git.exe. However, we do call MSYS2 executables frequently, most notably when setting the use_shell
flag in the child_process structure.
There is no elegant way to determine whether the .exe
file to be executed is an MSYS2 program or a MINGW one.
But since the use case of passing a command line through the shell is so prevalent, we need to work around this issue at least when executing sh.exe
.
Let's introduce an ugly, hard-coded test whether argv[0]
is "sh
", and
whether it refers to the MSYS2 Bash, to determine whether we need to
quote the arguments differently than usual.
That still does not fix the issue completely, but at least it is something.
Incidentally, this also fixes the problem where git clone \\server\repo
failed due to incorrect handling of the backslashes when handing the path to the git-upload-pack
process.
Further, we need to take care to quote not only whitespace and backslashes, but also curly brackets.
As aliases frequently go through the MSYS2 Bash, and as aliases frequently get parameters such as HEAD@{yesterday}
, this is really important.
See t/t5580-clone-push-unc.sh
How can I count the numbers of rows that a MySQL query returned?
The basics
To get the number of matching rows in SQL you would usually use COUNT(*)
. For example:
SELECT COUNT(*) FROM some_table
To get that in value in PHP you need to fetch the value from the first column in the first row of the returned result. An example using PDO and mysqli is demonstrated below.
However, if you want to fetch the results and then still know how many records you fetched using PHP, you could use count()
or avail of the pre-populated count in the result object if your DB API offers it e.g. mysqli's num_rows
.
Using MySQLi
Using mysqli you can fetch the first row using fetch_row()
and then access the 0
column, which should contain the value of COUNT(*)
.
// your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'dbuser', 'yourdbpassword', 'db_name');
$mysqli->set_charset('utf8mb4');
// your SQL statement
$stmt = $mysqli->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// now fetch 1st column of the 1st row
$count = $result->fetch_row()[0];
echo $count;
If you want to fetch all the rows, but still know the number of rows then you can use num_rows
or count()
.
// your SQL statement
$stmt = $mysqli->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// If you want to use the results, but still know how many records were fetched
$rows = $result->fetch_all(MYSQLI_ASSOC);
echo $result->num_rows;
// or
echo count($rows);
Using PDO
Using PDO is much simpler. You can directly call fetchColumn()
on the statement to get a single column value.
// your connection code
$pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]);
// your SQL statement
$stmt = $pdo->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// Fetch the first column of the first row
$count = $stmt->fetchColumn();
echo $count;
Again, if you need to fetch all the rows anyway, then you can get it using count()
function.
// your SQL statement
$stmt = $pdo->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// If you want to use the results, but still know how many records were fetched
$rows = $stmt->fetchAll();
echo count($rows);
PDO's statement doesn't offer pre-computed property with the number of rows fetched, but it has a method called rowCount()
. This method can tell you the number of rows returned in the result, but it cannot be relied upon and it is generally not recommended to use.
(SC) DeleteService FAILED 1072
make sure the service is stopped, the services control panel is closed, and no open file handles are open by the service.
Also make sure ProcessExplorer is not running.
PHP: Call to undefined function: simplexml_load_string()
For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:
extension=php_xmlrpc.dll
Then simply install php7.0-xml:
sudo apt-get install php7.0-xml
And restart PHP:
sudo service php7.0-fpm restart
And restart Apache:
sudo service apache2 restart
If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).
Powershell command to hide user from exchange address lists
You can use the following script, just replace DOMAIN with the name of your domain. When executed it will prompt you for a userlogin then hide that user's account from the address lists.
$name=Read-Host "Enter login name of user to hide"
Set-Mailbox -Identity DOMAIN\$name -HiddenFromAddressListsEnabled $true
Brian.
css divide width 100% to 3 column
How about using the CSS3 flex model:
HTML Code:
<div id="wrapper">
<div id="c1">c1</div>
<div id="c2">c2</div>
<div id="c3">c3</div>
</div>
CSS Code:
*{
margin:0;
padding:0;
}
#wrapper{
display:-webkit-flex;
-webkit-justify-content:center;
display:flex;
justify-content:center;
}
#wrapper div{
-webkit-flex:1;
flex:1;
border:thin solid #777;
}
Invalid Host Header when ngrok tries to connect to React dev server
I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:
module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
}, }
Require the file in the server.
const configstrp = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;
and connect as such
if (ngrok) {
console.log('If nGronk')
ngrok.connect(
{
addr: configstrp.ngrok.port,
subdomain: configstrp.ngrok.subdomain,
authtoken: configstrp.ngrok.authtoken,
host_header:3000
},
(err, url) => {
if (err) {
} else {
}
}
);
}
Do not pass a subdomain if you do not have a custom domain
javascript filter array multiple conditions
const users = [{
name: 'John',
email: '[email protected]',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: '[email protected]',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: '[email protected]',
age: 28,
address: 'England'
}
];
const filteredUsers = users.filter(({ name, age }) => name === 'Tom' && age === 35)
console.log(filteredUsers)
How to download all files (but not HTML) from a website using wget?
You may try:
wget --user-agent=Mozilla --content-disposition --mirror --convert-links -E -K -p http://example.com/
Also you can add:
-A pdf,ps,djvu,tex,doc,docx,xls,xlsx,gz,ppt,mp4,avi,zip,rar
to accept the specific extensions, or to reject only specific extensions:
-R html,htm,asp,php
or to exclude the specific areas:
-X "search*,forum*"
If the files are ignored for robots (e.g. search engines), you've to add also: -e robots=off
How can I insert binary file data into a binary SQL field using a simple insert statement?
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.