Remove specific rows from a data frame
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
python modify item in list, save back in list
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
RelativeLayout center vertical
If View's height/width = wrap_content
use:
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
If View's height/width = match_parent
use:
android:gravity="center_vertical|center_horizontal"
What's the right way to pass form element state to sibling/parent elements?
With React >= 16.3 you can use ref and forwardRef, to gain access to child's DOM from its parent. Don't use old way of refs anymore.
Here is the example using your case :
import React, { Component } from 'react';
export default class P extends React.Component {
constructor (props) {
super(props)
this.state = {data: 'test' }
this.onUpdate = this.onUpdate.bind(this)
this.ref = React.createRef();
}
onUpdate(data) {
this.setState({data : this.ref.current.value})
}
render () {
return (
<div>
<C1 ref={this.ref} onUpdate={this.onUpdate}/>
<C2 data={this.state.data}/>
</div>
)
}
}
const C1 = React.forwardRef((props, ref) => (
<div>
<input type='text' ref={ref} onChange={props.onUpdate} />
</div>
));
class C2 extends React.Component {
render () {
return <div>C2 reacts : {this.props.data}</div>
}
}
See Refs and ForwardRef for detailed info about refs and forwardRef.
The controller for path was not found or does not implement IController
I hope this helps someone else. I had this problem because, while I had the controller named properly, the class inside the file had a typo in it. I was looking for OrderSearch and the file was OrderSearchController.cs, but the class was OrdersSearchController.
Obviously, they should match, but they don't have to, and your route targets the class, not the filename.
Python string.replace regular expression
re.sub
is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.
Spring Boot REST API - request timeout?
You can try server.connection-timeout=5000
in your application.properties. From the official documentation:
server.connection-timeout= # Time in milliseconds that connectors will
wait for another HTTP request before closing the connection. When not
set, the connector's container-specific default will be used. Use a
value of -1 to indicate no (i.e. infinite) timeout.
On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here: https://stackoverflow.com/a/44484579/2328781
How to get value of a div using javascript
DIV
s do not have a value
property.
Technically, according to the DTDs, they shouldn't have a value
attribute either, but generally you'll want to use .getAttribute()
in this case:
function overlay()
{
var cookieValue = document.getElementById('demo').getAttribute('value');
alert(cookieValue);
}
MVC 4 - how do I pass model data to a partial view?
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two
Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three
pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
How to stop "setInterval"
Store the return of setInterval
in a variable, and use it later to clear the interval.
var timer = null;
$("textarea").blur(function(){
timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
if(timer){
window.clearInterval(timer);
timer = null
}
});
Initializing array of structures
This is quite simple:
my_data
is a before defined structure type.
So you want to declare an my_data
-array of some elements, as you would do with
char a[] = { 'a', 'b', 'c', 'd' };
So the array would have 4 elements and you initialise them as
a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';
This is called a designated initializer (as i remember right).
and it just indicates that data has to be of type my_dat
and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.
forEach is not a function error with JavaScript array
parent.children
is a HTMLCollection
which is array-like object. First, you have to convert it to a real Array
to use Array.prototype
methods.
const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
console.log(child)
})
Running Facebook application on localhost
A trick:
Use MAMPPRO and create:
server name: the EXACT adress of you website (eg: helloworld.com)
to your site on your disk
On Facebook:
So you can keep your original Site URL as well (eg: helloworld.com)
Now you understand that when you type your website on the adress bar you are in local!
..and when you want to be online, just inactive the server on MAMP PRO..
:)
How long do browsers cache HTTP 301s?
On the latest Google Chrome Version 79, you can use the chrome://net-internals
and select on DNS from the left panel, then tap the Clear host cache button
How to make a local variable (inside a function) global
Here are two methods to achieve the same thing:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function
, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print(x) # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print(x)
other_function()
print(x)
Now you will get:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
How to define the basic HTTP authentication using cURL correctly?
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication.
Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which
makes it impossible to use a colon in the user name with this option.
The password can, still.
When using Kerberos V5 with a Windows based server you should include
the Windows domain name in the user name, in order for the server to
succesfully obtain a Kerberos Ticket. If you don't then the initial
authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user
name, without the domain, if there is a single domain and forest in
your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN
(User Principal Name) formats. For example, EXAMPLE\user and
[email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5,
Negotiate, NTLM or Digest authentication then you can tell curl to
select the user name and password from your environment by specifying
a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
Send XML data to webservice using php curl
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:
//Store your XML Request in a variable
$input_xml = '<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>JFK</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<PreferredClass>E</PreferredClass>
<Eticket>true</Eticket>
<Clientid>777ClientID</Clientid>
<Clientpassword>*Your API Password</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>';
Now I've made a little changes in the above curl_setopt declaration as follows:
$url = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.
How to make gradient background in android
Visual examples help with this kind of question.
Boilerplate
In order to create a gradient, you create an xml file in res/drawable. I am calling mine my_gradient_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
</shape>
You set it to the background of some view. For example:
<View
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@drawable/my_gradient_drawable"/>
type="linear"
Set the angle
for a linear
type. It must be a multiple of 45 degrees.
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
type="radial"
Set the gradientRadius
for a radial
type. Using %p
means it is a percentage of the smallest dimension of the parent.
<gradient
android:type="radial"
android:gradientRadius="10%p"
android:startColor="#f6ee19"
android:endColor="#115ede" />
type="sweep"
I don't know why anyone would use a sweep, but I am including it for completeness. I couldn't figure out how to change the angle, so I am only including one image.
<gradient
android:type="sweep"
android:startColor="#f6ee19"
android:endColor="#115ede" />
center
You can also change the center of the sweep or radial types. The values are fractions of the width and height. You can also use %p
notation.
android:centerX="0.2"
android:centerY="0.7"
what innerHTML is doing in javascript?
innerHTML is a property of every element. It tells you what is between the starting and ending tags of the element, and it also let you sets the content of the element.
property describes an aspect of an object. It is something an object has as opposed to something an object does.
<p id="myParagraph">
This is my paragraph.
</p>
You can select the paragraph and then change the value of it's innerHTML with the following command:
document.getElementById("myParagraph").innerHTML = "This is my paragraph";
MySQL parameterized queries
As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
insert='insert into Songs ({0}) values ({1})'.
.format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
args = [ meta[i] for i in meta_cols ]
cursor=db.cursor()
cursor.execute(insert,args)
db.commit()
Where meta is the dictionary holding the values to insert. Update can be done in the same way:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
update='update Songs set {0} where id=%s'.
.format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
args = [ meta[i] for i in meta_cols ]
args.append( songid )
cursor=db.cursor()
cursor.execute(update,args)
db.commit()
Using msbuild to execute a File System Publish Profile
Found the answer here:
http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild
Visual Studio 2010 has great new Web Application Project publishing
features that allow you to easy publish your web app project with a
click of a button. Behind the scenes the Web.config transformation and
package building is done by a massive MSBuild script that’s imported
into your project file (found at: C:\Program Files
(x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets).
Unfortunately, the script is hugely complicated, messy and
undocumented (other then some oft-badly spelled and mostly useless
comments in the file). A big flowchart of that file and some
documentation about how to hook into it would be nice, but seems to be
sadly lacking (or at least I can’t find it).
Unfortunately, this means performing publishing via the command line
is much more opaque than it needs to be. I was surprised by the lack
of documentation in this area, because these days many shops use a
continuous integration server and some even do automated deployment
(which the VS2010 publishing features could help a lot with), so I
would have thought that enabling this (easily!) would be have been a
fairly main requirement for the feature.
Anyway, after digging through the Microsoft.Web.Publishing.targets
file for hours and banging my head against the trial and error wall,
I’ve managed to figure out how Visual Studio seems to perform its
magic one click “Publish to File System” and “Build Deployment
Package” features. I’ll be getting into a bit of MSBuild scripting, so
if you’re not familiar with MSBuild I suggest you check out this crash
course MSDN page.
Publish to File System
The VS2010 Publish To File System Dialog Publish to File System took
me a while to nut out because I expected some sensible use of MSBuild
to be occurring. Instead, VS2010 does something quite weird: it calls
on MSBuild to perform a sort of half-deploy that prepares the web
app’s files in your project’s obj folder, then it seems to do a manual
copy of those files (ie. outside of MSBuild) into your target publish
folder. This is really whack behaviour because MSBuild is designed to
copy files around (and other build-related things), so it’d make sense
if the whole process was just one MSBuild target that VS2010 called
on, not a target then a manual copy.
This means that doing this via MSBuild on the command-line isn’t as
simple as invoking your project file with a particular target and
setting some properties. You’ll need to do what VS2010 ought to have
done: create a target yourself that performs the half-deploy then
copies the results to the target folder. To edit your project file,
right click on the project in VS2010 and click Unload Project, then
right click again and click Edit. Scroll down until you find the
Import element that imports the web application targets
(Microsoft.WebApplication.targets; this file itself imports the
Microsoft.Web.Publishing.targets file mentioned earlier). Underneath
this line we’ll add our new target, called PublishToFileSystem:
<Target Name="PublishToFileSystem"
DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
<Error Condition="'$(PublishDestination)'==''"
Text="The PublishDestination property must be set to the intended publishing destination." />
<MakeDir Condition="!Exists($(PublishDestination))"
Directories="$(PublishDestination)" />
<ItemGroup>
<PublishFiles Include="$(_PackageTempDir)\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PublishFiles)"
DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="True" />
</Target>
This target depends on the
PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010
calls before it does its manual copy. Some digging around in
Microsoft.Web.Publishing.targets shows that calling this target causes
the project files to be placed into the directory specified by the
property _PackageTempDir.
The first task we call in our target is the Error task, upon which
we’ve placed a condition that ensures that the task only happens if
the PublishDestination property hasn’t been set. This will catch you
and error out the build in case you’ve forgotten to specify the
PublishDestination property. We then call the MakeDir task to create
that PublishDestination directory if it doesn’t already exist.
We then define an Item called PublishFiles that represents all the
files found under the _PackageTempDir folder. The Copy task is then
called which copies all those files to the Publish Destination folder.
The DestinationFiles attribute on the Copy element is a bit complex;
it performs a transform of the items and converts their paths to new
paths rooted at the PublishDestination folder (check out Well-Known
Item Metadata to see what those %()s mean).
To call this target from the command-line we can now simply perform
this command (obviously changing the project file name and properties
to suit you):
msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem
How to use LINQ to select object with minimum or maximum property value
So you are asking for ArgMin
or ArgMax
. C# doesn't have a built-in API for those.
I've been looking for a clean and efficient (O(n) in time) way to do this. And I think I found one:
The general form of this pattern is:
var min = data.Select(x => (key(x), x)).Min().Item2;
^ ^ ^
the sorting key | take the associated original item
Min by key(.)
Specially, using the example in original question:
For C# 7.0 and above that supports value tuple:
var youngest = people.Select(p => (p.DateOfBirth, p)).Min().Item2;
For C# version before 7.0, anonymous type can be used instead:
var youngest = people.Select(p => new {age = p.DateOfBirth, ppl = p}).Min().ppl;
They work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1
vs x2
, then y1
vs y2
. That's why the built-in .Min
can be used on those types.
And since both anonymous type and value tuple are value types, they should be both very efficient.
NOTE
In my above ArgMin
implementations I assumed DateOfBirth
to take type DateTime
for simplicity and clarity. The original question asks to exclude those entries with null DateOfBirth
field:
Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).
It can be achieved with a pre-filtering
people.Where(p => p.DateOfBirth.HasValue)
So it's immaterial to the question of implementing ArgMin
or ArgMax
.
NOTE 2
The above approach has a caveat that when there are two instances that have the same min value, then the Min()
implementation will try to compare the instances as a tie-breaker. However, if the class of the instances does not implement IComparable
, then a runtime error will be thrown:
At least one object must implement IComparable
Luckily, this can still be fixed rather cleanly. The idea is to associate a distanct "ID" with each entry that serves as the unambiguous tie-breaker. We can use an incremental ID for each entry. Still using the people age as example:
var youngest = Enumerable.Range(0, int.MaxValue)
.Zip(people, (idx, ppl) => (ppl.DateOfBirth, idx, ppl)).Min().Item3;
How to echo in PHP, HTML tags
You need to escape the "
so that PHP doesn't recognise them as part of your PHP code. You do this by using the \
escape character.
So, your code would look like this:
echo
"<div>
<h3><a href=\"#\">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<div>"
Returning boolean if set is empty
When you say:
c is not None
You are actually checking if c and None reference the same object. That is what the "is" operator does. In python None is a special null value conventionally meaning you don't have a value available. Sorta like null in c or java. Since python internally only assigns one None value using the "is" operator to check if something is None (think null) works, and it has become the popular style. However this does not have to do with the truth value of the set c, it is checking that c actually is a set rather than a null value.
If you want to check if a set is empty in a conditional statement, it is cast as a boolean in context so you can just say:
c = set()
if c:
print "it has stuff in it"
else:
print "it is empty"
But if you want it converted to a boolean to be stored away you can simply say:
c = set()
c_has_stuff_in_it = bool(c)
List all tables in postgresql information_schema
For private schema 'xxx'
in postgresql :
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'
Without table_type = 'BASE TABLE'
, you will list tables and views
How to determine a user's IP address in node
In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this:
proxy_set_header X-Real-IP $remote_addr;
Then in your app.js:
app.set('trust proxy', true);
After that, wherever you want it to appear:
var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;
How to get the last char of a string in PHP?
From PHP 7.1 you can do this (Accepted rfc for negative string offsets):
<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();
I'll let you guess the output.
Also, I added this to xenonite's performance code with these results:
substr() took 7.0334868431091seconds
array access took 2.3111131191254seconds
Direct string access (negative string offsets) took 1.7971360683441seconds
Generate a UUID on iOS from Swift
Also you can
use it lowercase
under below
let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)
Output
68b696d7-320b-4402-a412-d9cee10fc6a3
Thank you !
Full Screen Theme for AppCompat
just this ?
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen">
<item name="android:windowFullscreen">true</item>
</style>
How can I clear the NuGet package cache using the command line?
Clearing the cache
With dotnet core cli
dotnet nuget locals all --clear
With Visual Studio 2017
- Go to menu Tools ? NuGet Package Manager ? Package Manager Settings.
- Click Clear All NuGet Cache(s):
With the nuget cli
Download and install the NuGet command line tool.
nuget locals all -clear
With windows command line
del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q
(can be used in a .bat
file)
With PowerShell
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg
Or 'quiet' mode (without error messages):
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null
Cache location
Windows
%userprofile%\.nuget\packages
Linux
~/.nuget/
Build server
%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache
Example:
C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache
This answer is a rollup of all the existing answers for your convenience
"Eliminate render-blocking CSS in above-the-fold content"
Few tips that may help:
I came across this article in CSS optimization yesterday:
CSS profiling for ... optimization
A lot of useful info on CSS and what CSS causes the most performance drains.
I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools:
DevTools Can do that.
Check out the sections on Time to First Paint, repaints and costly CSS.
Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.
Off the question:
I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.
Getting values from JSON using Python
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
Font scaling based on width of container
HTML
<div style="height:100px; width:200px;">
<div id='qwe'>
test
</div>
</div>
JavaScript code for maximizing font-size:
var fontSize, maxHeight, maxWidth, textElement, parentElement;
textElement = document.getElementById('qwe');
parentElement = textElement.parentElement;
maxHeight = parentElement.clientHeight;
maxWidth = parentElement.clientWidth;
fontSize = maxHeight;
var minFS = 3, maxFS = fontSize;
while (fontSize != minFS) {
textElement.style.fontSize = `${fontSize}px`;
if (textElement.offsetHeight < maxHeight && textElement.offsetWidth <= maxWidth) {
minFS = fontSize;
} else{
maxFS = fontSize;
}
fontSize = Math.floor((minFS + maxFS)/2);
}
textElement.style.fontSize = `${minFS}px`;
List files recursively in Linux CLI with path relative to the current directory
Here is a Perl script:
sub format_lines($)
{
my $refonlines = shift;
my @lines = @{$refonlines};
my $tmppath = "-";
foreach (@lines)
{
next if ($_ =~ /^\s+/);
if ($_ =~ /(^\w+(\/\w*)*):/)
{
$tmppath = $1 if defined $1;
next;
}
print "$tmppath/$_";
}
}
sub main()
{
my @lines = ();
while (<>)
{
push (@lines, $_);
}
format_lines(\@lines);
}
main();
usage:
ls -LR | perl format_ls-LR.pl
"Fatal error: Cannot redeclare <function>"
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
Convert array values from string to int?
So I was curious about the performance of some of the methods mentioned in the answers for large number of integers.
Preparation
Just creating an array of 1 million random integers between 0 and 100. Than, I imploded them to get the string.
$integers = array();
for ($i = 0; $i < 1000000; $i++) {
$integers[] = rand(0, 100);
}
$long_string = implode(',', $integers);
Method 1
This is the one liner from Mark's answer:
$integerIDs = array_map('intval', explode(',', $long_string));
Method 2
This is the JSON approach:
$integerIDs = json_decode('[' . $long_string . ']', true);
Method 3
I came up with this one as modification of Mark's answer. This is still using explode()
function, but instead of calling array_map()
I'm using regular foreach
loop to do the work to avoid the overhead array_map()
might have. I am also parsing with (int)
vs intval()
, but I tried both, and there is not much difference in terms of performance.
$result_array = array();
$strings_array = explode(',', $long_string);
foreach ($strings_array as $each_number) {
$result_array[] = (int) $each_number;
}
Results:
Method 1 Method 2 Method 3
0.4804770947 0.3608930111 0.3387751579
0.4748001099 0.363986969 0.3762528896
0.4625790119 0.3645150661 0.3335959911
0.5065748692 0.3570590019 0.3365750313
0.4803431034 0.4135499001 0.3330330849
0.4510772228 0.4421861172 0.341176033
0.503674984 0.3612480164 0.3561749458
0.5598649979 0.352314949 0.3766179085
0.4573421478 0.3527538776 0.3473439217
0.4863037268 0.3742785454 0.3488383293
The bottom line is the average. It looks like the first method was a little slower for 1 million integers, but I didn't notice 3x performance gain of Method 2 as stated in the answer. It turned out foreach
loop was the quickest one in my case. I've done the benchmarking with Xdebug.
Edit: It's been a while since the answer was originally posted. To clarify, the benchmark was done in php 5.6.
How to create a label inside an <input> element?
The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:
- Relatively position a div that contains the input and label
- Absolutely position the label
- Absolutely position the input on top of the label
- Remove the borders of the input and set its background-color to transparent
Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.
how to query child objects in mongodb
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
Removing duplicate elements from an array in Swift
In Swift 3.0 the simplest and fastest solution I've found to eliminate the duplicated elements while keeping the order:
extension Array where Element:Hashable {
var unique: [Element] {
var set = Set<Element>() //the unique list kept in a Set for fast retrieval
var arrayOrdered = [Element]() //keeping the unique list of elements but ordered
for value in self {
if !set.contains(value) {
set.insert(value)
arrayOrdered.append(value)
}
}
return arrayOrdered
}
}
Writing Unicode text to a text file?
How to print unicode characters into a file:
Save this to file: foo.py:
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')
Run it and pipe output to file:
python foo.py > tmp.txt
Open tmp.txt and look inside, you see this:
el@apollo:~$ cat tmp.txt
e with obfuscation: é
Thus you have saved unicode e with a obfuscation mark on it to a file.
Graph visualization library in JavaScript
Disclaimer: I'm a developer of Cytoscape.js
Cytoscape.js is a HTML5 graph visualisation library. The API is sophisticated and follows jQuery conventions, including
- selectors for querying and filtering (
cy.elements("node[weight >= 50].someClass")
does much as you would expect),
- chaining (e.g.
cy.nodes().unselect().trigger("mycustomevent")
),
- jQuery-like functions for binding to events,
- elements as collections (like jQuery has collections of HTMLDomElements),
- extensibility (can add custom layouts, UI, core & collection functions, and so on),
- and more.
If you're thinking about building a serious webapp with graphs, you should at least consider Cytoscape.js. It's free and open-source:
http://js.cytoscape.org
Event on a disabled input
Disabled elements "eat" clicks in some browsers - they neither respond to them, nor allow them to be captured by event handlers anywhere on either the element or any of its containers.
IMHO the simplest, cleanest way to "fix" this (if you do in fact need to capture clicks on disabled elements like the OP does) is just to add the following CSS to your page:
input[disabled] {pointer-events:none}
This will make any clicks on a disabled input fall through to the parent element, where you can capture them normally. (If you have several disabled inputs, you might want to put each into an individual container of its own, if they aren't already laid out that way - an extra <span>
or a <div>
, say - just to make it easy to distinguish which disabled input was clicked).
The downside is that this trick unfortunately won't works for older browsers that don't support the pointer-events
CSS property. (It should work from IE 11, FF v3.6, Chrome v4): caniuse.com/#search=pointer-events
If you need to support older browsers, you'll need to use one of the other answers!
"Input string was not in a correct format."
You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.
How to check user is "logged in"?
I managed to find the correct one. It is below.
bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
EDIT
The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated
What is the height of iPhone's onscreen keyboard?
I can't find latest answer, so I check it all with simulator.(iOS 11.0)
Device | Screen Height | Portrait | Landscape
iPhone 4s | 480.0 | 216.0 | 162.0
iPhone 5, iPhone 5s, iPhone SE | 568.0 | 216.0 | 162.0
iPhone 6, iPhone 6s, iPhone 7, iPhone 8, iPhone X | 667.0 | 216.0 | 162.0
iPhone 6 plus, iPhone 7 plus, iPhone 8 plus | 736.0 | 226.0 | 162.0
iPad 5th generation, iPad Air, iPad Air 2, iPad Pro 9.7, iPad Pro 10.5, iPad Pro 12.9 | 1024.0 | 265.0 | 353.0
Thanks!
Undefined or null for AngularJS
You can always add it exactly for your application
angular.isUndefinedOrNull = function(val) {
return angular.isUndefined(val) || val === null
}
You cannot call a method on a null-valued expression
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
Convert Unicode to ASCII without errors in Python
2018 Update:
As of February 2018, using compressions like gzip
has become quite popular (around 73% of all websites use it, including large sites like Google, YouTube, Yahoo, Wikipedia, Reddit, Stack Overflow and Stack Exchange Network sites).
If you do a simple decode like in the original answer with a gzipped response, you'll get an error like or similar to this:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte
In order to decode a gzpipped response you need to add the following modules (in Python 3):
import gzip
import io
Note: In Python 2 you'd use StringIO
instead of io
Then you can parse the content out like this:
response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource
This code reads the response, and places the bytes in a buffer. The gzip
module then reads the buffer using the GZipFile
function. After that, the gzipped file can be read into bytes again and decoded to normally readable text in the end.
Original Answer from 2010:
Can we get the actual value used for link
?
In addition, we usually encounter this problem here when we are trying to .encode()
an already encoded byte string. So you might try to decode it first as in
html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")
As an example:
html = '\xa0'
encoded_str = html.encode("utf8")
Fails with
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
While:
html = '\xa0'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")
Succeeds without error. Do note that "windows-1252" is something I used as an example. I got this from chardet and it had 0.5 confidence that it is right! (well, as given with a 1-character-length string, what do you expect) You should change that to the encoding of the byte string returned from .urlopen().read()
to what applies to the content you retrieved.
Another problem I see there is that the .encode()
string method returns the modified string and does not modify the source in place. So it's kind of useless to have self.response.out.write(html)
as html is not the encoded string from html.encode (if that is what you were originally aiming for).
As Ignacio suggested, check the source webpage for the actual encoding of the returned string from read()
. It's either in one of the Meta tags or in the ContentType header in the response. Use that then as the parameter for .decode()
.
Do note however that it should not be assumed that other developers are responsible enough to make sure the header and/or meta character set declarations match the actual content. (Which is a PITA, yeah, I should know, I was one of those before).
What certificates are trusted in truststore?
Is there any equivalent for the truststore? How can I view the trusted
certificates?
Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)
No other difference
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How do I connect C# with Postgres?
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show
you the basics of using a PostgreSQL
database in your .NET application. The
reason why I'm doing this is the lack
of PostgreSQL articles on CodeProject
despite the fact that it is a very
good RDBMS. I have used PostgreSQL
back in the days when PHP was my main
programming language, and I
thought.... well, why not use it in my
C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
415 Unsupported Media Type - POST json to OData service in lightswitch 2012
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
- Make the Content-Type "application/json;odata=verbose" in your POST request, or
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
Fixing npm path in Windows 8 and 10
If after installing your npm successfully, and you want to install VueJS then this is what you should do
after running the following command (as Admin)
npm install --global vue-cli
It will place the vue.cmd in the following directory
C:\Users\YourUserName\AppData\Roaming\npm
you will see this in your directory.
Now to use vue as a command in cmd. Open the cmd as admin and run the following command.
setx /M path "%path%;%appdata%\npm"
Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.
I hope this helps.
Get cookie by name
Following function will return a key-value
pair of the required cookie, where key
is the cookie name and value
will be the value of the cookie.
/**
* Returns cookie key-value pair
*/
var getCookieByName = function(name) {
var result = ['-1','-1'];
if(name) {
var cookieList = document.cookie.split(';');
result = $.grep(cookieList,function(cookie) {
cookie = cookie.split('=')[0];
return cookie == name;
});
}
return result;
};
Maintaining href "open in new tab" with an onClick handler in React
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
CSS position:fixed inside a positioned element
I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div
. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed;
relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div
to position: relative;
and having a button wrapper with position: absolute;
and the button of course is position: fixed;
as follows:
<div class="wrapper">
<div class="content">
Your long content here
</div>
<div class="button-wrapper">
<button class="button">This is your button</button>
</div>
</div>
<style>
.wrapper {
position: relative;
}
.button-wrapper {
position: absolute;
right: 0;
top: 0;
width: 50px;
}
.button {
position: fixed;
top: 0;
width: 50px;
}
</style>
working example
*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.
How to see data from .RData file?
If you have a lot of variables in your Rdata
file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.
load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )
# Access individual variables in the RData file using '$' operator
isfar_env$var_name
# List all of the variable names in RData:
ls(isfar_env)
JSON Stringify changes time of date because of UTC
Here is something really neat and simple (atleast I believe so :)) and requires no manipulation of date to be cloned or overloading any of browser's native functions like toJSON (reference: How to JSON stringify a javascript Date and preserve timezone, courtsy Shawson)
Pass a replacer function to JSON.stringify that stringifies stuff to your heart's content!!! This way you don't have to do hour and minute diffs or any other manipulations.
I have put in console.logs to see intermediate results so it is clear what is going on and how recursion is working. That reveals something worthy of notice: value param to replacer is already converted to ISO date format :). Use this[key] to work with original data.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
Converting pfx to pem using openssl
You can use the OpenSSL Command line tool. The following commands should do the trick
openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts
openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts
If you want your file to be password protected etc, then there are additional options.
You can read the entire documentation here.
How to copy directories in OS X 10.7.3?
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
How to encode the filename parameter of Content-Disposition header in HTTP?
We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">
, and setting that in the url-encoded form in a new HTML <input type="hidden">
. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.
Of course this does not directly answer OPs question, but may be a solution for others.
Awaiting multiple Tasks with different results
Given three tasks - FeedCat()
, SellHouse()
and BuyCar()
, there are two interesting cases: either they all complete synchronously (for some reason, perhaps caching or an error), or they don't.
Let's say we have, from the question:
Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
// what here?
}
Now, a simple approach would be:
Task.WhenAll(x, y, z);
but ... that isn't convenient for processing the results; we'd typically want to await
that:
async Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
await Task.WhenAll(x, y, z);
// presumably we want to do something with the results...
return DoWhatever(x.Result, y.Result, z.Result);
}
but this does lots of overhead and allocates various arrays (including the params Task[]
array) and lists (internally). It works, but it isn't great IMO. In many ways it is simpler to use an async
operation and just await
each in turn:
async Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
// do something with the results...
return DoWhatever(await x, await y, await z);
}
Contrary to some of the comments above, using await
instead of Task.WhenAll
makes no difference to how the tasks run (concurrently, sequentially, etc). At the highest level, Task.WhenAll
predates good compiler support for async
/await
, and was useful when those things didn't exist. It is also useful when you have an arbitrary array of tasks, rather than 3 discreet tasks.
But: we still have the problem that async
/await
generates a lot of compiler noise for the continuation. If it is likely that the tasks might actually complete synchronously, then we can optimize this by building in a synchronous path with an asynchronous fallback:
Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
if(x.Status == TaskStatus.RanToCompletion &&
y.Status == TaskStatus.RanToCompletion &&
z.Status == TaskStatus.RanToCompletion)
return Task.FromResult(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
async Task Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await x, await y, await z);
}
This "sync path with async fallback" approach is increasingly common especially in high performance code where synchronous completions are relatively frequent. Note it won't help at all if the completion is always genuinely asynchronous.
Additional things that apply here:
with recent C#, a common pattern is for the async
fallback method is commonly implemented as a local function:
Task<string> DoTheThings() {
async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await a, await b, await c);
}
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
if(x.Status == TaskStatus.RanToCompletion &&
y.Status == TaskStatus.RanToCompletion &&
z.Status == TaskStatus.RanToCompletion)
return Task.FromResult(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
prefer ValueTask<T>
to Task<T>
if there is a good chance of things ever completely synchronously with many different return values:
ValueTask<string> DoTheThings() {
async ValueTask<string> Awaited(ValueTask<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await a, await b, await c);
}
ValueTask<Cat> x = FeedCat();
ValueTask<House> y = SellHouse();
ValueTask<Tesla> z = BuyCar();
if(x.IsCompletedSuccessfully &&
y.IsCompletedSuccessfully &&
z.IsCompletedSuccessfully)
return new ValueTask<string>(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
if possible, prefer IsCompletedSuccessfully
to Status == TaskStatus.RanToCompletion
; this now exists in .NET Core for Task
, and everywhere for ValueTask<T>
AngularJS multiple filter with custom filter function
Try this:
<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">
$scope.ageFilter = function (player) {
return (player.age > $scope.min_age && player.age < $scope.max_age);
}
How to handle button clicks using the XML onClick within Fragments
The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.
What I've been doing during conversions is simply adding a click listener that calls the old event handler.
for instance:
final Button loginButton = (Button) view.findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
onLoginClicked(v);
}
});
setInterval in a React app
Updated 10-second countdown using Hooks (a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha).
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const Clock = () => {
const [currentCount, setCount] = useState(10);
const timer = () => setCount(currentCount - 1);
useEffect(
() => {
if (currentCount <= 0) {
return;
}
const id = setInterval(timer, 1000);
return () => clearInterval(id);
},
[currentCount]
);
return <div>{currentCount}</div>;
};
const App = () => <Clock />;
ReactDOM.render(<App />, document.getElementById('root'));
Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0
You can find it in Nuget Package Microsoft ASP.NET Web Pages Version 3.2.0
If you have a reference to an earlier version than 3.0.0.0, Delete the reference, add the reference to the correct .dll in your packages folder and make sure "Copy Local" is set to "True" in the properties of the .dll.
Then in your web.config (as mentioned by @MichaelEvanchik)
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
Violation Long running JavaScript task took xx ms
Forced reflow often happens when you have a function called multiple times before the end of execution.
For example, you may have the problem on a smartphone, but not on a classic browser.
I suggest using a setTimeout
to solve the problem.
This isn't very important, but I repeat, the problem arises when you call a function several times, and not when the function takes more than 50 ms. I think you are mistaken in your answers.
- Turn off 1-by-1 calls and reload the code to see if it still produces the error.
- If a second script causes the error, use a
setTimeOut
based on the duration of the violation.
Pass Parameter to Gulp Task
It's a feature programs cannot stay without. You can try yargs.
npm install --save-dev yargs
You can use it like this:
gulp mytask --production --test 1234
In the code, for example:
var argv = require('yargs').argv;
var isProduction = (argv.production === undefined) ? false : true;
For your understanding:
> gulp watch
console.log(argv.production === undefined); <-- true
console.log(argv.test === undefined); <-- true
> gulp watch --production
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- true
console.log(argv.test); <-- undefined
> gulp watch --production --test 1234
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- false
console.log(argv.test); <-- 1234
Hope you can take it from here.
There's another plugin that you can use, minimist. There's another post where there's good examples for both yargs and minimist: (Is it possible to pass a flag to Gulp to have it run tasks in different ways?)
Regex that accepts only numbers (0-9) and NO characters
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
How to render pdfs using C#
You could google for PDF viewer component, and come up with more than a few hits.
If you don't really need to embed them in your app, though - you can just require Acrobat Reader or FoxIt (or bundle it, if it meets their respective licensing terms) and shell out to it. It's not as cool, but it gets the job done for free.
Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch
tl;dr Set the editor to something nicer, like Sublime or Atom
Here nice is used in the meaning of an editor you like or find more user friendly.
The underlying problem is that Git by default uses an editor that is too unintuitive to use for most people: Vim. Now, don't get me wrong, I love Vim, and while you could set some time aside (like a month) to learn Vim and try to understand why some people think Vim is the greatest editor in existence, there is a quicker way of fixing this problem :-)
The fix is not to memorize cryptic commands, like in the accepted answer, but configuring Git to use an editor that you like and understand! It's really as simple as configuring either of these options
- the git config setting
core.editor
(per project, or globally)
- the
VISUAL
or EDITOR
environment variable (this works for other programs as well)
I'll cover the first option for a couple of popular editors, but GitHub has an excellent guide on this for many editors as well.
To use Atom
Straight from its docs, enter this in a terminal:
git config --global core.editor "atom --wait"
Git normally wait for the editor command to finish, but since Atom forks to a background process immediately, this won't work, unless you give it the --wait
option.
To use Sublime Text
For the same reasons as in the Atom case, you need a special flag to signal to the process that it shouldn't fork to the background:
git config --global core.editor "subl -n -w"
Python: "TypeError: __str__ returned non-string" but still prints to output?
The problem that you are facing is :
TypeError : str returned non-string (type NoneType)
Here you have to understand the str function's working:
the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one.
In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used.
This was the explaination for your error
You can solve this problem by using the return in str function like:
*simply returnig the string value instead of printing it
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return self.summary
but if the value you are returning in not of string type then you can do like this to return string value from your str function
*typeconverting the value to string that your str function returns
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return str(self.summary)
`
What is 0x10 in decimal?
The simple version is 0x is a prefix denoting a hexadecimal number, source.
So the value you're computing is after the prefix, in this case 10.
But that is not the number 10. The most significant bit 1
denotes the hex value while 0
denotes the units.
So the simple math you would do is
0x10
1 * 16 + 0 = 16
Note - you use 16 because hex is base 16.
Another example:
0xF7
15 * 16 + 7 = 247
You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.
How to do "If Clicked Else .."
You may actually mean hovering the element by not clicking, right?
jQuery('#id').click(function()
{
// execute on click
}).hover(function()
{
// execute on hover
});
Clarify your question then we'll be able to understand better.
Simply if an element isn't being clicked on, do a setInterval
to continue the process until clicked.
var checkClick = setInterval(function()
{
// do something when the element hasn't been clicked yet
}, 2000); // every 2 seconds
jQuery('#id').click(function()
{
clearInterval(checkClick); // this is optional, but it will
// clear the interval once the element
// has been clicked on
// do something else
})
How to specify the JDK version in android studio?
This is old question but still my answer may help someone
For checking Java version in android studio version ,
simply open Terminal of Android Studio and type
java -version
This will display java version installed in android studio
Undo working copy modifications of one file in Git?
I always get confused with this, so here is a reminder test case; let's say we have this bash
script to test git
:
set -x
rm -rf test
mkdir test
cd test
git init
git config user.name test
git config user.email [email protected]
echo 1 > a.txt
echo 1 > b.txt
git add *
git commit -m "initial commit"
echo 2 >> b.txt
git add b.txt
git commit -m "second commit"
echo 3 >> b.txt
At this point, the change is not staged in the cache, so git status
is:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
If from this point, we do git checkout
, the result is this:
$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean
If instead we do git reset
, the result is:
$ git reset HEAD -- b.txt
Unstaged changes after reset:
M b.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
So, in this case - if the changes are not staged, git reset
makes no difference, while git checkout
overwrites the changes.
Now, let's say that the last change from the script above is staged/cached, that is to say we also did git add b.txt
at the end.
In this case, git status
at this point is:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: b.txt
If from this point, we do git checkout
, the result is this:
$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean
If instead we do git reset
, the result is:
$ git reset HEAD -- b.txt
Unstaged changes after reset:
M b.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
So, in this case - if the changes are staged, git reset
will basically make staged changes into unstaged changes - while git checkout
will overwrite the changes completely.
How to count check-boxes using jQuery?
You could do:
var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
EDIT
Or even simple
var numberNotChecked = $('input:checkbox:not(":checked")').length;
How to install the JDK on Ubuntu Linux
In case you have already downloaded the ZIP file follow these steps.
Run the following command to unzip your file.
tar -xvf ~/Downloads/jdk-7u3-linux-i586.tar.gz
sudo mkdir -p /usr/lib/jvm/jdk1.7.0
sudo mv jdk1.7.0_03/* /usr/lib/jvm/jdk1.7.0/
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
After installation is complete, set environment variables as follows.
Edit the system path in file /etc/profile
:
sudo gedit /etc/profile
Add the following lines at the end.
JAVA_HOME=/usr/lib/jvm/jdk1.7.0
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH
Source: http://javaandme.com/
JAX-RS / Jersey how to customize error handling?
I too like StaxMan would probably implement that QueryParam as a String, then handle the conversion, rethrowing as necessary.
If the locale specific behavior is the desired and expected behavior, you would use the following to return the 400 BAD REQUEST error:
throw new WebApplicationException(Response.Status.BAD_REQUEST);
See the JavaDoc for javax.ws.rs.core.Response.Status for more options.
Pointer vs. Reference
Pass by const reference unless there is a reason you wish to change/keep the contents you are passing in.
This will be the most efficient method in most cases.
Make sure you use const on each parameter you do not wish to change, as this not only protects you from doing something stupid in the function, it gives a good indication to other users what the function does to the passed in values. This includes making a pointer const when you only want to change whats pointed to...
How to change font-color for disabled input?
It is the solution that I found for this problem:
//If IE
inputElement.writeAttribute("unselectable", "on");
//Other browsers
inputElement.writeAttribute("disabled", "disabled");
By using this trick, you can add style sheet to your input element that works in IE and other browsers on your not-editable input box.
"Series objects are mutable and cannot be hashed" error
Shortly: gene_name[x]
is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.
Further explanation:
Mutable objects are objects which value can be changed.
For example, list
is a mutable object, since you can append to it. int
is an immutable object, because you can't change it. When you do:
a = 5;
a = 3;
You don't change the value of a
, you create a new object and make a
point to its value.
Mutable objects cannot be hashed. See this answer.
To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple
, string
, int
.
Parsing JSON string in Java
Correct me if i'm wrong, but json is just text seperated by ":", so just use
String line = ""; //stores the text to parse.
StringTokenizer st = new StringTokenizer(line, ":");
String input1 = st.nextToken();
keep using st.nextToken() until you're out of data. Make sure to use "st.hasNextToken()" so you don't get a null exception.
How do you display a Toast from a background thread on Android?
I encountered the same problem:
E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.languoguang.welcomeapp, PID: 4724
java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
at android.widget.Toast$TN.<init>(Toast.java:393)
at android.widget.Toast.<init>(Toast.java:117)
at android.widget.Toast.makeText(Toast.java:280)
at android.widget.Toast.makeText(Toast.java:270)
at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4724 SIG: 9
Application terminated.
Before: onCreate function
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
thread.start();
After: onCreate function
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
it worked.
get UTC time in PHP
As previously answered here, since PHP 5.2.0 you can use the DateTime
class and specify the UTC timezone with an instance of DateTimeZone
.
The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.
$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC
How do you return a JSON object from a Java Servlet
Gson is very usefull for this. easier even.
here is my example:
public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;
class InnerBean
{
private int edad=12;
}
public Bean() {
datosCriticos = new ArrayList<>();
datosCriticos.add(new InnerBean());
}
}
Bean bean = new Bean();
Gson gson = new Gson();
String json =gson.toJson(bean);
out.print(json);
{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}
Have to say people if yours vars are empty when using gson it wont build the json for you.Just the
{}
How to overcome root domain CNAME restrictions?
CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.
Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.
Per RFC:
If a CNAME RR is present at a node, no other data should be
present;
And Per IETF 'Common DNS Operational and Configuration Errors' Document:
This is often attempted by inexperienced administrators as an obvious
way to allow your domain name to also be a host. However, DNS
servers like BIND will see the CNAME and refuse to add any other
resources for that name. Since no other records are allowed to
coexist with a CNAME, the NS entries are ignored. Therefore all the
hosts in the podunk.xx domain are ignored as well!
References:
wp_nav_menu change sub-menu class name?
You don't need to extend the Walker. This will do:
function overrideSubmenuClasses( $classes ) {
$classes[] = 'myclass1';
$classes[] = 'myclass2';
return $classes;
}
add_action('nav_menu_submenu_css_class', 'overrideSubmenuClasses');
Format a Go string without printing?
I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter
it works in following manner:
func TestStrFormat(t *testing.T) {
strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
"Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
assert.Nil(t, err)
assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)
strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
assert.Nil(t, err)
assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)
strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
assert.Nil(t, err)
assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}
func TestStrFormatComplex(t *testing.T) {
strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
assert.Nil(t, err)
assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}
Show image using file_get_contents
Do i need to modify the headers and just echo it or something?
exactly.
Send a header("content-type: image/your_image_type");
and the data afterwards.
Trying to read cell 1,1 in spreadsheet using Google Script API
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is
Spreadsheet --> Sheet --> Range --> Cell.
Cannot change column used in a foreign key constraint
The type and definition of foreign key field and reference must be equal.
This means your foreign key disallows changing the type of your field.
One solution would be this:
LOCK TABLES
favorite_food WRITE,
person WRITE;
ALTER TABLE favorite_food
DROP FOREIGN KEY fk_fav_food_person_id,
MODIFY person_id SMALLINT UNSIGNED;
Now you can change you person_id
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
recreate foreign key
ALTER TABLE favorite_food
ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
REFERENCES person (person_id);
UNLOCK TABLES;
EDIT:
Added locks above, thanks to comments
You have to disallow writing to the database while you do this,
otherwise you risk data integrity problems.
I've added a write lock above
All writing queries in any other session than your own ( INSERT, UPDATE, DELETE
) will wait till timeout or UNLOCK TABLES
; is executed
http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html
EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."
From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints
Corresponding columns in the foreign key and the referenced key must
have similar internal data types inside InnoDB so that they can be
compared without a type conversion. The size and sign of integer types
must be the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
Submit form using a button outside the <form> tag
Here's a pretty solid solution that incorporates the best ideas so far as well as includes my solution to a problem highlighted with Offerein's. No javascript is used.
If you care about backwards compatibility with IE (and even Edge 13), you can't use the form="your-form"
attribute.
Use a standard submit input with display none and add a label for it outside the form:
<form id="your-form">
<input type="submit" id="your-form-submit" style="display: none;">
</form>
Note the use of display: none;
. This is intentional. Using bootstrap's .hidden
class conflicts with jQuery's .show()
and .hide()
, and has since been deprecated in Bootstrap 4.
Now simply add a label for your submit, (styled for bootstrap):
<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
Submit
</label>
Unlike other solutions, I'm also using tabindex - set to 0 - which means that we are now compatible with keyboard tabbing. Adding the role="button"
attribute gives it the CSS style cursor: pointer
. Et voila. (See this fiddle).
Make Bootstrap 3 Tabs Responsive
Pure CSS only for nav tabs, very simple for small screens:
@media (max-width: 767px) {
.nav-tabs {
min-width: 100%;
display: inline-grid;
}
}
Java: unparseable date exception
From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:
String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);
Next step is parse stringDate to Date:
Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);
Note that, parse method throws ParseException
SQL left join vs multiple tables on FROM line?
Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.
How to stop/kill a query in postgresql?
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
jQuery DIV click, with anchors
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
See event.preventDefault() vs. return false for details on return false vs. preventDefault.
Copying PostgreSQL database to another server
I struggled quite a lot and eventually the method that allowed me to make it work with Rails 4 was:
on your old server
sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql
I had to use the postgres linux user to create the dump. also i had to use -c to force the creation of the database on the new server. --inserts tells it to use the INSERT() syntax which otherwise would not work for me :(
then, on the new server, simpy:
sudo su - postgres
psql new_database_name < dump.sql
to transfer the dump.sql file between server I simply used the "cat" to print the content and than "nano" to recreate it copypasting the content.
Also, the ROLE i was using on the two database was different so i had to find-replace all the owner name in the dump.
Constructors in Go
Golang is not OOP language in its official documents.
All fields of Golang struct has a determined value(not like c/c++), so constructor function is not so necessary as cpp.
If you need assign some fields some special values, use factory functions.
Golang's community suggest New.. pattern names.
mysql -> insert into tbl (select from another table) and some default values
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
CodeIgniter: Unable to connect to your database server using the provided settings Error Message
Extending @Valeh Hajiyev great and clear answer for mysqli
driver tests:
Debug your database connection using this script at the end of ./config/database.php:
/* Your db config here */
$db['default'] = array(
// ...
'dbdriver' => 'mysqli',
// ...
);
/* Connection test: */
echo '<pre>';
print_r($db['default']);
echo '</pre>';
echo 'Connecting to database: ' .$db['default']['database'];
$mysqli_connection = new MySQLi($db['default']['hostname'],
$db['default']['username'],
$db['default']['password'],
$db['default']['database']);
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
echo "Connected.";
}
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);
Can you force Vue.js to reload/re-render?
Worked for me
data () {
return {
userInfo: null,
offers: null
}
},
watch: {
'$route'() {
this.userInfo = null
this.offers = null
this.loadUserInfo()
this.getUserOffers()
}
}
Cannot issue data manipulation statements with executeQuery()
For Delete query - Use @Modifying
and @Transactional
before the @Query
like:-
@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {
@Modifying
@Transactional
@Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
void deleteCopyByTradeId(Integer id);
}
It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
error.
Edit:
Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.
@Transactional
By default, CRUD methods on repository instances are transactional. For read operations,
the transaction configuration readOnly flag is set to true.
All others are configured with a plain @Transactional so that default transaction
configuration applies.
@Modifying
Indicates a query method should be considered as modifying query as that changes the way
it needs to be executed. This annotation is only considered if used on query methods defined
through a Query annotation). It's not applied on custom implementation methods or queries
derived from the method name as they already have control over the underlying data access
APIs or specify if they are modifying by their name.
Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL
statements.
jQuery callback on image load (even when the image is cached)
My simple solution, it doesn't need any external plugin and for common cases should be enough:
/**
* Trigger a callback when the selected images are loaded:
* @param {String} selector
* @param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
use it like this:
onImgLoad('img', function(){
// do stuff
});
for example, to fade in your images on load you can do:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
Or as alternative, if you prefer a jquery plugin-like approach:
/**
* Trigger a callback when 'this' image is loaded:
* @param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
and use it in this way:
$('img').imgLoad(function(){
// do stuff
});
for example:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});
angular2 manually firing click event on particular element
Angular4
Instead of
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
use
this.fileInput.nativeElement.dispatchEvent(event);
because invokeElementMethod
won't be part of the renderer anymore.
Angular2
Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent
to fire the event:
import { Component, Renderer, ElementRef, ViewChild } from '@angular/core';
@Component({
...
template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
@ViewChild('fileInput') fileInput:ElementRef;
constructor(private renderer:Renderer) {}
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
}
Update
Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well
this.fileInput.nativeElement.click()
See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
Read XML file into XmlDocument
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
What primitive data type is time_t?
You can use the function difftime
. It returns the difference between two given time_t
values, the output value is double
(see difftime documentation).
time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0);
printf("%g",actual_time_sec);
How to use Chrome's network debugger with redirects
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
- Open the js console
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
Why is my power operator (^) not working?
You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.
How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
Call method when home button pressed
The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app).
The Home button is considered the user's "safe zone" and will always launch the user's configured home app.
The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
When pressing the home button, the current home app's activity's onNewIntent
will be called.
Get root view from current activity
if you are in a activity, assume there is only one root view,you can get it like this.
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
you can then cast it to your real class
or you could using
getWindow().getDecorView();
notice this will include the actionbar view, your view is below the actionbar view
When restoring a backup, how do I disconnect all active connections?
I ran across this problem while automating a restore proccess in SQL Server 2008.
My (successfull) approach was a mix of two of the answers provided.
First, I run across all the connections of said database, and kill them.
DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = top 1 spid from master.dbo.sysprocesses
where dbid = db_id('dbName')
End
Then, I set the database to a single_user mode
ALTER DATABASE dbName SET SINGLE_USER
Then, I run the restore...
RESTORE DATABASE and whatnot
Kill the connections again
(same query as above)
And set the database back to multi_user.
ALTER DATABASE dbName SET MULTI_USER
This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.
How to parse JSON in Kotlin?
A bit late, but whatever.
If you prefer parsing JSON to JavaScript-like constructs making use of Kotlin syntax, I recommend JSONKraken, of which I am the author.
Suggestions and opinions on the matter are much apreciated!
Clear MySQL query cache without restarting server
In my system (Ubuntu 12.04) I found RESET QUERY CACHE
and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
and then reset the query cache in mysql client:
RESET QUERY CACHE;
Open JQuery Datepicker by clicking on an image w/ no input field
The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:
<img src='someimage.gif' id="datepickerImage" />
<div id="datepicker"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
})
.hide()
.click(function() {
$(this).hide();
});
$("#datepickerImage").click(function() {
$("#datepicker").show();
});
});
</script>
window.onload vs document.onload
The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed.
Ideally, subscribing to DOM-tree events, allows offscreen-manipulations through Javascript, incurring almost no CPU load. Contrarily, window.onload
can take a while to fire, when multiple external resources have yet to be requested, parsed and loaded.
?Test scenario:
To observe the difference and how your browser of choice implements the aforementioned event handlers, simply insert the following code within your document's - <body>
- tag.
<script language="javascript">
window.tdiff = []; fred = function(a,b){return a-b;};
window.document.onload = function(e){
console.log("document.onload", e, Date.now() ,window.tdiff,
(window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) );
}
window.onload = function(e){
console.log("window.onload", e, Date.now() ,window.tdiff,
(window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) );
}
</script>
?Result:
Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).
- No
document.onload
event.
onload
fires twice when declared inside the <body>
, once when declared inside the <head>
(where the event then acts as document.onload
).
- counting and acting dependent on the state of the counter allows to emulate both event behaviors.
- Alternatively declare the
window.onload
event handler within the confines of the HTML-<head>
element.
?Example Project:
The code above is taken from this project's codebase (index.html
and keyboarder.js
).
For a list of event handlers of the window object, please refer to the MDN documentation.
Declaring variable workbook / Worksheet vba
If the worksheet you want to retrieve exists at compile-time in ThisWorkbook
(i.e. the workbook that contains the VBA code you're looking at), then the simplest and most consistently reliable way to refer to that Worksheet
object is to use its code name:
Debug.Print Sheet1.Range("A1").Value
You can set the code name to anything you need (as long as it's a valid VBA identifier), independently of its "tab name" (which the user can modify at any time), by changing the (Name)
property in the Properties toolwindow (F4):
The Name
property refers to the "tab name" that the user can change on a whim; the (Name)
property refers to the code name of the worksheet, and the user can't change it without accessing the Visual Basic Editor.
VBA uses this code name to automatically declare a global-scope Worksheet
object variable that your code gets to use anywhere to refer to that sheet, for free.
In other words, if the sheet exists in ThisWorkbook
at compile-time, there's never a need to declare a variable for it - the variable is already there!
If the worksheet is created at run-time (inside ThisWorkbook
or not), then you need to declare & assign a Worksheet
variable for it.
Use the Worksheets
property of a Workbook
object to retrieve it:
Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)
Dim ws As Worksheet
Set ws = wb.Worksheets(nameOrIndex)
Important notes...
Both the name and index of a worksheet can easily be modified by the user (accidentally or not), unless workbook structure is protected. If workbook isn't protected, you simply cannot assume that the name or index alone will give you the specific worksheet you're after - it's always a good idea to validate the format of the sheet (e.g. verify that cell A1 contains some specific text, or that there's a table with a specific name, that contains some specific column headings).
Using the Sheets
collection contains Worksheet
objects, but can also contain Chart
instances, and a half-dozen more legacy sheet types that are not worksheets. Assigning a Worksheet
reference from whatever Sheets(nameOrIndex)
returns, risks throwing a type mismatch run-time error for that reason.
Not qualifying the Worksheets
collection is an implicit ActiveWorkbook reference - meaning the Worksheets
collection is pulling from whatever workbook is active at the moment the instruction is executing. Such implicit references make the code frail and bug-prone, especially if the user can navigate and interact with the Excel UI while code is running.
Unless you mean to activate a specific sheet, you never need to call ws.Activate
in order to do 99% of what you want to do with a worksheet. Just use your ws
variable instead.
disable all form elements inside div
I'm using the function below at various points. Works in a div or button elements in a table as long as the right selector is used. Just ":button" would not re-enable for me.
function ToggleMenuButtons(bActivate) {
if (bActivate == true) {
$("#SelectorId :input[type='button']").prop("disabled", true);
} else {
$("#SelectorId :input[type='button']").removeProp("disabled");
}
}
How to safely open/close files in python 2.4
In the above solution, repeated here:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:
f = None
try:
f = open('file.txt', 'r')
# do stuff with f
finally:
if f is not None:
f.close()
RegEx: How can I match all numbers greater than 49?
I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:
/([5-9][0-9])|([1-9]\d{3}\d*)/
How to convert numbers to words without using num2word library?
number=input("number")
numls20={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"ten","11":"elevn","12":"twelve","13":"thirteen","14":"fourteen","15":"fifteen","16":"sixteen","17":"seventeen","18":"eighteen","19":"ninteen"}
numls100={"1":"ten","2":"twenty","3":"thrity","4":"fourty","5":"fifty","6":"sixty","7":"seventy","8":"eighty","9":"ninty"}
numls1000={"1":"hundred","2":"twohundred","3":"threehundred","4":"fourhundred","5":"fivehundred","6":"sixhundred","7":"sevenhundred","8":"eighthundred","9":"ninehundred"}
def num2str(number):
if (int(number)<20):
print(numls20[number])
elif(int(number)<100):
print(numls100[number[0]]+" "+numls20[number[1]])
elif(int(number)<1000):
if ((int(number))%100 == 0):
print(numls1000[number[0]])
else:
print(numls1000[number[0]]+" and "+numls100[number[1]]+" "+numls20[number[2]])
elif(int(number)<10000):
if ((int(number))%1000 == 0):
print(numls20[number[0]]+" thousand")
elif(int(number)%100 == 0):
print(numls20[number[0]]+" thousand "+numls1000[number[1]])
elif(int(number)%10 == 0):
print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]])
else:
print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]]+" "+numls20[number[3]])
num2str(number)
How do I read input character-by-character in Java?
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
Null vs. False vs. 0 in PHP
Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.
So.. the quick answer is: context.
Why does Vim save files with a ~ extension?
To turn off those files, just add these lines to .vimrc (vim configuration file on unix based OS):
set nobackup #no backup files
set nowritebackup #only in case you don't want a backup file while editing
set noswapfile #no swap files
How to have EditText with border in Android Lollipop
A quick and dirty solution I have used is to place the EditText inside of a FrameLayout. The margins of the EditText control the thickness of the border and the border color is determined by the background color of the FrameLayout.
Example:
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000">
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:background="@android:color/white"
android:ems="10"
android:inputType="text"
android:textSize="24sp" />
</FrameLayout>
But I would recommend, and the vast majority of the time I do, drawables for borders. Elite's answer is what I would go for in that case.
Undefined reference to sqrt (or other mathematical functions)
You may find that you have to link with the math libraries on whatever system you're using, something like:
gcc -o myprog myprog.c -L/path/to/libs -lm
^^^ - this bit here.
Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.
Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).
The following code compiles and links fine:
#include <math.h>
int main (void) {
int max = sqrt (9);
return 0;
}
Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.
So, for example, given the commands:
gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o
and plugh.o
requires something from the xyzzy
library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.
And when the unresolved symbols from plugh.o
do appear, it's too late.
Good Free Alternative To MS Access
When people ask about a replacement for Access, a lot of them only think about the database, but what they are really asking about are all of the other features in Access. They usually don't care what database Access is using.
Some of the functionality provided by Access are: Forms, Query Building, Reports, Macros, Database Management, and some kind of language when you need to go beyond what the wizards provide.
SQLite, MySQL, and FireBird are free database back ends. They do not have those additional Access functions built into them. Any free alternatives to Access require you combining something like SQLite and a development language.
Probably the best free option would be SQLite and Visual Basic 2008 or C# 2008 Express Edition. This would have a heavy runtime dependency, so installing on a bare client could take quite the installer.
There really isn't a non-Access option for free with minimum runtime requirements. I wish there was.
I'll be interested in hearing if anybody knows any good alternatives.
How do I disable orientation change on Android?
You can simply use like below in the application class if you want only PORTRAIT mode for all activities in your app.
class YourApplicationName : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
})
}
}
ToggleClass animate jQuery?
You should look at the toggle
function found on jQuery. This will allow you to specify an easing method to define how the toggle works.
slideToggle
will only slide up and down, not left/right if that's what you are looking for.
If you need the class to be toggled as well you can deifine that in the toggle
function with a:
$(this).closest('article').toggle('slow', function() {
$(this).toggleClass('expanded');
});
Best way to get identity of inserted row?
From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
- IDENT_CURRENT is a function which takes a table as a argument.
- @@IDENTITY may return confusing result when you have an trigger on the table
- SCOPE_IDENTITY is your hero most of the time.
Getting the text from a drop-down box
This works i tried it my self i thought i post it here in case someone need it...
document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
How to set standard encoding in Visual Studio
Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents
, named Save documents as Unicode when data cannot be saved in codepage
. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.
Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.
How to implement a Navbar Dropdown Hover in Bootstrap v4?
_x000D_
_x000D_
$('body').on('mouseenter mouseleave','.dropdown',function(e){_x000D_
var _d=$(e.target).closest('.dropdown');_x000D_
if (e.type === 'mouseenter')_d.addClass('show');_x000D_
setTimeout(function(){_x000D_
_d.toggleClass('show', _d.is(':hover'));_x000D_
$('[data-toggle="dropdown"]', _d).attr('aria-expanded',_d.is(':hover'));_x000D_
},300);_x000D_
});_x000D_
_x000D_
/* this is not needed, just prevents page reload when a dd link is clicked */_x000D_
$('.dropdown a').on('click tap', e => e.preventDefault())
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href>Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href>Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<a class="dropdown-item" href>Action</a>_x000D_
<a class="dropdown-item" href>Another action</a>_x000D_
<a class="dropdown-item" href>Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_
How to upload a file and JSON data in Postman?
The way to send mulitpart data which containts a file with the json data is the following, we need to set the content-type of the respective json key fields to 'application/json' in the postman body tab like the following:
AJAX reload page with POST
By using jquery ajax you can reload your page
$.ajax({
type: "POST",
url: "packtypeAdd.php",
data: infoPO,
success: function() {
location.reload();
}
});