Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
DataRow myRow = dtSpecificOrders.NewRow(); // <-- create a brand-new row
myRow[dcID] = int.Parse(dr["ID"]);
myRow[dcName] = dr["Name"].ToString();
dtSpecificOrders.Rows.Add(myRow); // <-- this will add the new row
}
The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.
If you wish to avoid both building your projects with Bazel and generating a large binary, I have assembled a repository instructing the usage of the TensorFlow C++ library with CMake. You can find it here. The general ideas are as follows:
tensorflow/BUILD
(the provided ones do not include all of the C++ functionality).Just add \
at the end of line. For example
one\
two
Will become
one
two
It's also better than two spaces because it's visible.
A quick grep of the libstd++
code base revealed the following two usages of __gx_personality_v0
:
In libsupc++/unwind-cxx.h
// GNU C++ personality routine, Version 0.
extern "C" _Unwind_Reason_Code __gxx_personality_v0
(int, _Unwind_Action, _Unwind_Exception_Class,
struct _Unwind_Exception *, struct _Unwind_Context *);
In libsupc++/eh_personality.cc
#define PERSONALITY_FUNCTION __gxx_personality_v0
extern "C" _Unwind_Reason_Code
PERSONALITY_FUNCTION (int version,
_Unwind_Action actions,
_Unwind_Exception_Class exception_class,
struct _Unwind_Exception *ue_header,
struct _Unwind_Context *context)
{
// ... code to handle exceptions and stuff ...
}
(Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).
So, as long as your code isn't actually using exception handling, defining the symbol as void*
won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0
is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.
Press Ctrl+,
Then you will see a docked window under name of "Go to all"
This a picture of the "Go to all" in my IDE
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
Found one solution for WIFI (works for Android 4.3, 4.4):
If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:
In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.
At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.
Take advantage of the standard char_traits
. Recall that a std::string
is in fact a typedef for std::basic_string<char>
, or more explicitly, std::basic_string<char, std::char_traits<char> >
. The char_traits
type describes how characters compare, how they copy, how they cast etc. All you need to do is typedef a new string over basic_string
, and provide it with your own custom char_traits
that compare case insensitively.
struct ci_char_traits : public char_traits<char> {
static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }
static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }
static bool lt(char c1, char c2) { return toupper(c1) < toupper(c2); }
static int compare(const char* s1, const char* s2, size_t n) {
while( n-- != 0 ) {
if( toupper(*s1) < toupper(*s2) ) return -1;
if( toupper(*s1) > toupper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, int n, char a) {
while( n-- > 0 && toupper(*s) != toupper(a) ) {
++s;
}
return s;
}
};
typedef std::basic_string<char, ci_char_traits> ci_string;
The details are on Guru of The Week number 29.
I don't know why but animating only the visibility
property is not working on any browser.
What you can do is animate the opacity
property in such a way that the browser doesn't have enough frames to fade in or out the text.
Example:
span {_x000D_
opacity: 0;_x000D_
animation: blinking 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinking {_x000D_
from,_x000D_
49.9% {_x000D_
opacity: 0;_x000D_
}_x000D_
50%,_x000D_
to {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<span>I'm blinking text</span>
_x000D_
ps -eo size,pid,user,command --sort -size | \
awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' |\
cut -d "" -f2 | cut -d "-" -f1
0.00 Mb COMMAND
1288.57 Mb /usr/lib/firefox
821.68 Mb /usr/lib/chromium/chromium
762.82 Mb /usr/lib/chromium/chromium
588.36 Mb /usr/sbin/mysqld
547.55 Mb /usr/lib/chromium/chromium
523.92 Mb /usr/lib/tracker/tracker
476.59 Mb /usr/lib/chromium/chromium
446.41 Mb /usr/bin/gnome
421.62 Mb /usr/sbin/libvirtd
405.11 Mb /usr/lib/chromium/chromium
302.60 Mb /usr/lib/chromium/chromium
291.46 Mb /usr/lib/chromium/chromium
284.56 Mb /usr/lib/chromium/chromium
238.93 Mb /usr/lib/tracker/tracker
223.21 Mb /usr/lib/chromium/chromium
197.99 Mb /usr/lib/chromium/chromium
194.07 Mb conky
191.92 Mb /usr/lib/chromium/chromium
190.72 Mb /usr/bin/mongod
169.06 Mb /usr/lib/chromium/chromium
155.11 Mb /usr/bin/gnome
136.02 Mb /usr/lib/chromium/chromium
125.98 Mb /usr/lib/chromium/chromium
103.98 Mb /usr/lib/chromium/chromium
93.22 Mb /usr/lib/tracker/tracker
89.21 Mb /usr/lib/gnome
80.61 Mb /usr/bin/gnome
77.73 Mb /usr/lib/evolution/evolution
76.09 Mb /usr/lib/evolution/evolution
72.21 Mb /usr/lib/gnome
69.40 Mb /usr/lib/evolution/evolution
68.84 Mb nautilus
68.08 Mb zeitgeist
60.97 Mb /usr/lib/tracker/tracker
59.65 Mb /usr/lib/evolution/evolution
57.68 Mb apt
55.23 Mb /usr/lib/gnome
53.61 Mb /usr/lib/evolution/evolution
53.07 Mb /usr/lib/gnome
52.83 Mb /usr/lib/gnome
51.02 Mb /usr/lib/udisks2/udisksd
50.77 Mb /usr/lib/evolution/evolution
50.53 Mb /usr/lib/gnome
50.45 Mb /usr/lib/gvfs/gvfs
50.36 Mb /usr/lib/packagekit/packagekitd
50.14 Mb /usr/lib/gvfs/gvfs
48.95 Mb /usr/bin/Xwayland :1024
46.21 Mb /usr/bin/gnome
42.43 Mb /usr/bin/zeitgeist
42.29 Mb /usr/lib/gnome
41.97 Mb /usr/lib/gnome
41.64 Mb /usr/lib/gvfs/gvfsd
41.63 Mb /usr/lib/gvfs/gvfsd
41.55 Mb /usr/lib/gvfs/gvfsd
41.48 Mb /usr/lib/gvfs/gvfsd
39.87 Mb /usr/bin/python /usr/bin/chrome
37.45 Mb /usr/lib/xorg/Xorg vt2
36.62 Mb /usr/sbin/NetworkManager
35.63 Mb /usr/lib/caribou/caribou
34.79 Mb /usr/lib/tracker/tracker
33.88 Mb /usr/sbin/ModemManager
33.77 Mb /usr/lib/gnome
33.61 Mb /usr/lib/upower/upowerd
33.53 Mb /usr/sbin/gdm3
33.37 Mb /usr/lib/gvfs/gvfsd
33.36 Mb /usr/lib/gvfs/gvfs
33.23 Mb /usr/lib/gvfs/gvfs
33.15 Mb /usr/lib/at
33.15 Mb /usr/lib/at
30.03 Mb /usr/lib/colord/colord
29.62 Mb /usr/lib/apt/methods/https
28.06 Mb /usr/lib/zeitgeist/zeitgeist
27.29 Mb /usr/lib/policykit
25.55 Mb /usr/lib/gvfs/gvfs
25.55 Mb /usr/lib/gvfs/gvfs
25.23 Mb /usr/lib/accountsservice/accounts
25.18 Mb /usr/lib/gvfs/gvfsd
25.15 Mb /usr/lib/gvfs/gvfs
25.15 Mb /usr/lib/gvfs/gvfs
25.12 Mb /usr/lib/gvfs/gvfs
25.10 Mb /usr/lib/gnome
25.10 Mb /usr/lib/gnome
25.07 Mb /usr/lib/gvfs/gvfsd
24.99 Mb /usr/lib/gvfs/gvfs
23.26 Mb /usr/lib/chromium/chromium
22.09 Mb /usr/bin/pulseaudio
19.01 Mb /usr/bin/pulseaudio
18.62 Mb (sd
18.46 Mb (sd
18.30 Mb /sbin/init
18.17 Mb /usr/sbin/rsyslogd
17.50 Mb gdm
17.42 Mb gdm
17.09 Mb /usr/lib/dconf/dconf
17.09 Mb /usr/lib/at
17.06 Mb /usr/lib/gvfs/gvfsd
16.98 Mb /usr/lib/at
16.91 Mb /usr/lib/gdm3/gdm
16.86 Mb /usr/lib/gvfs/gvfsd
16.86 Mb /usr/lib/gdm3/gdm
16.85 Mb /usr/lib/dconf/dconf
16.85 Mb /usr/lib/dconf/dconf
16.73 Mb /usr/lib/rtkit/rtkit
16.69 Mb /lib/systemd/systemd
13.13 Mb /usr/lib/chromium/chromium
13.13 Mb /usr/lib/chromium/chromium
10.92 Mb anydesk
8.54 Mb /sbin/lvmetad
7.43 Mb /usr/sbin/apache2
6.82 Mb /usr/sbin/apache2
6.77 Mb /usr/sbin/apache2
6.73 Mb /usr/sbin/apache2
6.66 Mb /usr/sbin/apache2
6.64 Mb /usr/sbin/apache2
6.63 Mb /usr/sbin/apache2
6.62 Mb /usr/sbin/apache2
6.51 Mb /usr/sbin/apache2
6.25 Mb /usr/sbin/apache2
6.22 Mb /usr/sbin/apache2
3.92 Mb bash
3.14 Mb bash
2.97 Mb bash
2.95 Mb bash
2.93 Mb bash
2.91 Mb bash
2.86 Mb bash
2.86 Mb bash
2.86 Mb bash
2.84 Mb bash
2.84 Mb bash
2.45 Mb /lib/systemd/systemd
2.30 Mb (sd
2.28 Mb /usr/bin/dbus
1.84 Mb /usr/bin/dbus
1.46 Mb ps
1.21 Mb openvpn hackthebox.ovpn
1.16 Mb /sbin/dhclient
1.16 Mb /sbin/dhclient
1.09 Mb /lib/systemd/systemd
0.98 Mb /sbin/mount.ntfs /dev/sda3 /media/n0bit4/Data
0.97 Mb /lib/systemd/systemd
0.96 Mb /lib/systemd/systemd
0.89 Mb /usr/sbin/smartd
0.77 Mb /usr/bin/dbus
0.76 Mb su
0.76 Mb su
0.76 Mb su
0.76 Mb su
0.76 Mb su
0.76 Mb su
0.75 Mb sudo su
0.75 Mb sudo su
0.75 Mb sudo su
0.75 Mb sudo su
0.75 Mb sudo su
0.75 Mb sudo su
0.74 Mb /usr/bin/dbus
0.71 Mb /usr/lib/apt/methods/http
0.68 Mb /bin/bash /usr/bin/mysqld_safe
0.68 Mb /sbin/wpa_supplicant
0.66 Mb /usr/bin/dbus
0.61 Mb /lib/systemd/systemd
0.54 Mb /usr/bin/dbus
0.46 Mb /usr/sbin/cron
0.45 Mb /usr/sbin/irqbalance
0.43 Mb logger
0.41 Mb awk { hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }
0.40 Mb /usr/bin/ssh
0.34 Mb /usr/lib/chromium/chrome
0.32 Mb cut
0.32 Mb cut
0.00 Mb [kthreadd]
0.00 Mb [ksoftirqd/0]
0.00 Mb [kworker/0:0H]
0.00 Mb [rcu_sched]
0.00 Mb [rcu_bh]
0.00 Mb [migration/0]
0.00 Mb [lru
0.00 Mb [watchdog/0]
0.00 Mb [cpuhp/0]
0.00 Mb [cpuhp/1]
0.00 Mb [watchdog/1]
0.00 Mb [migration/1]
0.00 Mb [ksoftirqd/1]
0.00 Mb [kworker/1:0H]
0.00 Mb [cpuhp/2]
0.00 Mb [watchdog/2]
0.00 Mb [migration/2]
0.00 Mb [ksoftirqd/2]
0.00 Mb [kworker/2:0H]
0.00 Mb [cpuhp/3]
0.00 Mb [watchdog/3]
0.00 Mb [migration/3]
0.00 Mb [ksoftirqd/3]
0.00 Mb [kworker/3:0H]
0.00 Mb [kdevtmpfs]
0.00 Mb [netns]
0.00 Mb [khungtaskd]
0.00 Mb [oom_reaper]
0.00 Mb [writeback]
0.00 Mb [kcompactd0]
0.00 Mb [ksmd]
0.00 Mb [khugepaged]
0.00 Mb [crypto]
0.00 Mb [kintegrityd]
0.00 Mb [bioset]
0.00 Mb [kblockd]
0.00 Mb [devfreq_wq]
0.00 Mb [watchdogd]
0.00 Mb [kswapd0]
0.00 Mb [vmstat]
0.00 Mb [kthrotld]
0.00 Mb [ipv6_addrconf]
0.00 Mb [acpi_thermal_pm]
0.00 Mb [ata_sff]
0.00 Mb [scsi_eh_0]
0.00 Mb [scsi_tmf_0]
0.00 Mb [scsi_eh_1]
0.00 Mb [scsi_tmf_1]
0.00 Mb [scsi_eh_2]
0.00 Mb [scsi_tmf_2]
0.00 Mb [scsi_eh_3]
0.00 Mb [scsi_tmf_3]
0.00 Mb [scsi_eh_4]
0.00 Mb [scsi_tmf_4]
0.00 Mb [scsi_eh_5]
0.00 Mb [scsi_tmf_5]
0.00 Mb [bioset]
0.00 Mb [kworker/1:1H]
0.00 Mb [kworker/3:1H]
0.00 Mb [kworker/0:1H]
0.00 Mb [kdmflush]
0.00 Mb [bioset]
0.00 Mb [kdmflush]
0.00 Mb [bioset]
0.00 Mb [jbd2/sda5
0.00 Mb [ext4
0.00 Mb [kworker/2:1H]
0.00 Mb [kauditd]
0.00 Mb [bioset]
0.00 Mb [drbd
0.00 Mb [irq/27
0.00 Mb [i915/signal:0]
0.00 Mb [i915/signal:1]
0.00 Mb [i915/signal:2]
0.00 Mb [ttm_swap]
0.00 Mb [cfg80211]
0.00 Mb [kworker/u17:0]
0.00 Mb [hci0]
0.00 Mb [hci0]
0.00 Mb [kworker/u17:1]
0.00 Mb [iprt
0.00 Mb [iprt
0.00 Mb [kworker/1:0]
0.00 Mb [kworker/3:0]
0.00 Mb [kworker/0:0]
0.00 Mb [kworker/2:0]
0.00 Mb [kworker/u16:0]
0.00 Mb [kworker/u16:2]
0.00 Mb [kworker/3:2]
0.00 Mb [kworker/2:1]
0.00 Mb [kworker/1:2]
0.00 Mb [kworker/0:2]
0.00 Mb [kworker/2:2]
0.00 Mb [kworker/0:1]
0.00 Mb [scsi_eh_6]
0.00 Mb [scsi_tmf_6]
0.00 Mb [usb
0.00 Mb [bioset]
0.00 Mb [kworker/3:1]
0.00 Mb [kworker/u16:1]
I use this, it works with php...
<span><?php
if (file_exists("image/".$data['img_name'])) {
?>
<img src="image/<?php echo $data['img_name']; ?>" width="100" height="100">
<?php
}else{
echo "Image Not Found";
}>?
</span>
Essentially what the code is doing, is checking for the File. The $data
variable will be used with our array then actually make the desired change. If it isn't found, it will throw an Exception.
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.
Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command
you can integrate to LDAP or AD as well. It works well.
Just assuming this is for a regular expression, use re.escape
.
Integrated Security = False : User ID and Password are specified in the connection. Integrated Security = true : the current Windows account credentials are used for authentication.
Integrated Security = SSPI : this is equivalant to true.
We can avoid the username and password attributes from the connection string and use the Integrated Security
as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.
awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:
variable=$(ps -ef | awk '/port 10 \-/ {print $12}')
variable=`ps -ef | awk '/port 10 \-/ {print $12}'`
The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
This bash script will accept the root password as option and optimize it one by one, with status output:
#!/bin/bash
if [ -z "$1" ] ; then
echo
echo "ERROR: root password Parameter missing."
exit
fi
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
TBLLIST=""
COMMA=""
SQL="SELECT CONCAT(table_schema,'.',table_name) FROM information_schema.tables WHERE"
SQL="${SQL} table_schema NOT IN ('information_schema','mysql','performance_schema')"
for DBTB in `mysql ${MYSQL_CONN} -ANe"${SQL}"`
do
echo OPTIMIZE TABLE "${DBTB};"
SQL="OPTIMIZE TABLE ${DBTB};"
mysql ${MYSQL_CONN} -ANe"${SQL}"
done
Use the Set#toArray(IntFunction<T[]>)
method taking an IntFunction
as generator.
String[] GPXFILES1 = myset.toArray(String[]::new);
If you're not on Java 11 yet, then use the Set#toArray(T[])
method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
While still not on Java 11, and you can't guarantee that myset
is unmodifiable at the moment of conversion to array, then better specify an empty typed array.
String[] GPXFILES1 = myset.toArray(new String[0]);
With jQuery 1.6 and above you should use:
$("a").prop("href", "http://www.jakcms.com")
The difference between prop
and attr
is that attr
grabs the HTML attribute whereas prop
grabs the DOM property.
You can find more details in this post: .prop() vs .attr()
I am one of the engineers on the Fresco project. So obviously I'm biased.
But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.
I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco
.
Fresco offers features that Picasso, UIL, and Glide do not yet have:
There are many others (see our documentation), but these are the most important.
This error can mean that ./arm-mingw32ce-g++
doesn't exist (but it does), or that it exists and is a dynamically linked executable recognized by the kernel but whose dynamic loader is not available. You can see what dynamic loader is required by running ldd /arm-mingw32ce-g++
; anything marked not found
is the dynamic loader or a library that you need to install.
If you're trying to run a 32-bit binary on an amd64 installation:
ia32-libs
.ia32-libs-multiarch
.ia32-libs-multiarch
, or select a reasonable set of :i386
packages in addition to the :amd64
packages.docker run -v /host/directory:/container/directory -t IMAGE-NAME /bin/bash
docker run -v /root/shareData:/home/shareData -t kylemanna/openvpn /bin/bash
In my system I've corrected the answer from nhjk, it works flawless when you add the -t
flag.
<input type="button" value="Clear" onclick="javascript: functionName();" >
you just need to set the onclick event, call your desired function on this onclick event.
function functionName()
{
$("#output").val("");
}
Above function will set the value of text area to empty string.
In SQL Server 2017 STRING_AGG is added:
SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1
Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016
You can use font face like this:
@font-face {
font-family:"Name-Of-Font";
src: url("yourfont.ttf") format("truetype");
}
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:
h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
The k[1, k.length - 1]
bit grabs all of k
except the first character. If you want a copy, then:
new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
Or
new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
You could also use sub
if you don't like the k[]
notation for extracting a substring:
h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
And, if only some of the keys have the underscore prefix:
h.keys.each do |k|
if(k[0,1] == '_')
h[k[1, k.length - 1]] = h[k]
h.delete(k)
end
end
Similar modifications can be done to all the other variants above but these two:
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
should be okay with keys that don't have underscore prefixes without extra modifications.
--
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
---
@NgModule({
declarations: [ -- ],
imports: [BrowserAnimationsModule],
providers: [],
bootstrap: []
})
I'm just going to do this
def function():
while True:
#code here
break
Use "break" to stop the function.
This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.
A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.
The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.
The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
As of Chrome 46, a simple onclick=window.close()
does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.
... since dates naturally have time-zone information, which can span regions with different day light savings adjustments
Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24
, so the typical calculation will fail.
You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.
Now, the solution can be written as,
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
const a = new Date("2017-01-01"),
b = new Date("2017-07-25"),
difference = dateDiffInDays(a, b);
This works because UTC time never observes DST. See Does UTC observe daylight saving time?
p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.
If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.
enum TestStatus {
Available, // 0
Ready, // 1
Started, // 2
}
class Test {
status: TestStatus
}
var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
// and the sequence ID is automatic
The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available
. And Typescript will enforce the type when you pass those around.
You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.
class TestStatus {
id: number
name: string
constructor(id, name){
this.id = id;
this.name = name;
}
}
type Statuses = Array<TestStatus>;
var statuses: Statuses = [
new TestStatus(0, "Available"),
new TestStatus(1, "Ready"),
new TestStatus(2, "Started")
]
In addition to what the asker's own answer already stated, it may be worth noting the following. The reason this happens is because it is possible for a class to have a method with the same signature as an interface method without implementing that method. The following code illustrates that:
public interface IFoo
{
void DoFoo();
}
public class Foo : IFoo
{
public void DoFoo() { Console.WriteLine("This is _not_ the interface method."); }
void IFoo.DoFoo() { Console.WriteLine("This _is_ the interface method."); }
}
Foo foo = new Foo();
foo.DoFoo(); // This calls the non-interface method
IFoo foo2 = foo;
foo2.DoFoo(); // This calls the interface method
In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?
enqueue: to place something into a queue; to add an element to the tail of a queue;
dequeue to take something out of a queue; to remove the first available element from the head of a queue
You need to use at least Gradle 3.4 or newer to be able to use implementation
. It is not recommended to keep using the deprecated compile
since this can result in slower build times. For more details see the official android developer guide:
When your module configures an implementation dependency, it's letting Gradle know that the module does not want to leak the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime. Using this dependency configuration instead of api or compile can result in significant build time improvements because it reduces the amount of projects that the build system needs to recompile. For example, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly depend on it. Most app and test modules should use this configuration.
https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#new_configurations
Update: compile
will be removed by end of 2018, so make sure that you use only implementation
now:
Warning:Configuration 'compile' is obsolete and has been replaced with 'implementation'. It will be removed at the end of 2018
If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):
for (int x = 1; x <= 50; x++)
{
list.Items.Add(x);
}
You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:
listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });
It does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
Start mysql with the --log option:
mysqld --log=log_file_name
or place the following in your my.cnf
file:
log = log_file_name
Either one will log all queries to log_file_name.
You can also log only slow queries using the --log-slow-queries
option instead of --log
. By default, queries that take 10 seconds or longer are considered slow, you can change this by setting long_query_time
to the number of seconds a query must take to execute before being logged.
If you are getting errors even after downloading the newest SDK and Android Studio, here is what I did:
I hope it helps someone so that he won't suffer like I did for these couple of days.
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
Since this post is tagged Windows, I thought I would work out a solution for Windows. I wanted to automate the process, and I made a bat file. I resisted making a console.exe in C#.
I wanted to add any files or folders which are not added in my repository when I begin the commit process.
The problem with many of the answers is they will list unversioned files which should be ignored as per my ignore list in TortoiseSVN.
Here is my hook setting and batch file which does that
Tortoise Hook Script:
"start_commit_hook".
(where I checkout) working copy path = C:\Projects
command line: C:\windows\system32\cmd.exe /c C:\Tools\SVN\svnadd.bat
(X) Wait for the script to finish
(X) (Optional) Hide script while running
(X) Always execute the script
svnadd.bat
@echo off
rem Iterates each line result from the command which lists files/folders
rem not added to source control while respecting the ignore list.
FOR /F "delims==" %%G IN ('svn status ^| findstr "^?"') DO call :DoSVNAdd "%%G"
goto end
:DoSVNAdd
set addPath=%1
rem Remove line prefix formatting from svn status command output as well as
rem quotes from the G call (as required for long folder names). Then
rem place quotes back around the path for the SVN add call.
set addPath="%addPath:~9,-1%"
svn add %addPath%
:end
Use a simple background image for the textarea suffice.
Or
<div onselectstart="return false">your text</div>
if u want to have multiple selection on select row..
import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';
class ThreatReportTable extends React.Component{
constructor(props){
super(props);
this.state = {
selected: [],
row: []
}
}
render(){
const columns = this.props.label;
const data = this.props.data;
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
pageText: false,
previousText: '<',
nextText: '>',
showPageJump: false,
showPagination: true,
defaultSortMethod: (a, b, desc) => {
return b - a;
},
})
return(
<ReactTable className='threatReportTable'
data= {data}
columns={columns}
getTrProps={(state, rowInfo, column) => {
return {
onClick: (e) => {
var a = this.state.selected.indexOf(rowInfo.index);
if (a == -1) {
// this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
this.setState({selected: [...this.state.selected, rowInfo.index]});
// Pass props to the React component
}
var array = this.state.selected;
if(a != -1){
array.splice(a, 1);
this.setState({selected: array});
}
},
// #393740 - Lighter, selected row
// #302f36 - Darker, not selected row
style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},
}
}}
noDataText = "No available threats"
/>
)
}
}
export default ThreatReportTable;
Spent a few hours facing this issue this morning. I am likely to be the least technical person on these forums. Like the requester, I endured every reminder to set %JAVA_HOME%, biting my tongue each time I saw this non luminary advice. Finally I pondered whether my laptop's JRE was versions ahead of my JDK (as JREs are regularly updated automatically) and I installed the latest JDK. The difference was minor, emanating from a matter of weeks of different versions. I started with this error on jdk v 1.0865. The JRE was 1.0866. After installation, I had jdk v1.0874 and the equivalent JRE. At that point, I directed the Eclipse JRE to focus on my JDK and all was well. My println of java.home even reflected the correct JRE.
So much feedback repeated the wrong responses. I would strongly request that people read the feedback from others to avoid useless redundancy. Take care all, SG
development - each of our devs get their own schema as a sandbox to play in.
If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
I tried the below steps. It works well.
Just click the link Delete all SOLR data which will hit and delete all your SOLR indexed datas then you will get the following details on the screen as output.
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">494</int>
</lst>
</response>
if you are not getting the above output then please make sure the following.
host
(localhost) and port
(8080) on the above link. please alter the host and port if it is different in your end. collection
/ collection1
. I used collection1
in the above link. please change it too if your core name is different.You need to close the connection before you can use the output parameters. Something like this
con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());
To improve the solution proposed by @Maxim using $broadcast, send data don't change
$rootScope.$broadcast('SOME_TAG', 'my variable');
but to listening data
$scope.$on('SOME_TAG', function(event, args) {
console.log("My variable is", args);// args is value of your variable
})
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.
I can't believe nobody said nothing about Immunity Debugger, yet.
Immunity Debugger is a powerful tool to write exploits, analyze malware, and reverse engineer binary files. It was initially based on Ollydbg 1.0 source code, but with names resoution bug fixed. It has a well supported Python API for easy extensibility, so you can write your python scripts to help you out on the analysis.
Also, there's a good one Peter from Corelan team wrote called mona.py, excelent tool btw.
Oracle
stores only the fractions up to second in a DATE
field.
Use TIMESTAMP
instead:
SELECT TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM dual
, possibly casting it to a DATE
then:
SELECT CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM dual
If you don't know which option to enter the params.
Just want to keep the default value like on_delete=None
before migration:
on_delete=models.CASCADE
This is a code snippet in the old version:
if on_delete is None:
warnings.warn(
"on_delete will be a required arg for %s in Django 2.0. Set "
"it to models.CASCADE on models and in existing migrations "
"if you want to maintain the current default behavior. "
"See https://docs.djangoproject.com/en/%s/ref/models/fields/"
"#django.db.models.ForeignKey.on_delete" % (
self.__class__.__name__,
get_docs_version(),
),
RemovedInDjango20Warning, 2)
on_delete = CASCADE
You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.
The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).
import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dest)
=CONCATENATE(LEFT(A1,1), B1)
Assuming A1 holds 1st names; B1 Last names
The 'mangler' in the above code sample was doing the equivalent of this:
bytesThing = stringThing.encode(encoding='UTF-8')
There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8')
, but the above syntax makes it obvious what is going on, and also what to do to recover the string:
newStringThing = bytesThing.decode(encoding='UTF-8')
When we do this, the original string is recovered.
Note, using str(bytesThing)
just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8')
. No error is reported if the encoding is not specified.
Apache commons provides utility to convert the stack trace from throwable to string.
Usage:
ExceptionUtils.getStackTrace(e)
For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html
A merge one inspired by atzz and Mital Vora:
#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts
-file.
Much simpler than messing around with permissions
in the android FS (which always feels like
a hack for me - because i believe there must be a kind of integrated way
) is just to:
Allow ADB root access
and Restart the deamon
with root permissions
.
Settings
-> Developer Options
-> Root-Access for ADB
or Apps & ADB
.command prompt
and type: adb.exe root
Enjoy
browsing all filesadb.exe unroot
in your command prompt
.Either:
,[\s\S]*$
or ,.*$
to match everything after the first comma (see explanation for which one to use); or
[^,]*$
to match everything after the last comma (which is probably what you want).
You can use, for example, /[^,]*/.exec(s)[0]
in JavaScript, where s is the original string. If you wanted to use multiline mode and find all matches that way, you could use s.match(/[^,]*/mg)
to get an array (if you have more than one of your posted example lines in the variable on separate lines).
[\s\S]
is a character class that matches both whitespace and non-whitespace characters (i.e. all of them). This is different from .
in that it matches newlines.[^,]
is a negated character class that matches everything except for commas.*
means that the previous item can repeat 0 or more times.$
is the anchor that requires that the end of the match be at the end of the string (or end of line if using the /m multiline flag).For the first match, the first regex finds the first comma ,
and then matches all characters afterward until the end of line [\s\S]*$
, including commas.
The second regex matches as many non-comma characters as possible before the end of line. Thus, the entire match will be after the last comma.
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
its simple to call a message box, so if you want to code behind or call function, I think it is better or may be not. There is a process, you can just use namespace
using system.widows.forms;
then, where you want to show a message box, just call it as simple, as in C#, like:
messagebox.show("Welcome");
select CASE
when exists (SELECT U.USERID,U.USERNAME,U.PASSWORDHASH
FROM TBLUSERS U WHERE U.USERID =U.USERID
AND U.PASSWORDHASH=U.PASSWORDHASH)
then 'OLD PASSWORD EXISTS'
else 'OLD PASSWORD NOT EXISTS'
end as OUTPUT
from DUAL;
Try this....
get File from a content uri
fun fileFromContentUri(context: Context, contentUri: Uri): File {
// Preparing Temp file name
val fileExtension = getFileExtension(context, contentUri)
val fileName = "temp_file" + if (fileExtension != null) ".$fileExtension" else ""
// Creating Temp file
val tempFile = File(context.cacheDir, fileName)
tempFile.createNewFile()
try {
val oStream = FileOutputStream(tempFile)
val inputStream = context.contentResolver.openInputStream(contentUri)
inputStream?.let {
copy(inputStream, oStream)
}
oStream.flush()
} catch (e: Exception) {
e.printStackTrace()
}
return tempFile
}
private fun getFileExtension(context: Context, uri: Uri): String? {
val fileType: String? = context.contentResolver.getType(uri)
return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
}
@Throws(IOException::class)
private fun copy(source: InputStream, target: OutputStream) {
val buf = ByteArray(8192)
var length: Int
while (source.read(buf).also { length = it } > 0) {
target.write(buf, 0, length)
}
}
node & element are same. Every element is a node , but it's not that every node must be an element.
You can use this css code to get gutterless grid in bootstrap.
.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
margin-left: 0;
margin-right: 0;
}
.no-gutter>[class^="col-"]{
padding-left: 0;
padding-right: 0;
}
a git export to a zip archive while adding a prefix (e.g. directory name):
git archive master --prefix=directoryWithinZip/ --format=zip -o out.zip
In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.
arrList.set(5,newValue);
and if u want to update it then add this line also
youradapater.NotifyDataSetChanged();
It's not hard to get approval for your app the proper way. SSL (HTTPS/TLS) is still encryption and unless you are using it just for authentication, then you should get the proper approval. I just received approval, and my app is in the store now for something that uses SSL to encrypt data traffic (not just authentication).
Here is a blog entry I made so that others can do this the proper way.
Well the ModelState basically holds the current State of the model in terms of validation, it holds
ModelErrorCollection: Represent the errors when the model try to bind the values. ex.
TryUpdateModel();
UpdateModel();
or like a parameter in the ActionResult
public ActionResult Create(Person person)
ValueProviderResult: Hold the details about the attempted bind to the model. ex. AttemptedValue, Culture, RawValue.
Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.
ModelState["a"].Value.AttemptedValue
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.
See: http://jsfiddle.net/SfPju/466/
HTML
<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>
CSS
.foo
{
padding-right: 20px;
}
I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:
I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit
or /usr/bin/time
result from each of several methods of checksumming a file of approx. 11MB:
$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f /tmp/test.data.300k
real 0m0.043s
user 0m0.032s
sys 0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400
So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum
function (md5sum_read
in the above listing) is pretty similar to Omnifarious's:
import hashlib
def md5sum(filename, blocksize=65536):
hash = hashlib.md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
Granted, these are from single runs (the mmap
ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize)
after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum
on the command line is not necessarily faster than a Python implementation...
EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32()
call:
import zlib
def adler32sum(filename, blocksize=65536):
checksum = zlib.adler32("")
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
checksum = zlib.adler32(block, checksum)
return checksum & 0xffffffff
Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for ""
, which is 1
-- CRC can start with 0
instead. The AND
-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.
By all means mark this down for not-being-an-answer, but this problem of breakpoints not being hit, for me, just fixed itself. After hours of deleting temp files, rebooting, reinstalling, arsing around with debug settings to no avail, it just suddenly started working. I was on the verge of insanity when, for no reason at all, we hit a breakpoint. Love inconsistent bugs, me.
Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
You can't do variable manipulation in django templates. You have two options, either write your own template tag or do this in view,
If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
word = ' Hello World '
stripped = word.strip()
print(stripped)
You're trying to invoke an instance method on the class it self.
You should do:
Random rand = new Random();
int a = 0 ;
while (!done) {
int a = rand.nextInt(10) ;
....
Instead
As I told you here stackoverflow.com/questions/2694470/whats-wrong...
In order to get the MySQL Database item in the Choose Data Source window, one should install the MySQL for Visual Studio package available here (the last version today is 1.2.6):
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
Underscore-java can construct XML string with help of a builder.
class Customer {
String name;
int age;
int id;
}
Customer customer = new Customer();
customer.name = "John";
customer.age = 30;
customer.id = 12345;
String xml = U.objectBuilder().add("customer", U.objectBuilder()
.add("name", customer.name)
.add("age", customer.age)
.add("id", customer.id)).toXml();
// <?xml version="1.0" encoding="UTF-8"?>
// <customer>
// <name>John</name>
// <age number="true">30</age>
// <id number="true">12345</id>
// </customer>
As it is mentioned in the error that there is no --user so you have to follow these steps
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:
BARNABY_API int add(){
}
This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.
I would follow official projects like tar as an example. In my opinion help msg. needs to be simple and descriptive as possible. Examples of use are good too. There is no real need for "standard help".
You can use stri_detect_fixed function from stringi
package
stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1] TRUE FALSE
if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-
repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();
try like this
GNU parallel
and xargs
These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:
seq 10 | xargs -P4 -I'{}' echo '{}'
or:
seq 10 | parallel -j4 echo '{}'
See also: how to write a process-pool bash shell
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
thead {
position: fixed;
height: 10px; /* This is whatever height you want */
}
tbody {
position: fixed;
margin-top: 10px; /* This has to match the height of thead */
height: 300px; /* This is whatever height you want */
}
Typically you will find these underlying implementation-specific typedefs for gcc in the bits
or asm
header directory. For me, it's /usr/include/x86_64-linux-gnu/bits/types.h
.
You can just grep, or use a preprocessor invocation like that suggested by Quassnoi to see which specific header.
i do in this way ....
NSDate * mydate = [NSDate date];
NSCalendar * mycalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents * myComponents = [mycalendar components:units fromDate:mydate];
NSLog(@"%d-%d-%d",myComponents.day,myComponents.month,myComponents.year);
This problem is just because you have declared the column in CHAR, VARCHAR or TEXT datatype. Just change the datatype to INT, BIGINT etc. This is will solved the problem of your custom ordering.
With JUnit 5 I was able to solve this using the @RepeatedTest annotation:
@RepeatedTest(10)
public void testMyCode() {
//your test code goes here
}
Note that @Test
annotation shouldn't be used along with @RepeatedTest
.
Create a scope property called selectedIndex, and an itemClicked function:
function MyController ($scope) {
$scope.collection = ["Item 1", "Item 2"];
$scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection
$scope.itemClicked = function ($index) {
$scope.selectedIndex = $index;
};
}
Then my template would look something like this:
<div>
<span ng-repeat="item in collection"
ng-class="{ 'selected-class-name': $index == selectedIndex }"
ng-click="itemClicked($index)"> {{ item }} </span>
</div>
Just for reference $index is a magic variable available within ng-repeat directives.
You can use this same sample within a directive and template as well.
Here is a working plnkr:
use the configuration below;
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.springsource.ggts.ide
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-vm
C:\Program Files\Java\jdk1.7.0_51\jre\bin\javaw.exe
-vmargs
-Dorg.eclipse.swt.browser.IEVersion=10001
-Dgrails.console.enable.interactive=false
-Dgrails.console.enable.terminal=false
-Djline.terminal=jline.UnsupportedTerminal
-Dgrails.console.class=grails.build.logging.GrailsEclipseConsole
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx768m
-XX:MaxPermSize=256m
-Dorg.eclipse.swt.browser.IEVersion=10001
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text
[Display(Name = "Wild and Crazy")]
public string WildAndCrazyProperty { get; set; }
"Wild and Crazy" shows up consistently wherever you use the property in your application.
Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example
I guess that this single-line-return method is efficient enough to be used in such a simple job:
public enum Day {
SUNDAY,
MONDAY,
THURSDAY,
WEDNESDAY,
TUESDAY,
FRIDAY;
public static Day getRandom() {
return values()[(int) (Math.random() * values().length)];
}
public static void main(String[] args) {
System.out.println(Day.getRandom());
}
}
For unix systems only:
>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s") # <-- THIS IS THE CODE YOU WANT
'1293832800'
Note 1: dizzyf observed that this applies localized timezones. Don't use in production.
Note 2: Jakub Narebski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
Here's a simple wrapper for steven's answer. This function doesn't do repeated runs/averaging, just saves you from having to repeat the timing code everywhere :)
'''function which prints the wall time it takes to execute the given command'''
def time_func(func, *args): #*args can take 0 or more
import time
start_time = time.time()
func(*args)
end_time = time.time()
print("it took this long to run: {}".format(end_time-start_time))
Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.
To do this without any headache:
git status
, let's say branch "development".git clone
the project from repository.git checkout development
.rsync
, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1
. You don't have to do this with rsync
of course, but it does it so smooth.The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.
For npm's package.json, I have found two ways (after reading this conversation):
"devDependencies": {
"del-comment": [
"some-text"
],
"del": "^5.1.0 ! inner comment",
"envify-comment": [
"some-text"
],
"envify": "4.1.0 ! inner comment"
}
But with the update or reinstall of package with "--save" or "--save-dev, a comment like "^4.1.0 ! comment" in the corresponding place will be deleted. And all this will break npm audit.
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
Here a simple and easy solution on Angular JS using ng-repeat that might help.
var app = angular.module('myapp', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
_x000D_
$scope.arr= [_x000D_
{name:"Head1",desc:"Head1Desc"},_x000D_
{name:"Head2",desc:"Head2Desc"},_x000D_
{name:"Head3",desc:"Head3Desc"},_x000D_
{name:"Head4",desc:"Head4Desc"}_x000D_
];_x000D_
_x000D_
$scope.collapseIt = function(id){_x000D_
$scope.collapseId = ($scope.collapseId==id)?-1:id;_x000D_
}_x000D_
});
_x000D_
/* Put your css in here */_x000D_
li {_x000D_
list-style:none;_x000D_
padding:5px;_x000D_
color:red;_x000D_
}_x000D_
div{_x000D_
padding:10px;_x000D_
background:#ddd;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myapp">_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>AngularJS Simple Collapse</title>_x000D_
<script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>_x000D_
</head>_x000D_
<body ng-controller="MainCtrl">_x000D_
<ul>_x000D_
<li ng-repeat='ret in arr track by $index'>_x000D_
<div ng-click="collapseIt($index)">{{ret.name}}</div>_x000D_
<div ng-if="collapseId==$index">_x000D_
{{ret.desc}}_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
</html>
_x000D_
This should fulfill your requirements. Here is a working code.
Plunkr Link http://plnkr.co/edit/n5DZxluYHi8FI3OmzFq2?p=preview
Github: https://github.com/deepakkoirala/SimpleAngularCollapse
git branch -d branch1 branch2 branch3
already works, but will be faster with Git 2.31 (Q1 2021).
Before, when removing many branches and tags, the code used to do so one ref at a time.
There is another API it can use to delete multiple refs, and it makes quite a lot of performance difference when the refs are packed.
See commit 8198907 (20 Jan 2021) by Phil Hord (phord
).
(Merged by Junio C Hamano -- gitster
-- in commit f6ef8ba, 05 Feb 2021)
8198907795
:usedelete_refs
when deleting tags or branchesAcked-by: Elijah Newren
Signed-off-by: Phil Hord
'
git tag -d
'(man) accepts one or more tag refs to delete, but each deletion is done by callingdelete_ref
on eachargv
.
This is very slow when removing from packed refs.
Usedelete_refs
instead so all the removals can be done inside a single transaction with a single update.Do the same for '
git branch -d
'(man).Since
delete_refs
performs all the packed-refs delete operations inside a single transaction, if any of the deletes fail then all them will be skipped.
In practice, none of them should fail since we verify the hash of each one before callingdelete_refs
, but some network error or odd permissions problem could have different results after this change.Also, since the file-backed deletions are not performed in the same transaction, those could succeed even when the packed-refs transaction fails.
After deleting branches, remove the branch config only if the branch ref was removed and was not subsequently added back in.
A manual test deleting 24,000 tags took about 30 minutes using
delete_ref
.
It takes about 5 seconds usingdelete_refs
.
In case of a number you can try to convert to string:
var stringValue = str.toString();
return stringValue.replace(/^\s+|\s+$/g,'');
It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.
BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
case IntervalType.Month:
returnValue = start.AddMonths(-end.Month).Month.ToString();
break;
case IntervalType.Year:
returnValue = (start.Year - end.Year).ToString();
break;
You can just use Collections.rotate(List<?> list, int distance)
Use Arrays.asList(array)
to convert to List
more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)
Pure numpy
numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)
Check out the loadtxt documentation.
You can also use python's csv module:
import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")
You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:
result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")
Added Hint:
You could also use pandas.io.parsers.read_csv
and get the associated numpy
array which can be faster.
read "Dismiss on next click" here http://getbootstrap.com/javascript/#popovers
You can use the focus trigger to dismiss popovers on the next click, but you have to use use the <a>
tag, not the <button>
tag, and you also must include a tabindex
attribute...
Example:
<a href="#" tabindex="0" class="btn btn-lg btn-danger"
data-toggle="popover" data-trigger="focus" title="Dismissible popover"
data-content="And here's some amazing content. It's very engaging. Right?">
Dismissible popover
</a>
a = list(input("Enter a string\t: "))
def fun(a):
c =' '.join(['0'*(8-len(bin(ord(i))[2:]))+(bin(ord(i))[2:]) for i in a])
return c
print(fun(a))
Have a look at Control.BeginInvoke method. The point is to never update UI controls from another thread. BeginInvoke will dispatch the call to the UI thread of the control (in your case, the Form).
To grab the form, remove the static modifier from the sample function and use this.BeginInvoke() as shown in the examples from MSDN.
This will select duplicates in one table pass, no subqueries.
SELECT *
FROM (
SELECT ao.*, (@r := @r + 1) AS rn
FROM (
SELECT @_address := 'N'
) vars,
(
SELECT *
FROM
list a
ORDER BY
address, id
) ao
WHERE CASE WHEN @_address <> address THEN @r := 0 ELSE 0 END IS NOT NULL
AND (@_address := address ) IS NOT NULL
) aoo
WHERE rn > 1
This query actially emulates ROW_NUMBER()
present in Oracle
and SQL Server
See the article in my blog for details:
MySQL
.var result = listObject.Select( i => new{ i.category_name, i.category_id } )
This uses anonymous types so you must the var keyword, since the resulting type of the expression is not known in advance.
If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.
package edu.iu.common;_x000D_
_x000D_
import java.util.ArrayList;_x000D_
import java.util.Random;_x000D_
_x000D_
public class RandomCentroidLocator {_x000D_
_x000D_
public static void main(String [] args){_x000D_
_x000D_
int min =0;_x000D_
int max = 10;_x000D_
int numCentroids = 10;_x000D_
ArrayList<Integer> values = randomCentroids(min, max, numCentroids); _x000D_
for(Integer i : values){_x000D_
System.out.print(i+" ");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {_x000D_
_x000D_
boolean status = true;_x000D_
int count=0;_x000D_
for(Integer i : arr){_x000D_
if(i==num){_x000D_
count++;_x000D_
}_x000D_
}_x000D_
if(count==1){_x000D_
status = true;_x000D_
}else if(count>1){_x000D_
status =false;_x000D_
}_x000D_
_x000D_
_x000D_
return status;_x000D_
}_x000D_
_x000D_
// generate random centroid Ids -> these Ids can be used to retrieve data_x000D_
// from the data Points generated_x000D_
// simply we are picking up random items from the data points_x000D_
// in this case all the random numbers are unique_x000D_
// it provides the necessary number of unique and random centroids_x000D_
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {_x000D_
_x000D_
Random random = new Random();_x000D_
ArrayList<Integer> values = new ArrayList<Integer>();_x000D_
int num = -1;_x000D_
int count = 0;_x000D_
do {_x000D_
num = random.nextInt(max - min + 1) + min;_x000D_
values.add(num);_x000D_
int index =values.size()-1;_x000D_
if(unique(values, num, numCentroids)){ _x000D_
count++;_x000D_
}else{_x000D_
values.remove(index);_x000D_
}_x000D_
_x000D_
} while (!( count == numCentroids));_x000D_
_x000D_
return values;_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
Say your column names are dynamic, you can create an empty row-named matrix and transform it to a data frame.
nms <- sample(LETTERS,sample(1:10))
as.data.frame(t(matrix(nrow=length(nms),ncol=0,dimnames=list(nms))))
You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:
I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android
You can include it on your project only adding two lines into build.gradle
file thanks to jitpack.io service.
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
As of 5.5 you can run Kernel > Restart and Run All
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
My answer is "neither one".
I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.
This is usually done with enclosing the code in a try...except
clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).
Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".
As a trivial example consider:
if 'name' in dct:
value = dct['name'] * 3
else:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
vs
try:
value = dct['name'] * 3
except KeyError:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).
Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict:
is better for the reasons stated in the other answers.
If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).
Just check for process holding the session and Kill it. Its back to normal.
Below SQL will find your process
SELECT s.inst_id,
s.sid,
s.serial#,
p.spid,
s.username,
s.program FROM gv$session s
JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id;
Then kill it
ALTER SYSTEM KILL SESSION 'sid,serial#'
OR
some example I found online seems to need the instance id as well alter system kill session '130,620,@1';
I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.
I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).
The following recursive algorithm picks all of the k-element combinations from an ordered set:
i
of your combinationi
with each of the combinations of k-1
elements chosen recursively from the set of elements larger than i
.Iterate the above for each i
in the set.
It is essential that you pick the rest of the elements as larger than i
, to avoid repetition. This way [3,5] will be picked only once, as [3] combined with [5], instead of twice (the condition eliminates [5] + [3]). Without this condition you get variations instead of combinations.
This is mine. http://jsfiddle.net/pd1vojsL/
3 draggable buttons in a div, dragging constrained by div.
<div id="parent" class="parent">
<button id="button1" class="button">Drag me</button>
<button id="button2" class="button">Drag me</button>
<button id="button3" class="button">Drag me</button>
</div>
<div id="log1"></div>
<div id="log2"></div>
Requires JQuery (only):
$(function() {
$('.button').mousedown(function(e) {
if(e.which===1) {
var button = $(this);
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top')); //current top position
var original_ypos = button.css('top','').position().top; //original ypos (without top)
button.css({top:top+'px'}); //restore top pos
var drag_min_ypos = 0-original_ypos;
var drag_max_ypos = parent_height-original_ypos-button.outerHeight();
var drag_start_ypos = e.clientY;
$('#log1').text('mousedown top: '+top+', original_ypos: '+original_ypos);
$(window).on('mousemove',function(e) {
//Drag started
button.addClass('drag');
var new_top = top+(e.clientY-drag_start_ypos);
button.css({top:new_top+'px'});
if(new_top<drag_min_ypos) { button.css({top:drag_min_ypos+'px'}); }
if(new_top>drag_max_ypos) { button.css({top:drag_max_ypos+'px'}); }
$('#log2').text('mousemove min: '+drag_min_ypos+', max: '+drag_max_ypos+', new_top: '+new_top);
//Outdated code below (reason: drag contrained too early)
/*if(new_top>=drag_min_ypos&&new_top<=drag_max_ypos) {
button.css({top:new_top+'px'});
}*/
});
$(window).on('mouseup',function(e) {
if(e.which===1) {
//Drag finished
$('.button').removeClass('drag');
$(window).off('mouseup mousemove');
$('#log1').text('mouseup');
$('#log2').text('');
}
});
}
});
});
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
more +2 file1.txt > type > out.txt && type file2.txt > out.txt
I suggest to use this official way from MySql:
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article
GROUP BY s2.article)
ORDER BY article;
With this way, we can get the highest price on each article
You are looking for --build-arg
and the ARG
instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg
to the Dockerfile
and then build with docker build --build-arg arg=2.3 .
.
I had this problem for over 6 months, it may be the same issue. Main symptom is that you can't move the cursor or select text in text inputs, only the arrow keys allow you to move around in the input field. Very annoying problem, especially for textarea input fields. I have this html that gets populated with 1 out of 100s of forms via Javascript:
<div class="dialog" id="alert" draggable="true">
<div id="head" class="dialog_head">
<img id='icon' src='images/icon.png' height=20 width=20><img id='icon_name' src='images/icon_name.png' height=15><img id='alert_close_button' class='close_button' src='images/close.png'>
</div>
<div id="type" class="type"></div>
<div class='scroll_div'>
<div id="spinner" class="spinner"></div>
<div id="msg" class="msg"></div>
<div id="form" class="form"></div>
</div>
</div>
Apparently 6 months ago I had tried to make the popup draggable and failed, breaking text inputs at the same time. Once I removed draggable="true" it works again!
This way we can check for an existing file in a particular folder:
string curFile = @"c:\temp\test.txt"; //Your path
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
The best way to do it is:
return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");
'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.
You can use the following little trick:
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
The call
there causes another layer of variable expansion, making it necessary to quote the original %
signs but it all works out in the end.
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
There's a faster way, just use
YourActivity.setTitle("New Title");
You can also find it inside the onCreate() with this, for example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("My Title");
}
By the way, what you simply cannot do is call setTitle() in a static way without passing any Activity object.
Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.
Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.
create table calender(
day date not null -- Truncated date
,iso_year_week number(6) not null -- ISO Year week (IYYYIW)
,retail_week number(6) not null -- Monday to Sunday (YYYYWW)
,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
,primary key(day)
);
You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:
select a.colA
,a.colB
,b.first_day
,b.last_day
from your_table_with_weeks a
join (select iso_year_week
,min(day) as first_day
,max(day) as last_day
from calendar
group
by iso_year_week
) b on(a.iso_year_week = b.iso_year_week)
If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.
Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char()))
function calls.
I did debugging and finally returned my 'stuffed' query to it it's normal way.
Simply
select * from myTable for xml path('myTable')
gives me contents of the table to write to a log table from a trigger I debug.
Arrays.asList(array);
Example:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
See Arrays.asList
class documentation.
set the state data inside constructor like this
constructor(props) {
super(props);
this.state = {
productdatail: this.props.productdetailProps
};
}
it will not going to work if u set in side componentDidMount()
method through props.
This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"];
and then set a new value with config.ConnectionString = "your connection string";
. Note that if you have any comments in the connectionStrings
section in Web.Config
these will be removed.
private void UpdateAppSettings(string key, string value)
{
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
Add
[config]="{backdrop: 'static'}"
to the model code.
change in php.ini max_input_vars 1000
Eclipse is the most widely used development environment for the Android platform. The reason is that even Google itself providing the plug-in to be added in eclipse and start developing the applications. I have tried installing it from the eclipse market place, it is very easy and simple to create the android application. set up also very simple.
Update 2018-12-12 - Chrome App v Chrome Plugin - Most recent updates at top
With the deprecation of the Postman Chrome App, assuming that you are now using the Postman Native App, the options are now:
See below for full details on each option.
Personally, I still go for 2) Generate "Code" button/link as it allows me to see the variables without actually having to send.
1) Hover over variables with mouse
2) Generate "Code" button/link
Update: 2016-06-03
Whilst the method described above does work, in practice, I now normally use the "Generate Code" link on the Postman Request screen. The generated code, no matter what code language you choose, contains the substituted variables. Hitting the "Generate Code" link is just faster, additionally, you can see the substituted variables without actually making the request.
Original Answer below
To see the substituted variables in the Headers and Body, you need to use Chrome Developer tools. To enable Chrome Developer Tools from within Postman do the following, as per http://blog.getpostman.com/2015/06/13/debugging-postman-requests/.
I have copied the instructions from the link above in case the link gets broken in the future:
Type chrome://flags inside your Chrome URL window
Search for “packed” or try to find the “Enable debugging for packed apps”
Enable the setting
Restart Chrome
You can access the Developer Tools window by right clicking anywhere inside Postman and selecting “inspect element”. You can also go to chrome://inspect/#apps and then click “inspect” just below requester.html under the Postman heading.
Once enabled, you can use the Network Tools tab for even more information on your requests or the console while writing test scripts. If something goes wrong with your test scripts, it’ll show up here.
CodeIgniter User Guide says:
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news 2. local 3. metro 4. crime_is_up
So segment
refers to your url structure segment. By the above example, $this->uri->segment(3)
would be 'metro'
, while $this->uri->segment(4)
would be 'crime_is_up'
.
This is probably the best option in C#.
If you want to know if the string contains a whole number (integer):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.
Solutions using the int.Parse(someString)
alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...)
was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should therefore avoid the Parse()
alternative.
If you want to accept decimal numbers, the decimal class also has a .TryParse(...)
method. Replace int with decimal in the above discussion, and the same principles apply.
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>
, or it won't work!
Another option if you want to preserve translucency and you don't want to subclass every UINavigationController
in your app:
#import <objc/runtime.h>
@implementation UINavigationController (NoShadow)
+ (void)load {
Method original = class_getInstanceMethod(self, @selector(viewWillAppear:));
Method swizzled = class_getInstanceMethod(self, @selector(swizzled_viewWillAppear:));
method_exchangeImplementations(original, swizzled);
}
+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
- (void)swizzled_viewWillAppear:(BOOL)animated {
UIImageView *shadow = [UINavigationController findHairlineImageViewUnder:self.navigationBar];
shadow.hidden = YES;
[self swizzled_viewWillAppear:animated];
}
@end
In your invocation, the two functions are the same.
average
can compute a weighted average though.
tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()
for columns in jayscolumnlist:
print columns[0]
for i in range(len(jayscolumnlist)):
print columns[i][0])
Because $("input[type='number']")
doesn't work on IE, we should use a class name or id, for example, $('.input_quantity')
.
And don't use .bind()
method. The .on()
method is the preferred method for attaching event handlers to a document.
So, my version is:
HTML
<input type="number" value="5" step=".5" min="1" max="999" id="txt_quantity" name="txt_quantity" class="input_quantity">
jQuery
<script>
$(document).ready(function(){
$('.input_quantity').on('change keyup', function() {
console.log('nice');
});
});
</script>
Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0;
does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17
memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more
It is true that, functionally, both queries should be processed the same way. However, experience has shown that if you are selecting from views that use the new join syntax, it is important to structure your queries using it as well. Oracle's optimizer can get confused if a view uses a "join" statement, but a query accessing the view uses the traditional method of joining in the "where" clause.
Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.
There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.
Let me know if there additional problems you are missing.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
It worth to say that discussed topic is documented in RFC 2397 - The "data" URL scheme (https://tools.ietf.org/html/rfc2397)
Because of this PHP has a native way to handle such data - "data: stream wrapper" (http://php.net/manual/en/wrappers.data.php)
So you can easily manipulate your data with PHP streams:
$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
$source = fopen($data, 'r');
$destination = fopen('image.gif', 'w');
stream_copy_to_stream($source, $destination);
fclose($source);
fclose($destination);
You can create the sql to update all tables with:
SELECT CONCAT("ALTER TABLE ",TABLE_SCHEMA,".",TABLE_NAME," CHARACTER SET utf8 COLLATE utf8_general_ci; ",
"ALTER TABLE ",TABLE_SCHEMA,".",TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; ")
AS alter_sql
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "your_database_name";
Capture the output and run it.
Arnold Daniels' answer above is more elegant.
This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:
map $http_host $variable_name {
hostnames;
default /ap/;
example.com /api/;
*.example.org /whatever/;
}
server {
location $variable_name/test {
proxy_pass $auth_proxy;
}
}
If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:
map "" $variable_name {
default /test/;
}
Map can be used to initialise a variable based on the content of a string and can be used inside http
scope allowing variables to be global and sharable across servers.
w.female.replace(to_replace=dict(female=1, male=0), inplace=True)
Here is the swift 3 updated answer
var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0) Backslash (\\) Horizontal Tab (\t) Line Feed (\n) Carriage Return (\r) Double Quote (\") Single Quote (\') Unicode scalar (\u{n})
The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.
Yes, you can add padding by adding padding.
android:padding=5dp
PHP passes Arrays and Objects by reference (pointers). If you want to pass a normal variable Ex. $var = 'boo'; then use $boo = &$var;.
Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:
const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);
const readContentFile = async (filePath) => {
// Eureka, you are using good code practices here!
const content = await readFileAsync(path.join(__dirname, filePath), {
encoding: 'utf8'
})
return content;
}
Later can use this async function with try/catch from any other function:
const anyOtherFun = async () => {
try {
const fileContent = await readContentFile('my-file.txt');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
}
Happy Coding!
you can try quoting it which will keep the link as text. see the code blocks section: https://get.slack.help/hc/en-us/articles/202288908-Format-your-messages#code-blocks
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
I met similar problem. the log is like below
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: still could not bind()
2018/10/31 12:54:23 [alert] 127997#127997: unlink() "/run/nginx.pid" failed (2: No such file or directory)
2018/10/31 22:40:48 [info] 36948#36948: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
2018/10/31 22:50:40 [emerg] 37638#37638: duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/default:18
2018/10/31 22:51:33 [info] 37787#37787: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
The last [emerg]
shows that duplicate listen options for [::]:80
which means that there are more than one nginx block file containing [::]:80
.
My solution is to remove one of the [::]:80
setting
P.S. you probably have default block file. My advice is to keep this file as default server for port 80. and remove [::]:80
from other block files
When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a Resources.resx
file under the Properties
section, if not, you can easily add your own Resource.resx
file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.
After having resource files in your project, calling them is easy as this:
var myIcon = Resources.MyIconFile;
Of course you should add the using Properties
statement like this:
using <namespace>.Properties;
Sourcetree: resetting remote to a certain commit
When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.
See MSDN for the full syntax.
a fresh answer to a very old question:
starting from python 3.2 you can do this:
import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)
thanks to the exist_ok
flag this will not even complain if the directory exists (depending on your needs....).
starting from python 3.4 (which includes the pathlib module) you can do this:
from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)
starting from python 3.5 mkdir
also has an exist_ok
flag - setting it to True
will raise no exception if the directory exists:
path.mkdir(parents=True, exist_ok=True)
if some reason two versions of jQuery
are loaded (which is not recommended), calling $.noConflict(true)
from the second version will return the globally scoped jQuery
variables to those of the first version.
Some times it could be issue with older version (or not stable version) of JQuery
files
Solution use $.noConflict();
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$("#opener").click(function() {
$("#dialog1").dialog('open');
});
});
// Code that uses other library's $ can follow here.
</script>
Try dragging a UIView
onto the screen in IB. From there you can drag a UIImageView
and UILabel
into the view you just created. Set the image of the UIImageView
in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.
To clear the history, simply do:
this.appView.clearHistory();
Source: http://developer.android.com/reference/android/webkit/WebView.html
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");