HTML: how to make 2 tables with different CSS
Of course, just assign seperate css classes to both tables.
<table class="style1"></table>
<table class="style2"></table>
.css
table.style1 { //your css here}
table.style2 { //your css here}
Django request get parameters
You can use []
to extract values from a QueryDict
object like you would any ordinary dictionary.
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]
# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]
# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]
How can I time a code segment for testing performance with Pythons timeit?
Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.
And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).
That said, you can simply put your code in a function and run that function with timeit.timeit()
:
def function_to_repeat():
# ...
duration = timeit.timeit(function_to_repeat, number=1000)
This would disable the garbage collection, repeatedly call the function_to_repeat()
function, and time the total duration of those calls using timeit.default_timer()
, which is the most accurate available clock for your specific platform.
You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup
argument to either import or create those dependencies, and pass them into your function:
def function_to_repeat(var1, var2):
# ...
duration = timeit.timeit(
'function_to_repeat(var1, var2)',
'from __main__ import function_to_repeat, var1, var2',
number=1000)
would grab the globals function_to_repeat
, var1
and var2
from your script and pass those to the function each repetition.
Regular Expression usage with ls
You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep
, sed
, etc) that do.
What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.
Newer versions of bash do have a regular expression operator, =~
:
for x in `ls`; do
if [[ $x =~ .+\..* ]]; then
echo $x;
fi;
done
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
Also please explain why encoding should be taken into consideration.
Can't I simply get what bytes the string has been stored in?
Why this dependency on encoding?!!!
Because there is no such thing as "the bytes of the string".
A string (or more generically, a text) is composed of characters: letters, digits, and other symbols. That's all. Computers, however, do not know anything about characters; they can only handle bytes. Therefore, if you want to store or transmit text by using a computer, you need to transform the characters to bytes. How do you do that? Here's where encodings come to the scene.
An encoding is nothing but a convention to translate logical characters to physical bytes. The simplest and best known encoding is ASCII, and it is all you need if you write in English. For other languages you will need more complete encodings, being any of the Unicode flavours the safest choice nowadays.
So, in short, trying to "get the bytes of a string without using encodings" is as impossible as "writing a text without using any language".
By the way, I strongly recommend you (and anyone, for that matter) to read this small piece of wisdom: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Which characters make a URL invalid?
I am implementing old http (0.9, 1.0, 1.1) request and response reader/writer. Request URI is the most problematic place.
You can't just use RFC 1738, 2396 or 3986 as it is. There are many old HTTP clients and servers that allows more characters. So I've made research based on accidentally published webserver access logs: "GET URI HTTP/1.0" 200
.
I've found that the following non-standard characters are often used in URI:
\ { } < > | ` ^ "
These characters were described in RFC 1738 as unsafe.
If you want to be compatible with all old HTTP clients and servers - you have to allow these characters in request URI.
Please read more information about this research in oghttp-request-collector.
How to get the changes on a branch in Git
This is similar to the answer I posted on: Preview a Git push
Drop these functions into your Bash profile:
- gbout - git branch outgoing
- gbin - git branch incoming
You can use this like:
- If on master: gbin branch1 <-- this
will show you what's in branch1 and
not in master
- If on master: gbout
branch1 <-- this will show you what's
in master that's not in branch 1
This will work with any branch.
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
function gbin {
echo branch \($1\) has these commits and \($(parse_git_branch)\) does not
git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
function gbout {
echo branch \($(parse_git_branch)\) has these commits and \($1\) does not
git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
What does numpy.random.seed(0) do?
A random seed specifies the start point when a computer generates a random number sequence.
For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.
For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:
Add 900 + 77 = 977
Subtract 52 = 925
Following the same algorithm, the second “random” number would be:
900 + 925 = 1825
Subtract 52 = 1773
This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated
Converting HTML to plain text in PHP for e-mail
public function plainText($text)
{
$text = strip_tags($text, '<br><p><li>');
$text = preg_replace ('/<[^>]*>/', PHP_EOL, $text);
return $text;
}
$text = "string 1<br>string 2<br/><ul><li>string 3</li><li>string 4</li></ul><p>string 5</p>";
echo planText($text);
output
string 1
string 2
string 3
string 4
string 5
Make a link open a new window (not tab)
Browsers control a lot of this functionality but
<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>
will attempt to open yahoo.com in a new window.
How to fast-forward a branch to head?
Move your branch pointer to the HEAD:
git branch -f master
Your branch master
already exists, so git will not allow you to overwrite it, unless you use... -f
(this argument stands for --force
)
Or you can use rebase:
git rebase HEAD master
Do it on your own risk ;)
Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
Also if you want to make something similar to
You need
1.Set horizontal and vertical alignment for button to
Find all required values and set UIImageEdgeInsets
CGSize buttonSize = button.frame.size;
NSString *buttonTitle = button.titleLabel.text;
CGSize titleSize = [buttonTitle sizeWithAttributes:@{ NSFontAttributeName : [UIFont camFontZonaProBoldWithSize:12.f] }];
UIImage *buttonImage = button.imageView.image;
CGSize buttonImageSize = buttonImage.size;
CGFloat offsetBetweenImageAndText = 10; //vertical space between image and text
[button setImageEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 - offsetBetweenImageAndText,
(buttonSize.width - buttonImageSize.width) / 2,
0,0)];
[button setTitleEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 + buttonImageSize.height + offsetBetweenImageAndText,
titleSize.width + [button imageEdgeInsets].left > buttonSize.width ? -buttonImage.size.width + (buttonSize.width - titleSize.width) / 2 : (buttonSize.width - titleSize.width) / 2 - buttonImage.size.width,
0,0)];
This will arrange your title and image on button.
Also please note update this on each relayout
Swift
import UIKit
extension UIButton {
// MARK: - UIButton+Aligment
func alignContentVerticallyByCenter(offset:CGFloat = 10) {
let buttonSize = frame.size
if let titleLabel = titleLabel,
let imageView = imageView {
if let buttonTitle = titleLabel.text,
let image = imageView.image {
let titleString:NSString = NSString(string: buttonTitle)
let titleSize = titleString.sizeWithAttributes([
NSFontAttributeName : titleLabel.font
])
let buttonImageSize = image.size
let topImageOffset = (buttonSize.height - (titleSize.height + buttonImageSize.height + offset)) / 2
let leftImageOffset = (buttonSize.width - buttonImageSize.width) / 2
imageEdgeInsets = UIEdgeInsetsMake(topImageOffset,
leftImageOffset,
0,0)
let titleTopOffset = topImageOffset + offset + buttonImageSize.height
let leftTitleOffset = (buttonSize.width - titleSize.width) / 2 - image.size.width
titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset,
leftTitleOffset,
0,0)
}
}
}
}
.NET 4.0 has a new GAC, why?
I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):
Mark Miller said...
June 28, 2010 12:13 PM
Thanks for
the post. "Interference issues" was
intentionally vague. At the time of
writing, the issues were still being
investigated, but it was clear there
were several broken scenarios.
For instance, some applications use
Assemby.LoadWithPartialName to load
the highest version of an assembly. If
the highest version was compiled with
v4, then a v2 (3.0 or 3.5) app could
not load it, and the app would crash,
even if there were a version that
would have worked. Originally, we
partitioned the GAC under it's
original location, but that caused
some problems with windows upgrade
scenarios. Both of these involved code
that had already shipped, so we moved
our (version-partitioned GAC to
another place.
This shouldn't have any impact to most
applications, and doesn't add any
maintenance burden. Both locations
should only be accessed or modified
using the native GAC APIs, which deal
with the partitioning as expected. The
places where this does surface are
through APIs that expose the paths of
the GAC such as GetCachePath, or
examining the path of mscorlib loaded
into managed code.
It's worth noting that we modified GAC
locations when we released v2 as well
when we introduced architecture as
part of the assembly identity. Those
added GAC_MSIL, GAC_32, and GAC_64,
although all still under
%windir%\assembly. Unfortunately, that
wasn't an option for this release.
Hope it helps future readers.
Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query
I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.
Where can I get Google developer key
Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2
Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'
Click on the 'Google API Console' link.
When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'
How do I return multiple values from a function in C?
Option 1
: Declare a struct with an int and string and return a struct variable.
struct foo {
int bar1;
char bar2[MAX];
};
struct foo fun() {
struct foo fooObj;
...
return fooObj;
}
Option 2
: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:
int fun(char **param) {
int bar;
...
strcpy(*param,"....");
return bar;
}
or
char* fun(int *param) {
char *str = /* malloc suitably.*/
...
strcpy(str,"....");
*param = /* some value */
return str;
}
Option 3
: Similar to the option 2. You can pass both via pointer and return nothing from the function:
void fun(char **param1,int *param2) {
strcpy(*param1,"....");
*param2 = /* some calculated value */
}
How to generate a GUID in Oracle?
Creating a 350 characters GUID:
dbms_random.STRING ('a', 350) - returning string in mixed case alpha characters
dbms_random.STRING ('x', 350) - returning string in uppercase alpha-numeric characters
What are the git concepts of HEAD, master, origin?
HEAD
is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.
master
is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).
origin
is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.
Is there a way to cache GitHub credentials for pushing commits?
With Git version 1.7.9 and later
Since Git 1.7.9 (released in late January 2012), there is a neat mechanism in Git to avoid having to type your password all the time for HTTP / HTTPS, called credential helpers. (Thanks to dazonic for pointing out this new feature in the comments below.)
With Git 1.7.9 or later, you can just use one of the following credential helpers:
git config --global credential.helper cache
... which tells Git to keep your password cached in memory for (by default) 15 minutes. You can set a longer timeout with:
git config --global credential.helper "cache --timeout=3600"
(That example was suggested in the GitHub help page for Linux.) You can also store your credentials permanently if so desired, see the other answers below.
GitHub's help also suggests that if you're on Mac OS X and used Homebrew to install Git, you can use the native Mac OS X keystore with:
git config --global credential.helper osxkeychain
For Windows, there is a helper called Git Credential Manager for Windows or wincred in msysgit.
git config --global credential.helper wincred # obsolete
With Git for Windows 2.7.3+ (March 2016):
git config --global credential.helper manager
For Linux, you would use (in 2011) gnome-keyring
(or other keyring implementation such as KWallet).
Nowadays (2020), that would be (on Linux)
Fedora
sudo dnf install git-credential-libsecret
git config --global credential.helper /usr/libexec/git-core/git-credential-libsecret
Ubuntu
sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
With Git versions before 1.7.9
With versions of Git before 1.7.9, this more secure option is not available, and you'll need to change the URL that your origin
remote uses to include the password in this fashion:
https://you:[email protected]/you/example.git
... in other words with :password
after the username and before the @
.
You can set a new URL for your origin
remote with:
git config remote.origin.url https://you:[email protected]/you/example.git
Make sure that you use https
, and you should be aware that if you do this, your GitHub password will be stored in plaintext in your .git
directory, which is obviously undesirable.
With any Git version (well, since version 0.99)
An alternative approach is to put your username and password in your ~/.netrc
file, although, as with keeping the password in the remote URL, this means that your password will be stored on the disk in plain text and is thus less secure and not recommended. However, if you want to take this approach, add the following line to your ~/.netrc
:
machine <hostname> login <username> password <password>
... replacing <hostname>
with the server's hostname, and <username>
and <password>
with your username and password. Also remember to set restrictive file system permissions on that file:
chmod 600 ~/.netrc
Note that on Windows, this file should be called _netrc
, and you may need to define the %HOME% environment variable - for more details see:
Android and setting alpha for (image) view alpha
There is now an XML alternative:
<ImageView
android:id="@+id/example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/example"
android:alpha="0.7" />
It is: android:alpha="0.7"
With a value from 0 (transparent) to 1 (opaque).
How to call a method after a delay in Android
See this demo:
import java.util.Timer;
import java.util.TimerTask;
class Test {
public static void main( String [] args ) {
int delay = 5000;// in ms
Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run() {
System.out.println("Wait, what..:");
}
}, delay);
System.out.println("Would it run?");
}
}
How can I multiply all items in a list together with Python?
Starting Python 3.8
, a .prod
function has been included to the math
module in the standard library:
math.prod(iterable, *, start=1)
The method returns the product of a start
value (default: 1) times an iterable of numbers:
import math
math.prod([1, 2, 3, 4, 5, 6])
>>> 720
If the iterable is empty, this will produce 1
(or the start
value, if provided).
What is the difference between Swing and AWT?
Swing:
- Swing is part of the java foundation classes.
- Swing components are platform-independent.
- Swing components are lightweight components because swing sits on the top of awt.
AWT:
- AWT is called the abstract window tool.
- AWT components are platform-dependent.
- AWT components are heavyweight components.
MYSQL Sum Query with IF Condition
Try with a CASE in this way :
SUM(CASE
WHEN PaymentType = "credit card"
THEN TotalAmount
ELSE 0
END) AS CreditCardTotal,
Should give what you are looking for ...
How to access a value defined in the application.properties file in Spring Boot
Currently,
I know about the following three ways:
1. The @Value
annotation
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
- In my experience there are some situations when you are not
able to get the value or it is set to
null
.
For instance,
when you try to set it in a preConstruct()
method or an init()
method.
This happens because the value injection happens after the class is fully constructed.
This is why it is better to use the 3'rd option.
2. The @PropertySource
annotation
<pre>@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);</pre>
PropertySouce
sets values from the property source file in an Environment
variable (in your class) when the class is loaded.
So you able to fetch easily afterword.
- Accessible through System Environment variable.
3. The @ConfigurationProperties
annotation.
- This is mostly used in Spring projects to load configuration properties.
It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.
@Configuration
creates a bean based on configuration file variables.
@ConfigurationProperties(prefix = "user")
@Configuration("UserData")
class user {
//Property & their getter / setter
}
@Autowired
private UserData userData;
userData.getPropertyName();
How to customize the back button on ActionBar
The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator
attribute of the theme. To override it with your own custom version it would be something like this:
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>
If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11
or similar.
Loop through Map in Groovy?
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
Are these methods thread safe?
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
Tensorflow set CUDA_VISIBLE_DEVICES within jupyter
You can set environment variables in the notebook using os.environ
. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
You can double check that you have the correct devices visible to TF
from tensorflow.python.client import device_lib
print device_lib.list_local_devices()
I tend to use it from utility module like notebook_util
import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf
Path of assets in CSS files in Symfony 2
If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:
Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml
, we have commented:
#assetic:
# use_controller: true
And in routing_dev.yml
#_assetic:
# resource: .
# type: assetic
Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif");
Note: our vhost web root is pointing on web/
.
No usage of cssrewrite filter
javac option to compile all java files under a given directory recursively
I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.
You would just have to define a target like this in the build.xml file:
<target name="compile">
<javac srcdir="your/source/directory"
destdir="your/output/directory"
classpath="xyz.jar" />
</target>
Simplest way to do grouped barplot
with ggplot2:
library(ggplot2)
Animals <- read.table(
header=TRUE, text='Category Reason Species
1 Decline Genuine 24
2 Improved Genuine 16
3 Improved Misclassified 85
4 Decline Misclassified 41
5 Decline Taxonomic 2
6 Improved Taxonomic 7
7 Decline Unclear 41
8 Improved Unclear 117')
ggplot(Animals, aes(factor(Reason), Species, fill = Category)) +
geom_bar(stat="identity", position = "dodge") +
scale_fill_brewer(palette = "Set1")
How to open a file / browse dialog using javascript?
Here is a non-jQuery solution. Note you can't just use .click()
as some browsers do not support it.
<script type="text/javascript">
function performClick(elemId) {
var elem = document.getElementById(elemId);
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />
SVG fill color transparency / alpha?
You use an addtional attribute; fill-opacity
: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.
For example:
<rect ... fill="#044B94" fill-opacity="0.4"/>
Additionally you have the following:
stroke-opacity
attribute for the stroke
opacity
for the entire object
How to convert string date to Timestamp in java?
You can convert String to Timestamp:
String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());
Syntax error near unexpected token 'fi'
As well as having then
on a new line, you also need a space before and after the [
, which is a special symbol in BASH.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [ $((fname % 2)) -eq 1 ]
then
echo "removing $fname\n"
rm "$f"
fi
done
Can't connect to MySQL server on '127.0.0.1' (10061) (2003)
To re-iterate what Jens wrote in more current code, first open the Command Prompt with Administrator access by right-clicking the Command Prompt icon and select "Run as administrator." Then cut and paste the following into the Command Prompt at the C:> directory level:
"C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin\mysqld" --install
You may have to change the name of the folder depending on where MySQL is installed and what version it is.
Simple VBA selection: Selecting 5 cells to the right of the active cell
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)
You can use this code when using vs code on debugging mode.
"runtimeArgs": ["--disable-web-security","--user-data-dir=~/ChromeUserData/"]
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Chrome disable-web-security",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}",
"runtimeArgs": [
"--disable-web-security",
"--user-data-dir=~/ChromeUserData/"
]
}
]
}
Or directly run
Chrome --disable-web-security --user-data-dir=~/ChromeUserData/
Do C# Timers elapse on a separate thread?
For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.
static System.Timers.Timer DummyTimer = null;
static void Main(string[] args)
{
try
{
Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
DummyTimer.Enabled = true;
DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
DummyTimer.AutoReset = true;
DummyTimer.Start();
Console.WriteLine("Hit any key to exit");
Console.ReadLine();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
return;
}
static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
return;
}
Output you'd see if DummyTimer fired on 5 seconds interval:
Main Thread Id: 9
12
12
12
12
12
...
So, as seen, OnDummyTimerFired is executed on Workers thread.
No, further complication - If you reduce interval to say 10 ms,
Main Thread Id: 9
11
13
12
22
17
...
This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.
Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx#S2
Using Ajax.BeginForm with ASP.NET MVC 3 Razor
Example
//In Model
public class MyModel
{
[Required]
public string Name{ get; set; }
}
//In PartailView
//PartailView.cshtml
@model MyModel
<div>
<div>
@Html.LabelFor(model=>model.Name)
</div>
<div>
@Html.EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
In Index.cshtml view
@model MyModel
<div id="targetId">
@{Html.RenderPartial("PartialView",Model)}
</div>
@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
<div>
<input type="submit" value="Add Unit" />
</div>
}
In Controller
public ActionResult Index()
{
return View(new MyModel());
}
public string AddName(MyModel model)
{
string HtmlString = RenderPartialViewToString("PartailView",model);
return HtmlString;
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"
public class Splash extends Activity {
Location location;
LocationManager locationManager;
LocationListener locationlistener;
ImageView image_view;
ublic static ProgressDialog progressdialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressdialog = new ProgressDialog(Splash.this);
image_view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates("gps", 100000, 1, locationlistener);
Toast.makeText(getApplicationContext(), "Getting Location plz wait...", Toast.LENGTH_SHORT).show();
progressdialog.setMessage("getting Location");
progressdialog.show();
Intent intent = new Intent(Splash.this,Show_LatLng.class);
// }
});
}
Text here:-
use this for getting activity
context for progressdialog
progressdialog = new ProgressDialog(Splash.this);
or progressdialog = new ProgressDialog(this);
use this for getting application context for BroadcastListener
not for progressdialog
.
progressdialog = new ProgressDialog(getApplicationContext());
progressdialog = new ProgressDialog(getBaseContext());
How to send push notification to web browser?
So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.
Update (May 2018):
Here is a comprehensive and a very well written doc on web push notification from Google.
Answer to the original questions asked 3 years ago:
- Can we use GCM/APNS to send push notification to all Web Browsers
including Firefox & Safari?
Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.
- If not via GCM can we have our own back-end to do the same?
Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.
Check this codelab from Google to better understand the implementation.
Some Tutorials:
- Implementing push notification in Django Here.
- Using flask to send push notification Here & Here.
- Sending push notifcaiton from Nodejs Here
- Sending push notification using php Here & Here
- Sending push notification from Wordpress. Here & Here
- Sending push notification from Drupal. Here
Implementing own backend in various programming languages.:
Further Readings:
-
- Documentation from Firefox website can be read here.
- A very good overview of Web Push by Google can be found here.
- An FAQ answering most common confusions and questions.
Are there any free services to do the same?
There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:
- https://onesignal.com/ (Free | Support all platforms)
- https://firebase.google.com/products/cloud-messaging/ (Free)
- https://clevertap.com/ (Has free plan)
- https://goroost.com/
Note:
When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.
Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org
How can I create my own comparator for a map?
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
How to detect the currently pressed key?
if ((Control.ModifierKeys & Keys.Shift) != 0)
This will also be true if Ctrl+Shift is down. If you want to check whether Shift alone is pressed,
if (Control.ModifierKeys == Keys.Shift)
If you're in a class that inherits Control
(such as a form), you can remove the Control.
What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?
The backgroundTint
attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
The backgroundTintMode
on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop,
etc.
Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint
attribute and the description along with various attributes will be available.
How to change value of process.env.PORT in node.js?
EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
Original Answer:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
- Open up your bash profile
vim ~/.bash_profile
- Add the environment variable to the file
export PORT=80
- Open up the sudoers config file
sudo visudo
- Add the following line to the file exactly as so
Defaults env_keep +="PORT"
Now when you run sudo node app.js
it should work as desired.
c# Image resizing to different size while preserving aspect ratio
Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.
The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:
namespace YourApp
{
#region Namespaces
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
#endregion
/// <summary>Generic helper functions related to graphics.</summary>
public static class ImageExtensions
{
/// <summary>Resizes an image to a new width and height value.</summary>
/// <param name="image">The image to resize.</param>
/// <param name="newWidth">The width of the new image.</param>
/// <param name="newHeight">The height of the new image.</param>
/// <param name="mode">Interpolation mode.</param>
/// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
/// <returns>The new image. The old image is unaffected.</returns>
public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
{
Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);
using (Graphics gfx = Graphics.FromImage(output))
{
gfx.Clear(Color.FromArgb(0, 0, 0, 0));
gfx.InterpolationMode = mode;
if (mode == InterpolationMode.NearestNeighbor)
{
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.SmoothingMode = SmoothingMode.HighQuality;
}
double ratioW = (double)newWidth / (double)image.Width;
double ratioH = (double)newHeight / (double)image.Height;
double ratio = ratioW < ratioH ? ratioW : ratioH;
int insideWidth = (int)(image.Width * ratio);
int insideHeight = (int)(image.Height * ratio);
gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
}
return output;
}
}
}
Importing CSV data using PHP/MySQL
I answered a virtually identical question just the other day: Save CSV files into mysql database
MySQL has a feature LOAD DATA INFILE
, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.
Simple example:
<?php
$query = <<<eof
LOAD DATA INFILE '$fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1,field2,field3,etc)
eof;
$db->query($query);
?>
It's as simple as that.
No loops, no fuss. And much much quicker than parsing it in PHP.
MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Hope that helps
Using Google maps API v3 how do I get LatLng with a given address?
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
How can I switch word wrap on and off in Visual Studio Code?
I am not sure when it was added, but I'm using v0.10.8 and
Alt + Z is the keyboard shortcut for turning word wrap on and off. This satisfies the requirement of "able to turn it on and off quickly".
The setting does not persist after closing Visual Studio Code. To persist, you need to set it through Radha's answer of using the settings.json
file...
// Place your settings in this file to overwrite the default settings
{ "editor.wrappingColumn": 0 }
How to remove class from all elements jquery
This just removes the highlight
class from everything that has the edgetoedge
class:
$(".edgetoedge").removeClass("highlight");
I think you want this:
$(".edgetoedge .highlight").removeClass("highlight");
The .edgetoedge .highlight
selector will choose everything that is a child of something with the edgetoedge
class and has the highlight
class.
CentOS 64 bit bad ELF interpreter
Just came across the same problem on a freshly installed CentOS 6.4 64-bit machine. A single yum command will fix this plus 99% of similar problems:
yum groupinstall "Compatibility libraries"
Either prefix this with 'sudo' or run as root, whichever works best for you.
react hooks useEffect() cleanup for only componentWillUnmount?
instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.
//componentDidMount
useEffect( () => {
window.addEventListener("load", pageLoad);
//component will unmount
return () => {
window.removeEventListener("load", pageLoad);
}
});
now that this part is done I just run anything I want from the pageLoad function like this.
const pageLoad = () =>{
console.log(I was mounted and unmounted automatically :D)}
How can I echo HTML in PHP?
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?>
instead of <?=$var?>
depending on your PHP setup.
Reinitialize Slick js after successful ajax call
I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.
try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:
jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});
Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}
); the first ajax call and once it is initialized then follow above steps, you may wanna use if else
jQuery select change show/hide div event
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
Also change the values... as per your parameters
Change IPython/Jupyter notebook working directory
Besides @Matt's approach, one way to change the default directory to use for notebooks permanently is to change the config files. Firstly in the cmdline, type:
$> ipython profile create
to initialize a profile with the default configuration file. Secondly, in file ipython_notebook_config.py
, uncomment and edit this line:
# c.NotebookManager.notebook_dir = 'D:\\Documents\\Desktop'
changing D:\\Documents\\Desktop
to whatever path you like.
This works for me ;)
UPDATE: There is no c.NotebookManager.notebook_dir
anymore.
Now, the line to uncomment and config is this one:
c.NotebookApp.notebook_dir = 'Z:\\username_example\folder_that_you_whant'
Why can't static methods be abstract in Java?
Declaring a method as static
means we can call that method by its class name and if that class is abstract
as well, it makes no sense to call it as it does not contain any body, and hence we cannot declare a method both as static
and abstract
.
What does `unsigned` in MySQL mean and when to use it?
MySQL says:
All integer types can have an optional
(nonstandard) attribute UNSIGNED.
Unsigned type can be used to permit
only nonnegative numbers in a column
or when you need a larger upper
numeric range for the column. For
example, if an INT column is UNSIGNED,
the size of the column's range is the
same but its endpoints shift from
-2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Programmatically relaunch/recreate an activity?
If you're just looking to re-do your view, I had the exact same issue. In the onResume
function try putting this:
mView = new AndroidPinballView(getApplication());
This was also in my onCreate()
, so putting this in the onResume
worked for me :)
How to clear Flutter's Build cache?
You can run flutter clean
.
But that's most likely a problem with your IDE or similar, as flutter run creates a brand new apk. And hot reload push only modifications.
Try running your app using the command line flutter run
and then press r
or R
for respectively hot-reload and full-reload.
How do I specify row heights in CSS Grid layout?
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
What is a mutex?
To understand MUTEX at first you need to know what is "race condition" and then only you will understand why MUTEX is needed. Suppose you have a multi-threading program and you have two threads. Now, you have one job in the job queue. The first thread will check the job queue and after finding the job it will start executing it. The second thread will also check the job queue and find that there is one job in the queue. So, it will also assign the same job pointer. So, now what happens, both the threads are executing the same job. This will cause a segmentation fault. This is the example of a race condition.
The solution to this problem is MUTEX. MUTEX is a kind of lock which locks one thread at a time. If another thread wants to lock it, the thread simply gets blocked.
The MUTEX topic in this pdf file link is really worth reading.
Android: How to change CheckBox size?
Assume your original xml is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/tick_img" />
<item android:state_checked="false"
android:drawable="@drawable/untick_img" />
</selector>
then simply remove android:button="@drawable/xml_above"
in your checkbox xml, and do drawable scaling programmatically in java (decrease the 150
big size to your desired dp):
CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);
//custom selector size
Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
Bitmap bitmapTick = null;
if (drawableTick != null && drawableUntick != null) {
int desiredPixels = Math.round(convertDpToPixel(150, this));
bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
Drawable dTick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));
Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
Drawable dUntick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));
final StateListDrawable statesTick = new StateListDrawable();
statesTick.addState(new int[] {android.R.attr.state_checked},
dTick);
statesTick.addState(new int[] { }, //else state_checked false
dUntick);
tickRememberPasswd.setButtonDrawable(statesTick);
}
the convertDpToPixel
method:
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
html select option separator
You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)
In HTML:
<option value="—————————————" disabled>—————————————</option>
Or in XHTML:
<option value="—————————————" disabled="disabled">—————————————</option>
ld cannot find an existing library
As just formulated by grepsedawk, the answer lies in the -l
option of g++
, calling ld
. If you look at the man page of this command, you can either do:
g++ -l:libmagic.so.1 [...]
- or:
g++ -lmagic [...]
, if you have a symlink named libmagic.so in your libs path
How to escape double quotes in JSON
When and where to use \\\"
instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.
If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\"
is the one you're looking for.
However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\"
. This is because you're building your text string within an HTML <script>
block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \"
from the standard answer and the JSON parser will parse this as just the double quotes.
<script>
var text="{";
text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
text += "}";
var obj=JSON.parse(text);
</script>
+1: since it's a JavaScript text string, a double backslash double quote \\"
would work too; because the double quote does not need escaped within a single quoted string eg '\"'
and '"'
result in the same JS string.
Numpy: find index of the elements within range
Other way is with:
np.vectorize(lambda x: 6 <= x <= 10)(a)
which returns:
array([False, False, False, True, True, True, False, False, False])
It is sometimes useful for masking time series, vectors, etc.
How to send a Post body in the HttpClient request in Windows Phone 8?
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
How to unblock with mysqladmin flush hosts
You should put it into command line in windows.
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
For network login use the following command:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
you can permanently solution your problem by editing my.ini file[Mysql configuration file]
change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
Implementing SearchView in action bar
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
The module ".dll" was loaded but the entry-point was not found
The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered)
it seems that we are talking about a service not correctly installed. I will try to reinstall the application.
Can local storage ever be considered secure?
This is a really interesting article here. I'm considering implementing JS encryption for offering security when using local storage. It's absolutely clear that this will only offer protection if the device is stolen (and is implemented correctly). It won't offer protection against keyloggers etc. However this is not a JS issue as the keylogger threat is a problem of all applications, regardless of their execution platform (browser, native). As to the article "JavaScript Crypto Considered Harmful" referenced in the first answer, I have one criticism; it states "You could use SSL/TLS to solve this problem, but that's expensive and complicated". I think this is a very ambitious claim (and possibly rather biased). Yes, SSL has a cost, but if you look at the cost of developing native applications for multiple OS, rather than web-based due to this issue alone, the cost of SSL becomes insignificant.
My conclusion - There is a place for client-side encryption code, however as with all applications the developers must recognise it's limitations and implement if suitable for their needs, and ensuring there are ways of mitigating it's risks.
How to make correct date format when writing data to Excel
Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:
https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs
FWIW this is how I went about it:
- opened excel, manually entered a datetime into the first cell of a workbook
- opened the regions dialog in control panel
- used Spy to find out the HWND's of the regions combobox and the apply button so I can use SetForegroundWindow and SendKey to change the region (couldn't find how to change region through the Windows API)
- iterated through all regions and for each region asked Excel for the NumberFormat of the cell that contained the date, saved this data to into a file
Create a new RGB OpenCV image using Python?
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
How do I turn off PHP Notices?
As mentioned by some and if you are the code author, you should correct all those errors, notices, etc. because it will cause more problems for you long terms than not fixing them (especially when you upgrade your OS). For your server, you should have errors displayed in your logs only, not the client's screen.
So to avoid the errors in your browser you use the display_errors
flag as you already found:
display_errors = Off
Now the real problem is when you are running someone else code. In that case, modifying the code is likely to get overwritten each time you upgrade that code. It makes it tedious to maintain that code.
In my case, I am running PHP with crontab
to have the wp-cron.php
script running once in a while. I was getting errors sent to my emails, which becomes tedious when you get one email every 10 minutes! In that case, though, the Wordpress system has a configuration file includes a WP_DEBUG
and they call the error_reporting()
function so trying to change the error_reporting
variable on the command line won't work. Instead you have to edit the wp-config.php
file in the root folder and make sure that the WP_DEBUG
is set to false
. Otherwise you will get all those warnings and notices all the time.
How to iterate over a string in C?
You need a pointer to the first char to have an ANSI string.
printf("%s", source + i);
will do the job
Plus, of course you should have meant strlen(source)
, not sizeof(source)
.
cannot connect to pc-name\SQLEXPRESS
I'm Running Windows 10 and this worked for me:
- Open services by searching in the toolbar for Services.
- Right click SQL Server (SQLEXPESS)
- Go To Properties - Log On
- Check Local System Account & Allow service to interact with desktop.
- Apply and restart service.
- I was then able to connect
How to use SVG markers in Google Maps API v3
You need to pass optimized: false
.
E.g.
var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});
Without passing optimized: false
, my svg appeared as a static image.
Using Page_Load and Page_PreRender in ASP.Net
Well a big requirement to implement PreRender as opposed to Load is the need to work with the controls on the page. On Page_Load, the controls are not rendered, and therefore cannot be referenced.
Windows batch: call more than one command in a FOR loop?
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
Center text in div?
Adding line height helps too.
text-align: center;
line-height: 18px; /* for example. */
Putting HTML inside Html.ActionLink(), plus No Link Text?
Instead of using Html.ActionLink you can render a url via Url.Action
<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a>
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>
And to do a blank url you could have
<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>
Get first word of string
To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
rsync - mkstemp failed: Permission denied (13)
I had the same issue in case of CentOS 7. I went through lot of articles ,forums but couldnt find out the solution.
The problem was with SElinux. Disabling SElinux at the server end worked.
Check SELinux status at the server end (from where you are pulling data using rysnc)
Commands to check SELinux status and disable it
$getenforce
Enforcing ## this means SElinux is enabled
$setenforce 0
$getenforce
Permissive
Now try running rsync command at the client end ,it worked for me.
All the best!
Jquery $.ajax fails in IE on cross domain calls
Simply add "?callback=?" (or "&callback=?") to your url:
$.getJSON({
url:myUrl + "?callback=?",
data: myData,
success: function(data){
/*My function stuff*/
}
});
When doing the calls (with everything else set properly for cross-domain, as above) this will trigger the proper JSONP formatting.
More in-depth explanation can be found in the answer here.
Eclipse JPA Project Change Event Handler (waiting)
There is another way to disable JPA tools for the project, that doesn't require to uninstall JPA features/plug-ins. I tested on https://github.com/Jasig/uPortal project wich was mentioned in https://bugs.eclipse.org/bugs/show_bug.cgi?id=386171 and claims to have similar problems:
- Switch to Eclipse Projects Explorer View to see the projects with JPA Facet Enabled (there should be "JPA Content" node);
- Select the project of interest which has "JPA Content" node and select Properties from context menu or press Alt+Enter to show Properties dialog for the project;
- Select "Project Facets" node in tree with categories;
- Clear JPA check box in project facets list and press OK.
After disabling JPA facet for uportal-war project form repository above I don't see any JPA related jobs in Eclipse Progress View.
Unable to open debugger port in IntelliJ
I had the same problem and this solution also did the trick for me: Provide the IP 127.0.0.1 in the Intellij Debug configuration instead of the host name "localhost", in case you're using this hostname.
libpng warning: iCCP: known incorrect sRGB profile
There is an easier way to fix this issue with Mac OS and Homebrew:
Install homebrew if it is not installed yet
$brew install libpng
$pngfix --strip=color --out=file2.png file.png
or to do it with every file in the current directory:
mkdir tmp; for f in ./*.png; do pngfix --strip=color --out=tmp/"$f" "$f"; done
It will create a fixed copy for each png file in the current directory and put it in the the tmp subdirectory. After that, if everything is OK, you just need to override the original files.
Another tip is to use the Keynote and Preview applications to create the icons. I draw them using Keynote, in the size of about 120x120 pixels, over a slide with a white background (the option to make polygons editable is great!). Before exporting to Preview, I draw a rectangle around the icon (without any fill or shadow, just the outline, with the size of about 135x135) and copy everything to the clipboard. After that, you just need to open it with the Preview tool using "New from Clipboard", select a 128x128 pixels area around the icon, copy, use "New from Clipboard" again, and export it to PNG. You won't need to run the pngfix tool.
How can labels/legends be added for all chart types in chart.js (chartjs.org)?
You can include a legend template in the chart options:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
You'll also need to add some basic css to get it looking ok.
jQuery: how do I animate a div rotation?
If you want just a jQuery option, this will work:
$(el).stop().animate(
{rotation: 360},
{
duration: 500,
step: function(now, fx) {
$(this).css({"transform": "rotate("+now+"deg)"});
}
}
);
This works with jQuery 1.8, which takes care of CSS prefixing automatically. jQuery doesn't animate rotation so I'm putting the transform:rotate()
in the custom step
function. It might only work starting from 0.
Demo: http://jsfiddle.net/forresto/ShUgD/
IE9 and Mobile Safari 4 support CSS transforms but not CSS transitions, so I came up with this simple shim, using Modernizr feature testing:
if (Modernizr.csstransitions) {
$(el).css({
"transition": "all 500ms ease-in-out"
});
}
$(el).click(function(){
var rotateTo = 360;
if (Modernizr.csstransitions) {
$(el).css({"transform": "rotate("+rotateTo+"deg)"});
} else {
$(el).stop().animate(
{rotation: rotateTo},
{
duration: 500,
step: function(now, fx) {
$(this).css({"transform": "rotate("+now+"deg)"});
}
}
);
}
});
The above will use CSS transitions when available.
How can I open a website in my web browser using Python?
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open()
function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
How to convert Varchar to Int in sql server 2008?
That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123
to an int.
UPDATE
Based on your comments I would remove any spaces that are in the values you are trying to convert.
Copy existing project with a new name in Android Studio
As free3dom pointed out, here's what should be done:
- Create a copy using file manager
- Manually edit the app's
build.gradle
file to change the package name (you can use the file manager).
- Manually edit
AndroidManifest.xml
to change the package name.
- Run
gradle sync
.
- Open the project in Android Studio, and refactor the package name.
- Run gradle sync, again.
That seems to work without any problems.
When to use which design pattern?
I completely agree with @Peter Rasmussen.
Design patterns provide general solution to commonly occurring design problem.
I would like you to follow below approach.
- Understand intent of each pattern
- Understand checklist or use case of each pattern
- Think of solution to your problem and check if your solution falls into checklist of particular pattern
- If not, simply ignore the design-patterns and write your own solution.
Useful links:
sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java
wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .
Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.
Creating layout constraints programmatically
Hi I have been using this page a lot for constraints and "how to". It took me forever to get to the point of realizing I needed:
myView.translatesAutoresizingMaskIntoConstraints = NO;
to get this example to work. Thank you Userxxx, Rob M. and especially larsacus for the explanation and code here, it has been invaluable.
Here is the code in full to get the examples above to run:
UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor redColor];
myView.translatesAutoresizingMaskIntoConstraints = NO; //This part hung me up
[self.view addSubview:myView];
//needed to make smaller for iPhone 4 dev here, so >=200 instead of 748
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-[myView(>=200)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:[myView(==200)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
java IO Exception: Stream Closed
You call writer.close();
in writeToFile
so the writer has been closed the second time you call writeToFile
.
Why don't you merge FileStatus
into writeToFile
?
Loop through all the resources in a .resx file
The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.
Alternatively, you can use reflection to loop through these names.
Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.GetProperty);
foreach (PropertyInfo info in resourceProps)
{
string name = info.Name;
object value = info.GetValue(null, null); // object can be an image, a string whatever
// do something with name and value
}
This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".
The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.
C char array initialization
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct
or union
.
Example program:
#include <stdio.h>
struct ccont
{
char array[32];
};
struct icont
{
int array[32];
};
int main()
{
int cnt;
char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '\0', '\0', ...
int iarray[32] = { 67, 42, 25 };
struct ccont cc = { 0 };
struct icont ic = { 0 };
/* these don't work
carray = { [0]=1 }; // expected expression before '{' token
carray = { [0 ... 31]=1 }; // (likewise)
carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g)
*/
// but these perfectly work...
cc = (struct ccont){ .array='a' }; // 'a', '\0', '\0', '\0', ...
// the following is a gcc extension,
cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '\0', '\0', ...
ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ...
// index ranges can overlap, the latter override the former
// (no compiler warning with -Wall -Wextra)
ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...
for (cnt=0; cnt<5; cnt++)
printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);
return 0;
}
Recover sa password
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set
authentication mode (Windows or SQL Server) during the installation
process. You will be forced to choose the strong password for sa user
in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to
change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration"
check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate
security best practices that recommend to use windows authentication
mode, have sa login disabled and use strong passwords especially for
sa login.
Install pip in docker
An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine
. They offer pip
out of the box (and have a smaller footprint which leads to faster builds etc).
@selector() in Swift?
Swift itself doesn't use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is
/as
tests instead of respondsToSelector:
, and use closures wherever you can instead of performSelector:
for better type/memory safety.)
But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the Selector
type for working with these. (Swift automatically uses this in place of ObjC's SEL
type.)
In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Swift 4 / Xcode 9):
You can construct a Selector
from a Swift function type using the #selector
expression.
let timer = Timer(timeInterval: 1, target: object,
selector: #selector(MyClass.test),
userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
with: button, with: otherButton)
The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the #selector
expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per the Swift 2.2+ rules for function-type naming.
(This is actually an improvement over ObjC's @selector()
directive, because the compiler's -Wundeclared-selector
check verifies only that the named selector exists. The Swift function reference you pass to #selector
checks existence, membership in a class, and type signature.)
There are a couple of extra caveats for the function references you pass to the #selector
expression:
- Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g.
insertSubview(_:at:)
vs insertSubview(_:aboveSubview:)
). But if a function has no parameters, the only way to disambiguate it is to use an as
cast with the function's type signature (e.g. foo as () -> ()
vs foo(_:)
).
- There's a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a
var foo: Int
, you can use #selector(getter: MyClass.foo)
or #selector(setter: MyClass.foo)
.
General notes:
Cases where #selector
doesn't work, and naming: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a Selector
from a string: e.g. Selector("dynamicMethod:")
— though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:
) for each parameter.
Selector availability: The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the @objc
attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)
Remember that private
symbols aren't exposed to the runtime, too — your method needs to have at least internal
visibility.
Key paths: These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. chris.valueForKeyPath(#keyPath(Person.friends.firstName))
. See SE-0062 for details. And even more KeyPath
stuff in Swift 4, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.
You can read more about selectors under Interacting with Objective-C APIs in Using Swift with Cocoa and Objective-C.
Note: Before Swift 2.2, Selector
conformed to StringLiteralConvertible
, so you might find old code where bare strings are passed to APIs that take selectors. You'll want to run "Convert to Current Swift Syntax" in Xcode to get those using #selector
.
Difference between JSONObject and JSONArray
I know, all of the previous answers are insightful to your question. I had too like you this confusion just one minute before finding this SO thread. After reading some of the answers, here is what I get: A JSONObject is a JSON-like object that can be represented as an element in the array, the JSONArray. In other words, a JSONArray can contain a (or many) JSONObject.
.gitignore file for java eclipse project
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
How to get status code from webclient?
If you are using .Net 4.0 (or less):
class BetterWebClient : WebClient
{
private WebRequest _Request = null;
protected override WebRequest GetWebRequest(Uri address)
{
this._Request = base.GetWebRequest(address);
if (this._Request is HttpWebRequest)
{
((HttpWebRequest)this._Request).AllowAutoRedirect = false;
}
return this._Request;
}
public HttpStatusCode StatusCode()
{
HttpStatusCode result;
if (this._Request == null)
{
throw (new InvalidOperationException("Unable to retrieve the status
code, maybe you haven't made a request yet."));
}
HttpWebResponse response = base.GetWebResponse(this._Request)
as HttpWebResponse;
if (response != null)
{
result = response.StatusCode;
}
else
{
throw (new InvalidOperationException("Unable to retrieve the status
code, maybe you haven't made a request yet."));
}
return result;
}
}
If you are using .Net 4.5.X or newer, switch to HttpClient:
var response = await client.GetAsync("http://www.contoso.com/");
var statusCode = response.StatusCode;
How to POST JSON request using Apache HttpClient?
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
C free(): invalid pointer
You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.
There are two main types of memory you seem to be confusing - stack memory and heap memory.
Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main
, it sets aside some memory for your variables you've declared (p
,token
, and so on).
Heap memory lives from when you malloc
it to when you free
it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!
You have a few errors:
You're trying to free memory that's not heap memory. Don't do that.
You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc
. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.
For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function does allocate heap memory*.
"9.9.1 The malloc and free Functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."
~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011
EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.
adb shell command to make Android package uninstall dialog appear
While the above answers work but in case you have multiple devices connected to your computer then the following command can be used to remove the app from one of them:
adb -s <device-serial> shell pm uninstall <app-package-name>
If you want to find out the device serial then use the following command:
adb devices -l
This will give you a list of devices attached. The left column shows the device serials.
Send request to curl with post data sourced from a file
You're looking for the --data-binary
argument:
curl -i -X POST host:port/post-file \
-H "Content-Type: text/xml" \
--data-binary "@path/to/file"
In the example above, -i
prints out all the headers so that you can see what's going on, and -X POST
makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @
symbol, so curl
knows to read from a file.
How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?
To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.
<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="toolbarStyle">@style/MyToolBarStyle</item>
</style>
<style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
<item name="android:background">#80deea</item>
<item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
<item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
</style>
<style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">35dp</item>
<item name="android:textColor">#ff3d00</item>
</style>
<style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
<item name="android:textSize">30dp</item>
<item name="android:textColor">#1976d2</item>
</style>
Iterating over arrays in Python 3
While iterating over a list or array with this method:
ar = [10, 11, 12]
for i in ar:
theSum = theSum + ar[i]
You are actually getting the values of list or array sequentially in i
variable.
If you print the variable i
inside the for loop
. You will get following output:
10
11
12
However, in your code you are confusing i
variable with index value of array. Therefore, while doing ar[i]
will mean ar[10]
for the first iteration. Which is of course index out of range throwing IndexError
Edit
You can read this for better understanding of different methods of iterating over array or list in Python
Embed website into my site
Put content from other site in iframe
<iframe src="/othersiteurl" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
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's the strangest corner case you've seen in C# or .NET?
I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)
static void Foo<T>() where T : new()
{
T t = new T();
Console.WriteLine(t.ToString()); // works fine
Console.WriteLine(t.GetHashCode()); // works fine
Console.WriteLine(t.Equals(t)); // works fine
// so it looks like an object and smells like an object...
// but this throws a NullReferenceException...
Console.WriteLine(t.GetType());
}
So what was T...
Answer: any Nullable<T>
- such as int?
. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p
Update: the plot thickens... Ayende Rahien threw down a similar challenge on his blog, but with a where T : class, new()
:
private static void Main() {
CanThisHappen<MyFunnyType>();
}
public static void CanThisHappen<T>() where T : class, new() {
var instance = new T(); // new() on a ref-type; should be non-null, then
Debug.Assert(instance != null, "How did we break the CLR?");
}
But it can be defeated! Using the same indirection used by things like remoting; warning - the following is pure evil:
class MyFunnyProxyAttribute : ProxyAttribute {
public override MarshalByRefObject CreateInstance(Type serverType) {
return null;
}
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }
With this in place, the new()
call is redirected to the proxy (MyFunnyProxyAttribute
), which returns null
. Now go and wash your eyes!
Switching to landscape mode in Android Emulator
For those of you with a Chromebook Pixel/Ubuntu/Crouton with no numpad, installing the onboard
keyboard worked for me.
Just press 123 to access the numpad layout, and then press 7
If you're on Unity already, onboard
may already be installed, so just type onboard
from your command line to see if it's there.
If not, just type:
sudo apt-get update
sudo apt-get install onboard
PS: The Chromebook Pixel's upper keys were supposed to represent the traditional F1 through F11 function keys on Ubuntu/Crouton, so you may want to try those special hardware keys first (on their own or in combination with Ctrl). It's just that for me, I'm running an old copy of Crouton, and the only function key that seems to be recognized is F6
C# Inserting Data from a form into an access Database
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}
install beautiful soup using pip
The easy method that will work even in corrupted setup environment is :
To download ez_setup.py and run it using command line
python ez_setup.py
output
Extracting in c:\uu\uu\appdata\local\temp\tmpjxvil3
Now working in c:\u\u\appdata\local\temp\tmpjxvil3\setuptools-5.6
Installing Setuptools
run
pip install beautifulsoup4
output
Downloading/unpacking beautifulsoup4
Running setup.py ... egg_info for package
Installing collected packages: beautifulsoup4
Running setup.py install for beautifulsoup4
Successfully installed beautifulsoup4
Cleaning up...
Bam ! |Done¬
How to lock orientation of one view controller to portrait mode only in Swift
As of iOS 10 and 11, iPad supports Slide Over and Split View. To enable an app in Slide Over and Split View, Requires full screen
must be unchecked. That means the accepted answer cannot be used if the app wants to support Slide Over and Split View. See more from Apple's Adopting Multitasking Enhancements on iPad here.
I have a solution that allows (1) unchecking Requires full screen
, (2) just one function to be implemented in appDelegate
(especially if you don't want to / can't modify the target view controllers), and (3) avoid recursive calls. No need of helper class nor extensions.
appDelegate.swift (Swift 4)
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
// Search for the visible view controller
var vc = window?.rootViewController
// Dig through tab bar and navigation, regardless their order
while (vc is UITabBarController) || (vc is UINavigationController) {
if let c = vc as? UINavigationController {
vc = c.topViewController
} else if let c = vc as? UITabBarController {
vc = c.selectedViewController
}
}
// Look for model view controller
while (vc?.presentedViewController) != nil {
vc = vc!.presentedViewController
}
print("vc = " + (vc != nil ? String(describing: type(of: vc!)) : "nil"))
// Final check if it's our target class. Also make sure it isn't exiting.
// Otherwise, system will mistakenly rotate the presentingViewController.
if (vc is TargetViewController) && !(vc!.isBeingDismissed) {
return [.portrait]
}
return [.all]
}
Edit
@bmjohns pointed out that this function is not called on iPad. I verified and yes it was not called. So, I did a bit more testing and found out some facts:
- I unchecked
Requires full screen
because I want to enable Slide Over and Slide View on iPad. That requires the app to support all 4 orientation for iPad, in Info.plist: Supported interface orientations (iPad)
.
My app works same way as Facebook: on iPhone, most of the time it is locked to portrait. When viewing image in full screen, allows users to rotate landscape for better view. On iPad, users can rotate to any orientation in any view controllers. So, the app looks nice when iPad is stand on Smart Cover (landscape left).
For iPad to call application(_:supportedInterfaceOrientationsFor)
, in Info.plist, only keep portrait for iPad. The app will lose Slide Over + Split View ability. But you can lock or unlock the orientation for any view controller, in just one place and no need to modify ViewController class.
Finally, this function get called on view controller's life cycle, when view is displayed/removed. If your app need to lock/unlock/change orientation in other time, it might not work
Change drawable color programmatically
You may need to call mutate() on the drawable or else all icons are affected.
Drawable icon = ContextCompat.getDrawable(getContext(), R.drawable.ic_my_icon).mutate();
TypedValue typedValue = new TypedValue();
getContext().getTheme().resolveAttribute(R.attr.colorIcon, typedValue, true);
icon.setColorFilter(typedValue.data, PorterDuff.Mode.SRC_ATOP);
How to convert a UTF-8 string into Unicode?
So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string
. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.
public static string DecodeFromUtf8(this string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i=0;i<utf8String.Length;++i) {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}
DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà
This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string
using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length)
.
Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:
public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
// the inverse of `mistake.GetString(originalBytes);`
byte[] originalBytes = mistake.GetBytes(mangledString);
return correction.GetString(originalBytes);
}
UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);
How do I tar a directory of files and folders without including the directory itself?
This Answer should work in most situations. Notice however how the filenames are stored in the tar file as, for example, ./file1
rather than just file1
. I found that this caused problems when using this method to manipulate tarballs used as package files in BuildRoot.
One solution is to use some Bash globs to list all files except for ..
like this:
tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
This is a trick I learnt from this answer.
Now tar will return an error if there are no files matching ..?*
or .[^.]*
, but it will still work. If the error is a problem (you are checking for success in a script), this works:
shopt -s nullglob
tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
shopt -u nullglob
Though now we are messing with shell options, we might decide that it is neater to have *
match hidden files:
shopt -s dotglob
tar -C my_dir -zcvf my_dir.tar.gz *
shopt -u dotglob
This might not work where your shell globs *
in the current directory, so alternatively, use:
shopt -s dotglob
cd my_dir
tar -zcvf ../my_dir.tar.gz *
cd ..
shopt -u dotglob
How to pass a single object[] to a params object[]
The params
parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params
parameter:
1) Calling with an array of the parameter type, in which case the params
keyword has no effect and the array is passed directly to the method:
object[] array = new[] { "1", "2" };
// Foo receives the 'array' argument directly.
Foo( array );
2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:
// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );
// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );
In order to pass in an object array to a method with a "params object[]
" parameter, you can either:
1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:
Foo( new object[] { array } ); // Equivalent to calling convention 1.
2) Or, cast the argument to object
, as mentioned by Adam, in which case the compiler will create the wrapper array for you:
Foo( (object)array ); // Equivalent to calling convention 2.
However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]
" parameter. This would allow you to pass multiple arrays as arguments:
void Foo( params object[][] arrays ) {
foreach( object[] array in arrays ) {
// process array
}
}
...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );
// Equivalent to:
object[][] arrays = new[] {
new[] { "1", "2" },
new[] { "3", "4" }
};
Foo( arrays );
Edit: Raymond Chen describes this behavior and how it relates to the C# specification in a new post.
Throughput and bandwidth difference?
Although there are already few answers to this questions but I think some people still may have doubt in actually visualising the differece b/w throughput and bandwidth just like I had ;) until I read this analogy on quora(full credits to that) which proved really helpful
Consider
A highway which has a capacity of moving ,say, 200 vehicles at a time
but
at a random time someone notices only , say, 150 vehicles moving through it..
say due to some traffic-jam in between...
i.e.
capacity is 200 but not all the time it is fully utilised, actual traffic is only 150 out of a max of 200.
i.e. the bandwidth is 200 per unit time but still actual throughput is 150 ...
I thought it might help someone...
Add params to given URL in Python
You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded).
Check out urllib.urlencode:
>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'
In python3:
from urllib import parse
parse.urlencode({'lang':'en','tag':'python'})
WPF popup window
Simply show a new window with two buttons. Add property to contain user result.
Entity Framework select distinct name
The way that @alliswell showed is completely valid, and there's another way! :)
var result = EFContext.TestAddresses
.GroupBy(ta => ta.Name)
.Select(ta => ta.Key);
I hope it'll be useful to someone.
Google Geocoding API - REQUEST_DENIED
Until the end of 2014, a common source of this error was omitting the mandatory sensor
parameter from the request, as below. However since then this is no longer required:
The sensor Parameter
The Google Maps API previously required that you include the sensor parameter to indicate whether your application used a sensor to determine the user's location. This parameter is no longer required.
Did you specify the sensor
parameter on the request?
"REQUEST_DENIED" indicates that your request was denied, generally because of lack of a sensor parameter.
sensor (required) — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false
What is cardinality in Databases?
A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.
In data modelling terms, cardinality is how one table relates to another.
- 1-1 (one row in table A relates to one row in tableB)
- 1-Many (one row in table A relates to many rows in tableB)
- Many-Many (Many rows in table A relate to many rows in tableB)
There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).
See Wikipedia on Cardinality (data modelling).
When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.
See Wikipedia on Cardinality (SQL statements).
add title attribute from css
Can do, with jQuery:
$(document).ready(function() {
$('.mandatory').each(function() {
$(this).attr('title', $(this).attr('class'));
});
});
Jquery resizing image
You can resize image with this piece of code
var maxWidth = 600;
$("img").each(function () {
var imageWidth = $(this).width();
var imageHeight = $(this).height();
if (imageWidth > maxWidth) {
var percentdiff = (imageWidth - maxWidth) / imageWidth * 100;
$(this).width(maxWidth);
$(this).height(imageHeight - (imageHeight * percentdiff / 100));
}
});