If you have a parent-pom anyways, then in my opinion using <dependencyManagement>
just for controlling the version (and maybe scope) is a waste of space and confuses junior developers.
You will probably have properties for versions anyways, in some kind of parent-pom file. Why not just use this properties in the child pom's? That way you can still update a version in the property (within parent-pom) for all child projects at once. That has the same effect as <dependencyManagement>
just without <dependencyManagement>
.
In my opinion, <dependencyManagement>
should be used for "real" management of dependencies, like exclusions and the like.
None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:
<repository>
<id>1_maven.apache.org</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>true</enabled> </snapshots>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
</repository>
<repository>
<id>2_maven.oracle.com</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>false</enabled> </snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
Go to build path... delete existing maven library u added... click add library ... click maven managed dependencies... then click maven project settings... check resolve maven dependencies check box..it'll download all maven dependencies
You need to copy the dependency you need for project.
Having these in hand please clear all the <dependency>
tag embedded into <dependencies>
tag
from POM.XML file in your project.
After saving the file you will not see Maven Dependencies in your Libraries
.
Then please paste those <dependency>
you have copied earlier.
The required jars will be automatically downloaded by Maven, you can see that too in
the generated Maven Dependencies Libraries
after saving the file.
Thanks.
I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(
after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.
composer require [vendorName]/[packageName]:dev-[gitBranchName]
You can put this configuration in your settings.xml file:
<repository>
<id>mvnrepository</id>
<url>http://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
Run yarn cache clean
.
Run yarn help cache
in your bash, and you will see:
Usage: yarn cache [ls|clean] [flags]
Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executingVisit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.
The best way to do it is to add this in your build.gradle file and hit the sync option
dependency{
compile files('path.jar')
}
You should debug first, to help identify your level of XML hell. In my opinion, the first step is to add
-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
to the command line. If that works, then start excluding libraries. If not, then add
-Djaxp.debug=1
to the command-line.
For me the issue was I did not have my webpack build mode set to production for the package I was referencing in. Explicitly setting it to "build": "webpack --mode production" fixed the issue.
In Android Stuido, I like use Gradle to manage Gson lib.
Add below dependency in your build.gradle file.
repositories {mavenCentral()}
dependencies {compile 'com.google.code.gson:gson:2.2.4'}
Everything is OK.
You can also see this post. The best way to integrate third party library in Android studio
Compile
configuration was deprecated and should be replaced by implementation
or api
.
You can read the docs at https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation.
The brief part being-
The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers. A library is a Java component meant to be consumed by other components. It's a very common use case in multi-project builds, but also as soon as you have external dependencies.
The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.
usually in maven we have two types of builds 1)Snapshot builds 2)Release builds
snapshot builds:SNAPSHOT is the special version that indicate current deployment copy not like a regular version, maven checks the version for every build in the remote repository so the snapshot builds are nothing but development builds.
Release builds:Release means removing the SNAPSHOT at the version for the build, these are the regular build versions.
Two things you need to do, if you want to make a custom button design.
1st is: create a xml resource file in drawable folder (Example: btn_shape_rectangle.xml) then copy and paste the code there.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:shape="rectangle">
<solid
android:color="#fff"/>
<stroke
android:width="1dp"
android:color="#000000"
/>
<corners android:radius="10dp" />
</shape>
2nd is go to your layout button where you want to implement this design. just link up it. Example: android:background="@drawable/btn_shape_rectangle"
You can change shape color radius what design you want can do.
Hope it will works and help you. Happy Coding
Here is the MD5 code inserted in an Excel Module with the name "module_md5":
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)
Sub SetUpArrays()
m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)
End Sub
Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function
Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function
Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function
Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function
Private Function F(x, y, z)
F = (x And y) Or ((Not x) And z)
End Function
Private Function G(x, y, z)
G = (x And z) Or (y And (Not z))
End Function
Private Function H(x, y, z)
H = (x Xor y Xor z)
End Function
Private Function I(x, y, z)
I = (y Xor (x Or (Not z)))
End Function
Private Sub FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function
Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function
Public Function MD5(sMessage)
module_md5.SetUpArrays
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
FF a, b, c, d, x(k + 0), S11, &HD76AA478
FF d, a, b, c, x(k + 1), S12, &HE8C7B756
FF c, d, a, b, x(k + 2), S13, &H242070DB
FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
FF d, a, b, c, x(k + 5), S12, &H4787C62A
FF c, d, a, b, x(k + 6), S13, &HA8304613
FF b, c, d, a, x(k + 7), S14, &HFD469501
FF a, b, c, d, x(k + 8), S11, &H698098D8
FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
FF b, c, d, a, x(k + 11), S14, &H895CD7BE
FF a, b, c, d, x(k + 12), S11, &H6B901122
FF d, a, b, c, x(k + 13), S12, &HFD987193
FF c, d, a, b, x(k + 14), S13, &HA679438E
FF b, c, d, a, x(k + 15), S14, &H49B40821
GG a, b, c, d, x(k + 1), S21, &HF61E2562
GG d, a, b, c, x(k + 6), S22, &HC040B340
GG c, d, a, b, x(k + 11), S23, &H265E5A51
GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
GG a, b, c, d, x(k + 5), S21, &HD62F105D
GG d, a, b, c, x(k + 10), S22, &H2441453
GG c, d, a, b, x(k + 15), S23, &HD8A1E681
GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
GG d, a, b, c, x(k + 14), S22, &HC33707D6
GG c, d, a, b, x(k + 3), S23, &HF4D50D87
GG b, c, d, a, x(k + 8), S24, &H455A14ED
GG a, b, c, d, x(k + 13), S21, &HA9E3E905
GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
GG c, d, a, b, x(k + 7), S23, &H676F02D9
GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
HH a, b, c, d, x(k + 5), S31, &HFFFA3942
HH d, a, b, c, x(k + 8), S32, &H8771F681
HH c, d, a, b, x(k + 11), S33, &H6D9D6122
HH b, c, d, a, x(k + 14), S34, &HFDE5380C
HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
HH a, b, c, d, x(k + 13), S31, &H289B7EC6
HH d, a, b, c, x(k + 0), S32, &HEAA127FA
HH c, d, a, b, x(k + 3), S33, &HD4EF3085
HH b, c, d, a, x(k + 6), S34, &H4881D05
HH a, b, c, d, x(k + 9), S31, &HD9D4D039
HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
HH b, c, d, a, x(k + 2), S34, &HC4AC5665
II a, b, c, d, x(k + 0), S41, &HF4292244
II d, a, b, c, x(k + 7), S42, &H432AFF97
II c, d, a, b, x(k + 14), S43, &HAB9423A7
II b, c, d, a, x(k + 5), S44, &HFC93A039
II a, b, c, d, x(k + 12), S41, &H655B59C3
II d, a, b, c, x(k + 3), S42, &H8F0CCC92
II c, d, a, b, x(k + 10), S43, &HFFEFF47D
II b, c, d, a, x(k + 1), S44, &H85845DD1
II a, b, c, d, x(k + 8), S41, &H6FA87E4F
II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
II c, d, a, b, x(k + 6), S43, &HA3014314
II b, c, d, a, x(k + 13), S44, &H4E0811A1
II a, b, c, d, x(k + 4), S41, &HF7537E82
II d, a, b, c, x(k + 11), S42, &HBD3AF235
II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next
MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
End Function
this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -
Used the cmd to install python and flask after creating environment as suggested above.
Followed this answer.
Obviously kept the correct python interpreter (the one in the environment) everywhere.
Vue
allows for you to specify a default prop
value and type
directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):
props: {
year: {
default: 2016,
type: Number
}
}
If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:
Any reason you cannot just change it on the object directly? It is not as if javascript enforces visibility of a property on an object.
Looking at the output of free -m
it seems to me that you actually do not have swap memory available. I am not sure if in Linux the swap always will be available automatically on demand, but I was having the same problem and none of the answers here really helped me. Adding some swap memory however, fixed the problem in my case so since this might help other people facing the same problem, I post my answer on how to add a 1GB swap (on Ubuntu 12.04 but it should work similarly for other distributions.)
You can first check if there is any swap memory enabled.
$sudo swapon -s
if it is empty, it means you don't have any swap enabled. To add a 1GB swap:
$sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
$sudo mkswap /swapfile
$sudo swapon /swapfile
Add the following line to the fstab
to make the swap permanent.
$sudo vim /etc/fstab
/swapfile none swap sw 0 0
Source and more information can be found here.
I had the same exact issue, Maybe you already chececked this but got it solved just by placing the "images" folder in the same location as the jquery-ui.css
Please put this code in head section
<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
and use font-family: 'Lato', sans-serif;
in your css. For example:
h1 {
font-family: 'Lato', sans-serif;
font-weight: 400;
}
Or you can use manually also
Generate .ttf
font from fontSquiral
and can try this option
@font-face {
font-family: "Lato";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Called like this
body {
font-family: 'Lato', sans-serif;
}
The main difference is ::
npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json
npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).
Ponits to note::
One more thing, npm build
and npm run build
are two different things, npm run build
will do custom work written inside package.json
and npm build
is a pre-defined script (not available to use directly)
You cannot specify some thing inside custom build script (npm run build
) script and expect npm build
to do the same. Try following thing to verify in your package.json
:
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }
and run npm run build
and npm build
one by one and you will see the difference. For more about commands kindly follow npm documentation.
Cheers!!
Try the following method:
dt=`case "$OSTYPE" in darwin*) date -v-1d "+%s"; ;; *) date -d "1 days ago" "+%s"; esac`
echo $dt
It works on both Linux and OSX.
I went through all the previous answers (and answers to similar questions) without success, so here is what finally worked for me. The key step was to explicitly grant privileges on the mysql server to a local user (for the server), but with my local IP appended to it (myuser@*.*.*.*
). The complete step by step solution is as follows:
Comment out the bind_address
line in /etc/mysql/my.cnf
at the server (i.e. the EC2 Instance). I suppose
bind_address=0.0.0.0
would also work, but it's not needed as
others have mentioned.
Add a rule (as others have mentioned too) for MYSQL to the EC2 instance's security group with port 3306 and either My IP
or Anywhere
as Source. Both work fine after following all the steps.
Create a new user myuser
with limited privileges to one particular
database mydb
(basically following the instructions in this Amazon tutorial):
$EC2prompt> mysql -u root -p
[...omitted output...]
mysql> CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'your_strong_password';
mysql> GRANT ALL PRIVILEGES ON 'mydb'.* TO 'myuser'@'localhost';`
Here's the key step, without which my local address was refused when attempting a remote connection (ERROR 1130 (HY000): Host '*.*.*.23' is not allowed to connect to this MySQL server)
:
mysql> GRANT ALL PRIVILEGES ON 'mydb'.* TO 'myuser'@'*.*.*.23';
mysql> FLUSH PRIVILEGES;`
(replace '*.*.*.23'
by your local IP address)
For good measure, I exited mysql to the shell and restarted the msyql server:
$EC2prompt> sudo service mysql restart
After these steps, I was able to happily connect from my computer with:
$localprompt> mysql -h myinstancename.amazonaws.com -P 3306 -u myuser -p
(replace myinstancename.amazonaws.com
by the public address of your EC2 instance)
Using bash to look for a process with the current script's name. No extra file.
import commands
import os
import time
import sys
def stop_if_already_running():
script_name = os.path.basename(__file__)
l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
if l[1]:
sys.exit(0);
To test, add
stop_if_already_running()
print "running normally"
while True:
time.sleep(3)
This is the correct syntax for archiving individual; folders in a batch as individual zipped files...
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"
I have followed https://gist.github.com/n3dst4/b932117f3453cc6c56be link and I was able to renamed my entire solution successfully.
Me and my buddy created a web service to handle this kind of thing.
Check out Modifly.co for instructions on how to transform CSV to JSON with a single RESTful call.
Use:
setTimeout(startTimer,startInterval);
You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().
Replace all latters from any language in 'A', and if you wish for example all digits to 0:
return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");
Solution only works on Mac OS X
If you've installed MySQL with homebrew, what worked for me was uninstalling MySQL, and installing MySQL Community Edition via the MySQL website (https://www.mysql.com/).
After installed, just re-enter the command to gem install mysql2
or if necessary, sudo gem install mysql2
, if you are getting permission denied problems.
http://maps.google.com/maps?q=58%2041.881N%20152%2031.324W
Just use the coordinates as q
-parameter. Strip the z
and t
prameters. While z
should actually just be the zoom level, it seems that it won't work if you set any.
t
is the map type. Having that said, it's not obvious how those parameters would affect the result in the shown way. But they do.
Maybe you should try the ll
-parameter, but only decimal format will be accepted.
You can find a quick overview of all the parameters here.
Update: to sort dirpath
's entries by modification date in Python 3:
import os
from pathlib import Path
paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
(put @Pygirl's answer here for greater visibility)
If you already have a list of filenames files
, then to sort it inplace by creation time on Windows:
files.sort(key=os.path.getctime)
The list of files you could get, for example, using glob
as shown in @Jay's answer.
old answer
Here's a more verbose version of @Greg Hewgill
's answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).
#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time
# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)
# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date
# but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date
for cdate, path in sorted(entries):
print time.ctime(cdate), os.path.basename(path)
Example:
$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py
IF you happen to have ODBC set up, you can get the password from the ODBC config file. This is in /etc/odbc.ini for Linux and in the Software/ODBC folder in the registry in Windows (there are several - it may take some hunting)
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
I was having the same problem where the browser was unable to find the font files, and my issue was due to exclusions in my .htaccess file that was whitelisting files that shouldn't be sent to index.php
for processing. As the font file couldn't be loaded the characters were replaced with BLOB.
RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|svg|css|js|ico|rss|xml|json)$
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^ index.php [L,QSA]
As you can see, files like images, rss, and xml are excluded from the rewrite, but the font files are .woff
and .woff2
files, so these also needed adding to the whitelist.
RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|svg|css|js|ico|rss|xml|json|woff|woff2)$
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^ index.php [L,QSA]
Adding woff
and woff2
to the whitelist allows the font files to be loaded, and the glyphicons should then display properly.
The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.
const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);
background-size: 200px 50px change it to 100% 100% and it will scale on the needs of the content tag like ul li or div... tried it
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
,reset() method does not clear the default values and checkbox field and there are many more issues.
In order to completely reset check the below link -
http://www.javascript-coder.com/javascript-form/javascript-reset-form.htm
You can pass the variable to the Makefile like below:
run:
@echo ./prog $$FOO
Usage:
$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat
or:
$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat
Alternatively use the solution provided by Beta:
run:
@echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
@:
%:
- rule which match any task name;@:
- empty recipe = do nothing
Usage:
$ make run the dog kicked the cat
./prog the dog kicked the cat
I stumbled upon this question because I created, successfully built and published a PyPI Package, but couldn't execute it after installation. The $PATH
variable was correctly set.
In my case the problem was that I hadn't set the entry_point
in the setup.py
file:
entry_points = {'console_scripts':
['YOUR_CONSOLE_COMMAND=MODULE_NAME.FILE_NAME:FUNCTION_NAME'],},
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
A few suggestions:
The above effects could be 'improved' by redeploying the application ;)
Recently stumbled upon this:
Read http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5072161 and linked issues for an in-depth-discussion.
If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.
CREATE TABLE #Table(C1 int,
C2 NVarchar(100) , C3 varchar(100)
UNIQUE CLUSTERED (c1)
);
Create table with unique clustered index
Insert data into Temp "#Table" table
Create non clustered indexes.
CREATE NONCLUSTERED INDEX IX1 ON #Table (C2,C3);
Your code is in the <head>
=> runs before the elements are rendered, so document.getElementById('compute');
returns null, as MDN promise...
element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.
Solutions:
What is the jQuery ready
event and why is it needed?
(why no just JavaScript's load event):
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...
ready
docs
Here is a simple and backward compatible way to deliver ripple effect to raised buttons with the custom background.
Your layout should look like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_custom_background"
android:foreground="?android:attr/selectableItemBackground"/>
<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
<TR style="vertical-align:top">
<TD>
<!-- The log text-box -->
<div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
Log:
</div>
</TD>
<TD>
<!-- The 2nd column -->
</TD>
<TD>
<!-- The 3rd column -->
</TD>
</TR>
</TABLE>
Use the below code to convert a php array to CSV
<?php
$ROW=db_export_data();//Will return a php array
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
$fp = fopen('php://output', 'w');
foreach ($ROW as $row) {
fputcsv($fp, $row);
}
fclose($fp);
h1 {_x000D_
color: black;_x000D_
-webkit-text-fill-color: white; /* Will override color (regardless of order) */_x000D_
-webkit-text-stroke-width: 1px;_x000D_
-webkit-text-stroke-color: black;_x000D_
}
_x000D_
<h1>Properly stroked!</h1>
_x000D_
Take a look at permatswap()
in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.
mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
This gives:
R> out$perm[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 1
[2,] 0 1 0 1 0
[3,] 0 0 0 1 1
[4,] 1 0 0 0 1
R> out$perm[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 1 1
[2,] 0 0 0 1 1
[3,] 1 0 0 1 0
[4,] 0 0 1 0 1
To explain the call:
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
times
is the number of randomised matrices you want, here 99burnin
is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matricesthin
says only take a random draw every thin
swapsmtype = "prab"
says treat the matrix as presence/absence, i.e. binary 0/1 data.A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin
is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.
Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.
Just execute
sudo npm i --save
That's all
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
SELECT json_agg(t) FROM t
for a JSON array of objects, and
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
for a JSON object of arrays.
This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:
[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]
The json_agg
function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.
SELECT json_agg(t) FROM t
There is no jsonb
(introduced in 9.4) version of json_agg
. You can either aggregate the rows into an array and then convert them:
SELECT to_jsonb(array_agg(t)) FROM t
or combine json_agg
with a cast:
SELECT json_agg(t)::jsonb FROM t
My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.
9.2 does not have the json_agg
or to_json
functions, so you need to use the older array_to_json
:
SELECT array_to_json(array_agg(t)) FROM t
You can optionally include a row_to_json
call in the query:
SELECT array_to_json(array_agg(row_to_json(t))) FROM t
This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.
I wasn't able to discern any significant performance difference between the two.
This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:
{"a":[1,2,3], "b":["value1","value2","value3"]}
We can leverage the json_build_object
function:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
You can also aggregate the columns, creating a single row, and then convert that into an object:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.
Which one is clearer is a matter of opinion. If using the json_build_object
function, I highly recommend putting one key/value pair on a line to improve readability.
You could also use array_agg
in place of json_agg
, but my testing indicates that json_agg
is slightly faster.
There is no jsonb
version of the json_build_object
function. You can aggregate into a single row and convert:
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Unlike the other queries for this kind of result, array_agg
seems to be a little faster when using to_jsonb
. I suspect this is due to overhead parsing and validating the JSON result of json_agg
.
Or you can use an explicit cast:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)::jsonb
FROM t
The to_jsonb
version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.
The json_build_object
function was new to 9.5, so you have to aggregate and convert to an object in previous versions:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
or
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
depending on whether you want json
or jsonb
.
(9.3 does not have jsonb
.)
In 9.2, not even to_json
exists. You must use row_to_json
:
SELECT row_to_json(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Find the documentation for the JSON functions in JSON functions.
json_agg
is on the aggregate functions page.
If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.
Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.
Aggregate functions typically give back NULL
when they operate over zero rows. If this is a possibility, you might want to use COALESCE
to avoid them. A couple of examples:
SELECT COALESCE(json_agg(t), '[]'::json) FROM t
Or
SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t
Credit to Hannes Landeholm for pointing this out
How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+"
.
If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"
You can run maven in offline mode mvn -o install
. Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos.
In addition, the mvn dependency:go-offline
can be used to ensure you have all of your dependencies installed locally before you begin to work offline.
For tab separated values the code below can be used
sort -t$'\t' -k2 -n
-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code
sort -t$'\t' -k2 -rn
Here is a way to do it without adding an ID to the form elements.
<form method="post">
...
<select name="List">
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
<select name="List">
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
...
</form>
public ActionResult OrderProcessor()
{
string[] ids = Request.Form.GetValues("List");
}
Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:
public class OrderModel
{
public string[] List { get; set; }
}
public ActionResult OrderProcessor(OrderModel model)
{
string[] ids = model.List;
}
Hope this helps.
A simpler but equally effective option would be:
+ theme_bw(base_size=X)
You can try to use the bringChildToFront
, you can check if this documentation is helpful in the Android Developers page.
var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
Name = r.Field<string>("Name"),
Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
Just run the command:
php artisan migrate:refresh --seed
Submit a form that contains an input with value of canvas toDataURL('image/png') e.g
//JAVASCRIPT
var canvas = document.getElementById("canvas");
var url = canvas.toDataUrl('image/png');
Insert the value of the url to your hidden input on form element.
//PHP
$data = $_POST['photo'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = base64_decode($data);
file_put_contents("i". rand(0, 50).".png", $data);
If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).
The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.
You should set JAVA_HOME
based on current Java you are using.
readlink
will print value of a symbolic link for current Java and sed
will adjust it to JRE directory:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
If you want to set up JAVA_HOME to JDK you should go up one folder more:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
If you want to have your ls colorized you have to edit your ~/.bash_profile file and add the following line (if not already written) :
source .bashrc
Then you edit or create ~/.bashrc file and write an alias to the ls command :
alias ls="ls -G"
Now you have to type source .bashrc
in a terminal if already launched, or simply open a new terminal.
If you want more options in your ls
juste read the manual ( man ls
). Options are not exactly the same as in a GNU/Linux system.
TextMate with the Django and django-html bundles installed gives you syntax highlighting and great extensibility. It is lightweight and fun to use.
Here is a link to a code completion project for TextMate with Python (which I haven't used myself). As for "intellisense" (which I understand to be inline-doc reference), TextMate has that too.
Why not just use:
$("#foo span")
or
$("#foo > span")
$('span', $('#foo'));
works fine on my machine ;)
Disable all indexes (including the pk, which will disable all fks), then reenable the pks.
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)
from
sys.tables t
where type='u'
select @sql = @sql +
'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.key_constraints i
join
sys.tables t on i.parent_object_id=t.object_id
where
i.type='PK'
exec dbo.sp_executesql @sql;
go
[Do your data load]
Then bring everything back to life...
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.tables t
where type='u'
exec dbo.sp_executesql @sql;
go
You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
I got solution after working whole day on it. It is little hacky solution Added span inside td tag
<td><span><%= item.StartICDate %></span></td>.
Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0
If you write software, or use software written, which stores program window coordinates or sizes to be resused when starting a program, check there for any occurrence(s) of such sizes and positions which would be causing this. I've seen it time and time again from various vendors lazily producing code which resizes and repositions controls on a "form" (a program window) based on the size of said form. Look in HKLM\Software\Vendor\Program and HKCU\Software\Vendor\Program. Look for specific keys which might be offending. I once had a program store -48000 for the program window position in keys called WindowsPosX and WindowPosY. You could see the program start and running on the taskbar but since the program window itself was smaller than 48000 (the absolute value of -48000), it was positioned completely off the screen. If you're not comfortable with editing regstry information - most people aren't - then uninstall the software, use a registry cleaner to remove any leftover entries then reinstall the software and see if that doesn't fix the problem.
Check the site's Application Pool in IIS / Application Pools / YourPool / Advanced Settings :
There's some anecdotal evidence to suggest you do this too:
You may be interested in using a ORM like Mongoid or MongoMapper.
http://mongoid.org/docs/relations/referenced/1-n.html
In a NoSQL database like MongoDB there are not 'tables' but collections. Documents are grouped inside Collections. You can have any kind of document ā with any kind of data ā in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.
What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.
Edit:
In mongoid you will write your scheme like this:
class Student
include Mongoid::Document
field :name
embeds_many :addresses
embeds_many :scores
end
class Address
include Mongoid::Document
field :address
field :city
field :state
field :postalCode
embedded_in :student
end
class Score
include Mongoid::Document
belongs_to :course
field :grade, type: Float
embedded_in :student
end
class Course
include Mongoid::Document
field :name
has_many :scores
end
Edit:
> db.foo.insert({group:"phones"})
> db.foo.find()
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
{ "_id" : ObjectId("4df6540fe90592692ccc9941"), "group" : "phones" }
>db.foo.find({'_id':ObjectId("4df6539ae90592692ccc9940")})
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
You can use that ObjectId in order to do relations between documents.
To access field or method of an object use dot .
:
user = User()
print user.fullName
If a name of the field will be defined at run time, use buildin getattr
function:
field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName
Java byte compare,
public static boolean equals(byte[] a, byte[] a2) {
if (a == a2)
return true;
if (a == null || a2 == null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i = 0; i < length; i++)
if (a[i] != a2[i])
return false;
return true;
}
There is HTML and URI encodings. &
is &
encoded in HTML while %26
is &
in URI encoding.
So before URI encoding your string you might want to HTML decode and then URI encode it :)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
result %26AndOtherHTMLEncodedStuff
Hope this saves you some time
If you want to do an executable jar file, them need set the main class too. So the full configuration should be.
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- ... -->
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
To run an individual test:
npm test -t ValidationUtil # `ValidationUtil` is my module `ValidationUtil.spec.js`
-t
- after it, put a regular expression containing the test name.
Might be wrong but:
Tinyint is an integer between 0 and 255
bit is either 1 or 0
Therefore to me bit is the choice for booleans
Handlebars partials take a second parameter which becomes the context for the partial:
{{> person this}}
In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:
{{> person headline='Headline'}}
You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32
Try using online generator css3.me
Change the value and get the code, pretty simple.
Using Postman for Chrome, selecting CODE you get this... And works
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
CURLOPT_RETURNTRANSFER => true,_x000D_
CURLOPT_ENCODING => "",_x000D_
CURLOPT_MAXREDIRS => 10,_x000D_
CURLOPT_TIMEOUT => 30,_x000D_
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"[email protected]\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
CURLOPT_HTTPHEADER => array(_x000D_
"cache-control: no-cache",_x000D_
"content-type: application/json",_x000D_
"x-api-key: whateveriyouneedinyourheader"_x000D_
),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
As per the Javadoc, the MimeMessage#setText()
sets a default mime type of text/plain
, while you need text/html
. Rather use MimeMessage#setContent()
instead.
message.setContent(someHtmlMessage, "text/html; charset=utf-8");
For additional details, see:
no, there is no way to make array length dynamic in java. you can use ArrayList
or other List
implementations instead.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
My problem was that POST requests need trailing slashes '/'.
How about something like:
SELECT mt.*
FROM MyTable mt INNER JOIN
(
SELECT id, MIN(record_date) AS MinDate
FROM MyTable
GROUP BY id
) t ON mt.id = t.id AND mt.record_date = t.MinDate
This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.
Call decode()
on a bytes
instance to get the text which it encodes.
str = bytes.decode()
There is no such font as āCalibri (Body)ā. You probably saw this string in Microsoft Word font selection menu, but itās not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browserās default sans-serif font suits your design better than the browserās default font, which is most often a serif font.)
While uninstalling Angular CLI I got the same message (as it had some permission issues):
Unable to delete .Staging folder
I tried deleting the .staging
folder manually, but still got the same error. I logged in from my administrator account and tried deleting the staging folder again manually, but to no avail.
I tried this (run as Administrator):
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli.
Then I tried creating the project from my normal user account and it worked.
Try this. It holds the color until another item is clicked.
<style type="text/css">
.activeElem{
background-color:lightblue
}
.desactiveElem{
background-color:none
}
}
</style>
<script type="text/javascript">
var activeElemId;
function activateItem(elemId) {
document.getElementById(elemId).className="activeElem";
if(null!=activeElemId) {
document.getElementById(activeElemId).className="desactiveElem";
}
activeElemId=elemId;
}
</script>
<li id="aaa"><a href="#" onclick="javascript:activateItem('aaa');">AAA</a>
<li id="bbb"><a href="#" onClick="javascript:activateItem('bbb');">BBB</a>
<li id="ccc"><a href="#" onClick="javascript:activateItem('ccc');">CCC</a>
The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.
$(document).ready(){
$('#collapseSix').collapse("hide");
}
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
If you want to use Graph API to get current user ID then just send a request to:
https://graph.facebook.com/me?access_token=...
You answered your own question---unsrt
is to be used when you want references to ne listed in the order of appeareance.
But you might also want to have a look at natbib, an extremely flexible citation package. I can not imagine living without it.
Use defaultdict:
from collections import defaultdict
urls = defaultdict(int)
for url in list_of_urls:
urls[url] += 1
The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine.
This is one of those situations where "If you have to ask, you're probably doing something wrong."
Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:
The classes under java.io
resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.
Eclipse sets the working directory to the top-level project folder.
The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).
In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.
def main():
print("main code")
def meth1():
print("meth1")
meth1()
if __name__ == "__main__":main() ## with if
Output -
meth1
main code
More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html
A module's __name__
Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.
Using a module's __name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
Output -
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
How It Works -
Every Python module has it's __name__
defined and if this is __main__
, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
To get a random 3-digit number:
from random import randint
randint(100, 999) # randint is inclusive at both ends
(assuming you really meant three digits, rather than "up to three digits".)
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.
jsfiddle.net/5XzeE/4/
The below code, when added to the .htaccess
file, will automatically redirect any traffic destined for http: to https:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</IfModule>
If your project is in Laravel
add the two lines
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
just below RewriteEngine On
. Finally your .htaccess
file will look like the following.
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
func get_Contact_list()
{
ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading..")
let cont_nunber = contact_array as NSArray
print(cont_nunber)
let token = UserDefaults.standard.string(forKey: "vAuthToken")!
let apiToken = "Bearer \(token)"
let headers = [
"Vauthtoken": apiToken,
"content-type": "application/json"
]
let myArray: [Any] = cont_nunber as! [Any]
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: myArray, options: .prettyPrinted)
// var jsonString: String = nil
var jsonString = String()
if let aData = jsonData {
jsonString = String(data: aData, encoding: .utf8)!
}
let url1 = "URL"
var request = URLRequest(url: URL(string: url1)!)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = jsonData as! Data
// let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
ApiUtillity.sharedInstance.dismissSVProgressHUD()
return
}
print("response = \(String(describing: response))")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
let json = self.convertStringToDictionary(text: responseString!)! as NSDictionary
print(json)
let status = json.value(forKey: "status") as! Int
if status == 200
{
let array = (json.value(forKey: "data") as! NSArray).mutableCopy() as! NSMutableArray
}
else if status == 401
{
ApiUtillity.sharedInstance.dismissSVProgressHUD()
}
else
{
ApiUtillity.sharedInstance.dismissSVProgressHUD()
}
}
task.resume()
}
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
} catch {
print("Something went wrong")
}
}
return nil
}
IIS 6.0 and previous versions :
ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.
This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.
Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.
The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests
What's a SCRIPT MAP ?
Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed
A good example can be seen here
IIS 7 and above
IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.
IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )
What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules
and ASP.NET modules
providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.
IHttpModule
) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.IHttpHandler
)For me the following worked:
if (receiver.isOrderedBroadcast()) {
requireContext().unregisterReceiver(receiver);
}
Section 3.13 of the Unicode standard defines algorithms for caseless matching.
X.casefold() == Y.casefold()
in Python 3 implements the "default caseless matching" (D144).
Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('Ć„'
vs. 'aĀ°'
). D145 introduces "canonical caseless matching":
import unicodedata
def NFD(text):
return unicodedata.normalize('NFD', text)
def canonical_caseless(text):
return NFD(NFD(text).casefold())
NFD()
is called twice for very infrequent edge cases involving U+0345 character.
Example:
>>> 'Ć„'.casefold() == 'aĀ°'.casefold()
False
>>> canonical_caseless('Ć„') == canonical_caseless('aĀ°')
True
There are also compatibility caseless matching (D146) for cases such as '?'
(U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.
When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.
The following should work for you:
[\n\r].*Object Name:\s*([^\n\r]*)
Your desired match will be in capture group 1.
[\n\r][ \t]*Object Name:[ \t]*([^\n\r]*)
Would be similar but not allow for things such as " blah Object Name: blah" and also make sure that not to capture the next line if there is no actual content after "Object Name:"
I implemented access using the following
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
now I can just do
print(D.x)
to get 1
as result.
You can also use self.name
in case you wanted to print x
instead of 1
.
You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).
The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.
ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);
p.descendants().forEach(ph -> {
ph.destroy();
});
p.destroy();
Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
Directive using formaters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var moment = $window.moment;
var dateFormat = attrs.moDateInput;
attrs.$observe('moDateInput', function (newValue) {
if (dateFormat == newValue || !ctrl.$modelValue) return;
dateFormat = newValue;
ctrl.$modelValue = new Date(ctrl.$setViewValue);
});
ctrl.$formatters.unshift(function (modelValue) {
if (!dateFormat || !modelValue) return "";
var retVal = moment(modelValue).format(dateFormat);
return retVal;
});
ctrl.$parsers.unshift(function (viewValue) {
var date = moment(viewValue, dateFormat);
return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
});
}
};
});
This should do it for you - all your files will end up called Part1-Part500.
#!/bin/bash
FILENAME=10000.csv
HDR=$(head -1 $FILENAME) # Pick up CSV header line to apply to each file
split -l 20 $FILENAME xyz # Split the file into chunks of 20 lines each
n=1
for f in xyz* # Go through all newly created chunks
do
echo $HDR > Part${n} # Write out header to new file called "Part(n)"
cat $f >> Part${n} # Add in the 20 lines from the "split" command
rm $f # Remove temporary file
((n++)) # Increment name of output part
done
I use Marked 2 on Mac OS X. It supports the following syntax for including other files.
<<[chapters/chapter1.md]
<<[chapters/chapter2.md]
<<[chapters/chapter3.md]
<<[chapters/chapter4.md]
Sadly, you can't feed that to pandoc as it doesn't understand the syntax. However, writing a script to strip the syntax out to construct a pandoc command line is easy enough.
Even if this is an old post with an already accepted answer, I post my alternative answer because it works well for the present issue and it seems nobody mentioned this method.
With the java.net.URI library:
URI uri = URI.create(URLString);
And if you want a URL-formatted string corresponding to it:
String validURLString = uri.toASCIIString();
Unlike many other methods (e.g. java.net.URLEncoder) this one replaces only unsafe ASCII characters (like Ƨ
, Ć©
...).
In the above example, if URLString
is the following String
:
"http://www.domain.com/faƧon+word"
the resulting validURLString
will be:
"http://www.domain.com/fa%C3%A7on+word"
which is a well-formatted URL.
If you're using numpy for your arrays, you can also use
x = x[numpy.logical_not(numpy.isnan(x))]
Equivalently
x = x[~numpy.isnan(x)]
[Thanks to chbrown for the added shorthand]
Explanation
The inner function, numpy.isnan
returns a boolean/logical array which has the value True
everywhere that x
is not-a-number. As we want the opposite, we use the logical-not operator, ~
to get an array with True
s everywhere that x
is a valid number.
Lastly we use this logical array to index into the original array x
, to retrieve just the non-NaN values.
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??
This depends strongly on the crypto algorithm you use:
There is one more way to solve this problem. 1)Go to Project Explorer. Go to the target folder of your project, right-click and delete the target folder. 2)Right-click on your project, select run as Maven Build. 3)After you get Build Success on the console; right click on the project folder and select refresh. After performing the above steps, try to run your project.Your problem should be solved now.
Using inline styles:
<input type="text" style="text-align: right"/>
or, put it in a style sheet, like so:
<style>
.rightJustified {
text-align: right;
}
</style>
and reference the class:
<input type="text" class="rightJustified"/>
void TOH(int n, int a, int b){
/*Assuming a as source stack numbered as 1, b as spare stack numbered as 2 and c as target stack numbered as 3. So once we know values of a and b, we can determine c as there sum is a constant number (3+2+1=)6.
*/
int c = 6-a-b;
if(n==1){
cout<<"Move from "<<a<<" to "<<b<<"\n";
}
else{
// Move n-1 disks from 1st to 2nd stack. As we are not allowed to move more than one disks at a time, we do it by recursion. Breaking the problem into a simpler problem.
TOH(n-1, a, c);
// Move the last alone disk from 1st to 3rd stack.
TOH(1, a, b);
// Put n-1 disks from 2nd to 3rd stack. As we are not allowed to move more than one disks at a time, we do it by recursion. Breaking the problem into a simpler problem.
TOH(n-1, c, b);
}
}
int main() {
TOH(2, 1, 3);
cout<<"FINISHED \n";
TOH(3, 1, 3);
cout<<"FINISHED \n";
TOH(4, 1, 3);
return 0;
}
Something like this:
for (/* stuff */)
{
var x = '<option value="' + col + '" '
+ (col === 'screwdriver' ? 'selected' : '')
+ '>Very roomy</option>';
// snip...
}
A better way, use getParent()
from File
Class..
String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path
File file = new File(a);
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
http://developer.android.com/reference/java/io/File.html#getParent%28%29
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
Have you considered using:
where('date', '<', '2014-08-11')
You should avoid using the DATE()
function on indexed columns in MySQL, as this prevents the engine from using the index.
UPDATE
As there seems to be some disagreement about the importance of DATE()
and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS
.
If the object you are trying to cast from or to has properties that are also user-defined classes, and you don't want to go through reflection, you can use this.
<?php
declare(strict_types=1);
namespace Your\Namespace\Here
{
use Zend\Logger; // or your logging mechanism of choice
final class OopFunctions
{
/**
* @param object $from
* @param object $to
* @param Logger $logger
*
* @return object
*/
static function Cast($from, $to, $logger)
{
$logger->debug($from);
$fromSerialized = serialize($from);
$fromName = get_class($from);
$toName = get_class($to);
$toSerialized = str_replace($fromName, $toName, $fromSerialized);
$toSerialized = preg_replace("/O:\d*:\"([^\"]*)/", "O:" . strlen($toName) . ":\"$1", $toSerialized);
$toSerialized = preg_replace_callback(
"/s:\d*:\"[^\"]*\"/",
function ($matches)
{
$arr = explode(":", $matches[0]);
$arr[1] = mb_strlen($arr[2]) - 2;
return implode(":", $arr);
},
$toSerialized
);
$to = unserialize($toSerialized);
$logger->debug($to);
return $to;
}
}
}
$(this.parentNode).addClass('newClass');
try changing this part,
<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter
for this
<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up for newsletter
I did the CSS way with my install of Bootstrap 3.0.0, since I am not that familiar with LESS. Here is the code that I added to my custom css file (which I load after bootstrap.css) which allowed me to control so the menu was always working like an accordion
.
Note: I wrapped my whole navbar
inside a div with the class sidebar
to separate out the behavior I wanted so it did not affect other navbars on my site, like the main menu. Adjust along your needs, hope it is of help.
/* Sidebar Menu Fix */
.sidebar .navbar-nav {
margin: 7.5px -15px;
}
.sidebar .navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
.sidebar .navbar-collapse {
max-height: 500px;
}
.sidebar .navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
box-shadow: none;
}
.sidebar .dropdown-menu > li > a {
color: #777777;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333333;
background-color: transparent;
}
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.sidebar .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555555;
background-color: #e7e7e7;
}
.sidebar .navbar-nav {
float: none;
}
.sidebar .navbar-nav > li {
float: none;
}
Additional note: I also added a change to the toggle of the main menu navbar
(since the code above on my site is used for a "submenu" on the side.
I changed:
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
into:
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-topmenu">
And then also adjusted:
<div class="navbar-collapse collapse navbar-collapse">
into:
<div class="navbar-collapse collapse navbar-collapse-topmenu">
If you will only have one navbar
I guess you will not need to worry about this, but it helped me in my case.
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
Just need config file under ~/.ssh directory
ref : https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html
add bellow configuration in config file
Host bitbucket.org
IdentityFile ~/.ssh/<privatekeyfile>
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
If you are creating a new MySQL table, you can specify the charset of all columns upon creation, and that fixed the issue for me.
CREATE TABLE tablename (
<list-of-columns>
)
CHARSET SET utf8mb4 COLLATE utf8mb4_unicode_ci;
You can read more details: https://dev.mysql.com/doc/refman/8.0/en/charset-column.html
There is a simple way to solve this: you can execute php file by cron every 1 minute, and inside php executable file make "if" statement to execute when time "now" like this
<?/** suppose we have 1 hour and 1 minute inteval 01:01 */
$interval_source = "01:01";
$time_now = strtotime( "now" ) / 60;
$interval = substr($interval_source,0,2) * 60 + substr($interval_source,3,2);
if( $time_now % $interval == 0){
/** do cronjob */
}
One solution for this, not requiring any JavaScript, is simply to create a single page in which the multiple pages are simply regular content that is separated by a lot of white space. They can be wrapped into div
containers, and an inline style sheet can endow them with the margin:
<style>
.subpage { margin-bottom: 2048px; }
</style>
... main page ...
<div class="subpage">
<!-- first one is empty on purpose: just a place holder for margin;
alternative is to use this for the main part of the page also! -->
</div>
<div class="subpage">
</div>
<div class="subpage">
</div>
You get the picture. Each "page" is just a section followed by a whopping amount of vertical space so that the next one doesn't show.
I'm using this trick to add "disambiguation navigation links" into a large document (more than 430 pages long in its letter-sized PDF form), which I would greatly prefer to keep as a single .html
file. I emphasize that this is not a web site, but a document.
When the user clicks on a key word hyperlink in the document for which there are multiple possible topics associated with word, the user is taken a small navigation menu presenting several topic choices. This menu appears at top of what looks like a blank browser window, and so effectively looks like a page.
The only clue that the menu isn't a separate page is the state of the browser's vertical scroll bar, which is largely irrelevant in this navigation use case. If the user notices that, and starts scrolling around, the whole ruse is revealed, at which point the user will smile and appreciate not having been required to unpack a .zip
file full of little pages and go hunting for the index.html
.
It's actually possible to embed a HTML page within HTML. It can be done using the somewhat obscure data:
URL in the href
attribute. As a simple test, try sticking this somewhere in a HTML page:
<a href="data:text/html;charset=utf-8,<h3>FOO</h3>">blah</a>
In Firefox, I get a "blah" hyperlink, which navigates to a page showing the FOO heading. (Note that I don't have a fully formed HTML page here, just a HTML snippet; it's just a hello-world example).
The downside of this technique is that the entire target page is in the URL, which is stuffed into the browser's address input box.
If it is large, it could run into some issues, perhaps browser-specific; I don't have much experience with it.
Another disadvantage is that the entire HTML has to be properly escaped so that it can appear as the argument of the href
attribute. Obviously, it cannot contain a plain double quote character anywhere.
A third disadvantage is that each such link has to replicates the data:
material, since it isn't semantically a link at all, but a copy and paste embedding. It's not an attractive solution if the page-to-be-embeddded is large, and there are to be numerous links to it.
Variables in PHP are cast in three different type:
Public : values of this variable types are available in all scope and call on execution of you code.
declare as: public $examTimeTable;
Private: Values of this type of variable are only available on only to the class it belongs to.
private $classRoomComputers;
Protected: Values of this class only and only available when Access been granted in a form of inheritance or their child class. generally used ::
to grant access by parent class
protected $familyWealth;
I struggled with all the answers here, starting with Pascal's solution, which is getting harder with the Java compiler not binding against rt.jar
by default any more (and using internal classes makes it specific to that runtime implementation).
The answer from edubriguenti brought me close. The way the handler is hooked up in the final bit of code didn't work for me, though - it was never called.
I ended up using a variation of his handler class, but wired it into the javax.xml.ws.Service
instance like this:
Service service = Service.create(url, qname);
service.setHandlerResolver(
portInfo -> Collections.singletonList(new SOAPHeaderHandler(handlerArgs))
);
If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :
date("Y-m-d H:i:s", $myTimestamp)
//create a folder in server (~/Uploads)
//to upload
File.Copy(@"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));
//to download
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
Response.WriteFile("~/Uploads/CORREO.txt");
Response.End();
Why complicate?
std::string removeSpaces(std::string x){
if(x[0] == ' ') { x.erase(0, 1); return removeSpaces(x); }
if(x[x.length() - 1] == ' ') { x.erase(x.length() - 1, x.length()); return removeSpaces(x); }
else return x;
}
This works even if boost was to fail, no regex, no weird stuff nor libraries.
EDIT: Fix for M.M.'s comment.
check $this->upload->initialize($config); this works fine for me
$new_image_name = "imgName".time() . str_replace(str_split(' ()\\/,:*?"<>|'), '',
$_FILES['userfile']['name']);
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['file_name'] = $new_image_name;
$config['max_size'] = '0';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
$config['file_name'] = url_title("imgsclogo");
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
$this->upload->do_upload();
$data = $this->upload->data();
}
Use math.ceil
to round up:
>>> import math
>>> math.ceil(5.4)
6.0
NOTE: The input should be float.
If you need an integer, call int
to convert it:
>>> int(math.ceil(5.4))
6
BTW, use math.floor
to round down and round
to round to nearest integer.
>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)
Go to the query designer window, switch to SQL mode, and try this:
Update Table Set MyField = 0
Where MyField Is Null;
another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:
UserZone = User.zones.through
# for a single zone
users_in_zone = User.objects.filter(
id__in=UserZone.objects.filter(zone=zone1).values('user'))
# for multiple zones
users_in_zones = User.objects.filter(
id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))
it would be nice if it didn't need the .values('user')
specified, but Django (version 3.0.7) seems to need it.
the above code will end up generating SQL that looks something like:
SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))
which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned
You can configure HttpClient
to automatically pass credentials like this:
var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
You can certainly do something like
SQL> ed
Wrote file afiedt.buf
1 begin
2 for d in (select * from dept)
3 loop
4 for e in (select * from emp where deptno=d.deptno)
5 loop
6 dbms_output.put_line( 'Employee ' || e.ename ||
7 ' in department ' || d.dname );
8 end loop;
9 end loop;
10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
Or something equivalent using explicit cursors.
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor dept_cur
3 is select *
4 from dept;
5 d dept_cur%rowtype;
6 cursor emp_cur( p_deptno IN dept.deptno%type )
7 is select *
8 from emp
9 where deptno = p_deptno;
10 e emp_cur%rowtype;
11 begin
12 open dept_cur;
13 loop
14 fetch dept_cur into d;
15 exit when dept_cur%notfound;
16 open emp_cur( d.deptno );
17 loop
18 fetch emp_cur into e;
19 exit when emp_cur%notfound;
20 dbms_output.put_line( 'Employee ' || e.ename ||
21 ' in department ' || d.dname );
22 end loop;
23 close emp_cur;
24 end loop;
25 close dept_cur;
26* end;
27 /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of
FOR x IN (SELECT *
FROM all_users,
org
WHERE length(all_users.username) = 3
AND all_users.username = org.username )
LOOP
<<do something>>
END LOOP;
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
ā starts with "tocolor-".
[class*=" tocolor-"]
ā contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
for who needs complete example code. Right+Left added
var keyPressed = {};
document.addEventListener('keydown', function(e) {
keyPressed[e.key + e.location] = true;
if(keyPressed.Shift1 == true && keyPressed.Control1 == true){
// Left shift+CONTROL pressed!
keyPressed = {}; // reset key map
}
if(keyPressed.Shift2 == true && keyPressed.Control2 == true){
// Right shift+CONTROL pressed!
keyPressed = {};
}
}, false);
document.addEventListener('keyup', function(e) {
keyPressed[e.key + e.location] = false;
keyPressed = {};
}, false);
If you want to extract the hours, minutes and seconds, try this:
String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);
You can use reflection to find all the get
methods in your DAO objects and call the equivalent set
method in the DTO. This will only work if all such methods exist. It should be easy to find example code for this.
Use sed's substitution: sed 's/"//g'
s/X/Y/
replaces X with Y.
g
means all occurrences should be replaced, not just the first one.
The only thing that helped is to use a file of JSON instead of json body text. Based on How to send file contents as body entity using cURL
Seems you can just use the prop method on the angular element:
var top = $el.prop('offsetTop');
Works for me. Does anyone know any downside to this?
If you are on HTTPS do this-
git remote add origin URL_TO_YOUR_REPO
Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose
.feature_desc {
display: block;
}
.feature_desc:before {
content: "";
display: block;
}
might give you want you want to achieve without the <br/>
element. Though it would help to see your CSS applied to these elements.
NOTE. The example above doesn't work in IE7 though.
This Swift 3.0 example returns the current device model as an enum
constant (to avoid direct comparisons to string literals). The enum's raw value is a String
containing the human-readable iOS device name. Since it is Swift, the list of recognized devices only includes models recent enough to support iOS releases that include Swift. The following usage example utilizes the implementation at the end of this answer:
switch UIDevice().type {
case .iPhone5:
print("No TouchID sensor")
case .iPhone5S:
fallthrough
case .iPhone6:
fallthrough
case .iPhone6plus:
fallthrough
case .iPad_Pro9_7:
fallthrough
case .iPad_Pro12_9:
fallthrough
case .iPhone7:
fallthrough
case .iPhone7plus:
print("Put your thumb on the " +
UIDevice().type.rawValue + " TouchID sensor")
case .unrecognized:
print("Device model unrecognized");
default:
print(UIDevice().type.rawValue + " not supported by this app");
}
Your app should be kept up-to-date for new device releases and also when Apple adds new models for the same device family. For example, iPhone3,1 iPhone3,2 iPhone3,4 are all "iPhone 4". Avoid writing code that doesn't account for new models, so your algorithms don't unexpectedly fail to configure or respond to a new device. You can refer to this maintained list of iOS Device Model #'s to update your app at strategic times.
iOS includes device-independent interfaces to detect hardware capabilities and parameters such as screen size. The generalized interfaces Apple provides are usually the safest, best supported mechanisms to dynamically adapt an app's behavior to different hardware. Nevertheless, the following code can be useful for prototyping, debugging, testing, or any time code needs to target a specific device family. This technique can also be useful to describe the current device by its common/publicly recognized name.
Swift 3
// 1. Declare outside class definition (or in its own file).
// 2. UIKit must be included in file where this code is added.
// 3. Extends UIDevice class, thus is available anywhere in app.
//
// Usage example:
//
// if UIDevice().type == .simulator {
// print("You're running on the simulator... boring!")
// } else {
// print("Wow! Running on a \(UIDevice().type.rawValue)")
// }
import UIKit
public enum Model : String {
case simulator = "simulator/sandbox",
iPod1 = "iPod 1",
iPod2 = "iPod 2",
iPod3 = "iPod 3",
iPod4 = "iPod 4",
iPod5 = "iPod 5",
iPad2 = "iPad 2",
iPad3 = "iPad 3",
iPad4 = "iPad 4",
iPhone4 = "iPhone 4",
iPhone4S = "iPhone 4S",
iPhone5 = "iPhone 5",
iPhone5S = "iPhone 5S",
iPhone5C = "iPhone 5C",
iPadMini1 = "iPad Mini 1",
iPadMini2 = "iPad Mini 2",
iPadMini3 = "iPad Mini 3",
iPadAir1 = "iPad Air 1",
iPadAir2 = "iPad Air 2",
iPadPro9_7 = "iPad Pro 9.7\"",
iPadPro9_7_cell = "iPad Pro 9.7\" cellular",
iPadPro10_5 = "iPad Pro 10.5\"",
iPadPro10_5_cell = "iPad Pro 10.5\" cellular",
iPadPro12_9 = "iPad Pro 12.9\"",
iPadPro12_9_cell = "iPad Pro 12.9\" cellular",
iPhone6 = "iPhone 6",
iPhone6plus = "iPhone 6 Plus",
iPhone6S = "iPhone 6S",
iPhone6Splus = "iPhone 6S Plus",
iPhoneSE = "iPhone SE",
iPhone7 = "iPhone 7",
iPhone7plus = "iPhone 7 Plus",
iPhone8 = "iPhone 8",
iPhone8plus = "iPhone 8 Plus",
iPhoneX = "iPhone X",
iPhoneXS = "iPhone XS",
iPhoneXSmax = "iPhone XS Max",
iPhoneXR = "iPhone XR",
iPhone11 = "iPhone 11",
iPhone11Pro = "iPhone 11 Pro",
iPhone11ProMax = "iPhone 11 Pro Max",
unrecognized = "?unrecognized?"
}
public extension UIDevice {
public var type: Model {
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: 1) {
ptr in String.init(validatingUTF8: ptr)
}
}
var modelMap : [ String : Model ] = [
"i386" : .simulator,
"x86_64" : .simulator,
"iPod1,1" : .iPod1,
"iPod2,1" : .iPod2,
"iPod3,1" : .iPod3,
"iPod4,1" : .iPod4,
"iPod5,1" : .iPod5,
"iPad2,1" : .iPad2,
"iPad2,2" : .iPad2,
"iPad2,3" : .iPad2,
"iPad2,4" : .iPad2,
"iPad2,5" : .iPadMini1,
"iPad2,6" : .iPadMini1,
"iPad2,7" : .iPadMini1,
"iPhone3,1" : .iPhone4,
"iPhone3,2" : .iPhone4,
"iPhone3,3" : .iPhone4,
"iPhone4,1" : .iPhone4S,
"iPhone5,1" : .iPhone5,
"iPhone5,2" : .iPhone5,
"iPhone5,3" : .iPhone5C,
"iPhone5,4" : .iPhone5C,
"iPad3,1" : .iPad3,
"iPad3,2" : .iPad3,
"iPad3,3" : .iPad3,
"iPad3,4" : .iPad4,
"iPad3,5" : .iPad4,
"iPad3,6" : .iPad4,
"iPhone6,1" : .iPhone5S,
"iPhone6,2" : .iPhone5S,
"iPad4,1" : .iPadAir1,
"iPad4,2" : .iPadAir2,
"iPad4,4" : .iPadMini2,
"iPad4,5" : .iPadMini2,
"iPad4,6" : .iPadMini2,
"iPad4,7" : .iPadMini3,
"iPad4,8" : .iPadMini3,
"iPad4,9" : .iPadMini3,
"iPad6,3" : .iPadPro9_7,
"iPad6,11" : .iPadPro9_7,
"iPad6,4" : .iPadPro9_7_cell,
"iPad6,12" : .iPadPro9_7_cell,
"iPad6,7" : .iPadPro12_9,
"iPad6,8" : .iPadPro12_9_cell,
"iPad7,3" : .iPadPro10_5,
"iPad7,4" : .iPadPro10_5_cell,
"iPhone7,1" : .iPhone6plus,
"iPhone7,2" : .iPhone6,
"iPhone8,1" : .iPhone6S,
"iPhone8,2" : .iPhone6Splus,
"iPhone8,4" : .iPhoneSE,
"iPhone9,1" : .iPhone7,
"iPhone9,2" : .iPhone7plus,
"iPhone9,3" : .iPhone7,
"iPhone9,4" : .iPhone7plus,
"iPhone10,1" : .iPhone8,
"iPhone10,2" : .iPhone8plus,
"iPhone10,3" : .iPhoneX,
"iPhone10,6" : .iPhoneX,
"iPhone11,2" : .iPhoneXS,
"iPhone11,4" : .iPhoneXSmax,
"iPhone11,6" : .iPhoneXSmax,
"iPhone11,8" : .iPhoneXR,
"iPhone12,1" : .iPhone11,
"iPhone12,3" : .iPhone11Pro,
"iPhone12,5" : .iPhone11ProMax
]
if let model = modelMap[String.init(validatingUTF8: modelCode!)!] {
return model
}
return Model.unrecognized
}
}
If the Data-set size is less the 25mb, The easiest way to upload a CSV file is from your GitHub repository.
Example:
import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
/start
. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.telegram_chat_id
. If yes, use the sendMessage
method in the Bot API to send them a message in Telegram.Just to clarify, you can't do location.split('#')
, location
is an object, not a string. But you can do location.href.split('#');
because location.href
is a string.
If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good:
seq 1 $END | xargs -I {} echo {}
React Native .toUpperCase() function works fine in a string but if you used the numbers
or other non-string data types
, it doesn't work. The error
will have occurred.
Below Two are string properties:
<Text>{props.complexity.toUpperCase()}</Text>
<Text>{props.affordability.toUpperCase()}</Text>
For cygwin64 or installations without chere you can use the following command in a registry entry (assuming windows due to your path, also assuming cygwin installation directory is c:\cygwin64)
C:\cygwin64\bin\mintty.exe /bin/sh -lc 'cd "`cygpath "%V"`"; bash'
Works on Windows 7 and 8 Registry file available for download here: http://tomkay.me/blog/Cygwin64---Open-Here-18
Windows Registry Editor Version 5.00
; Open cygwin to folder
; http://tomkay.me - Tom Kay
[HKEY_CLASSES_ROOT\Folder\shell\open_cygwin]
@="Open Cygwin Here"
[HKEY_CLASSES_ROOT\Folder\shell\open_cygwin\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; bash'"
[HKEY_CLASSES_ROOT\Directory\Background\shell\open_cygwin]
@="Open Cygwin Here"
[HKEY_CLASSES_ROOT\Directory\Background\shell\open_cygwin\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; bash'"
there is really a problem in 1.8.6. and it's ok after this edition
in 1.8.6,you can add this:
requre 'jcode'
Well, you can write a loop:
public static void replaceAll(StringBuilder builder, String from, String to)
{
int index = builder.indexOf(from);
while (index != -1)
{
builder.replace(index, index + from.length(), to);
index += to.length(); // Move to the end of the replacement
index = builder.indexOf(from, index);
}
}
Note that in some cases it may be faster to use lastIndexOf
, working from the back. I suspect that's the case if you're replacing a long string with a short one - so when you get to the start, any replacements have less to copy. Anyway, this should give you a starting point.
This Worked for me ! For Angular 2 , Call child component method in parent component
Parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child';
@Component({
selector: 'parent-app',
template: `<child-cmp></child-cmp>`
})
export class parentComponent implements OnInit{
@ViewChild(ChildComponent ) child: ChildComponent ;
ngOnInit() {
this.child.ChildTestCmp(); }
}
Child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-cmp',
template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
test: string;
ChildTestCmp()
{
this.test = "I am child component!";
}
}
When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance
@Html.LabelFor
, @Html.TextBoxFor
, etc@Html.EditorFor
, as you can assign specific behavior och looks in a editor viewTo adjust the width, you could wrap your TextField
with a Container
widget, like so:
Container(
width: 100.0,
child: TextField()
)
I'm not really sure what you're after when it comes to the height of the TextField
but you could definitely have a look at the TextStyle
widget, with which you can manipulate the fontSize
and/or height
Container(
width: 100.0,
child: TextField(
style: TextStyle(
fontSize: 40.0,
height: 2.0,
color: Colors.black
)
)
)
Bear in mind that the height
in the TextStyle
is a multiplier of the font size, as per comments on the property itself:
The height of this text span, as a multiple of the font size.
When [height] is null or omitted, the line height will be determined by the font's metrics directly, which may differ from the fontSize. When [height] is non-null, the line height of the span of text will be a multiple of [fontSize] and be exactly
fontSize * height
logical pixels tall.
Last but not least, you might want to have a look at the decoration
property of you TextField
, which gives you a lot of possibilities
EDIT: How to change the inner padding/margin of the TextField
You could play around with the InputDecoration
and the decoration
property of the TextField
. For instance, you could do something like this:
TextField(
decoration: const InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 40.0),
)
)
Use the parentesis syntax of Razor:
@(Model.address + " " + Model.city)
or
@(String.Format("{0} {1}", Model.address, Model.city))
Update: With C# 6 you can also use the $-Notation (officially interpolated strings):
@($"{Model.address} {Model.city}")
Safe and memory-saving:
with open("out1.txt", "w") as fw, open("in.txt","r") as fr:
fw.writelines(l for l in fr if "tests/file/myword" in l)
It doesn't create temporary lists (what readline
and []
would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with
blocks ensure that the files are closed on exit.
This will depend on the device you're using. If you're using a pdf device, you can do this:
pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )
You can then divide up the space in the pdf using the mfrow parameter like this:
par( mfrow = c(2,2) )
That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().
Other devices that might be useful include:
There's a list of all of the devices here.
there you go
$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));
echo $tomorrow;
this will output
04-16-2013
This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.
var fullEntries = dbContext.tbl_EntryPoint
.Join(
dbContext.tbl_Entry,
entryPoint => entryPoint.EID,
entry => entry.EID,
(entryPoint, entry) => new { entryPoint, entry }
)
.Join(
dbContext.tbl_Title,
combinedEntry => combinedEntry.entry.TID,
title => title.TID,
(combinedEntry, title) => new
{
UID = combinedEntry.entry.OwnerUID,
TID = combinedEntry.entry.TID,
EID = combinedEntry.entryPoint.EID,
Title = title.Title
}
)
.Where(fullEntry => fullEntry.UID == user.UID)
.Take(10);
Until host.docker.internal
is working for every platform, you can use my container acting as a NAT gateway without any manual setup:
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:
import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array
res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])
which can be extended to D dimensions.
The results are:
Prediction:
[[1 2]
[2 0]
[2 0]
[1 2]
[1 2]]
Target:
[[0 1]
[1 0]
[2 0]
[0 0]
[2 1]]
Count of correct prediction for D=1: 1
Count of correct prediction for D=2: 2
You'll have to make this separate try
blocks:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
This assumes you want to run code c
only if code b
failed.
If you need to run code c
regardless, you need to put the try
blocks one after the other:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
pass
try:
code c
except ExplicitException:
pass
try:
code d
except ExplicitException:
pass
I'm using except ExplicitException
here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError
, KeyboardInterrupt
and SystemExit
as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.
InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.ShowSoftInput(_enterPin.FindFocus(), 0);
*This is for Android.xamarin and FindFocus()-it searches for the view in hierarchy rooted at this view that currently has focus,as i have _enterPin.RequestFocus() before the above code thus it shows keyboard for _enterPin EditText *
class Student{
int rollno;
String name;
void m1(int x,int y){
System.out.println("add is" +(x+y));
}
private void m3(String name){
this.name=name;
System.out.println("danger yappa:"+name);
}
void m4(){
System.out.println("This is m4");
}
}
import java.lang.reflect.Method;
public class StudentTest{
public static void main(String[] args){
try{
Class cls=Student.class;
Student s=(Student)cls.newInstance();
String x="kichha";
Method mm3=cls.getDeclaredMethod("m3",String.class);
mm3.setAccessible(true);
mm3.invoke(s,x);
Method mm1=cls.getDeclaredMethod("m1",int.class,int.class);
mm1.invoke(s,10,20);
}
catch(Exception e){
e.printStackTrace();
}
}
}
i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.
the code is below:-
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
<input type="submit" value="SAVE">
</form>
</body>
</html>
You could try using scipy.ndimage.convolve
it allows convolution of multidimensional images. here is the docs
A plain JavaScript solution, assuming jsonObj
already contains JSON:
Loop over it looking for the matching Id, set the corresponding Username, and break
from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
You can simply get HQ youtube thumbnails..
Possibly browser returns String representation of some integer value? Actually int can't be null. May be you could check for null, if value is not null, then transform String representation to int.
Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).
function loadCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}
Usage as so:
loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
function() {
alert("All resources loaded");
}, function() {
alert("One or more resources failed to load");
});
Here is another function that will load both CSS and javascript files:
function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
if(url.endsWith(".css")) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
} else {
return $.getScript(url);
}
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}
Try this one ,
var height;
$(document).ready(function(){
$('#first').css('height','auto');
height = $('#first').height();
$('#first').css('height','200px');
})
$("div:first").click(function(){
$("#first").animate({
height: height
}, 1000 );
});
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
return Observable.fromEventPattern(
handler => iframe.addEventListener('load', handler, true),
handler => iframe.removeEventListener('load', handler)
);
According to the RFC that introduced the operator, $a <=> $b
evaluates to:
$a == $b
$a < $b
$a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b
will return
an integer less than, equal to, or greater than zero when
$a
is respectively less than, equal to, or greater than$b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort
(and the similar uasort
and uksort
).
usort
takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
In my first answer the logic is shown for those who want to go with the logic only.
I think I was not able to make clear to @chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.
BluetoothDemo.java
public class BluetoothDemo extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if(removeBonding)
{
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed"+removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for(int i = 0; i<arrayListBluetoothDevices.size();i++)
{
if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
{
flag = false;
}
}
if(flag == true)
{
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}
Here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="On"/>
<Button
android:id="@+id/buttonDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Make Discoverable"/>
<Button
android:id="@+id/buttonSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<Button
android:id="@+id/buttonOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Off"/>
<ListView
android:id="@+id/listViewPaired"
android:layout_width="match_parent"
android:layout_height="120dp">
</ListView>
<ListView
android:id="@+id/listViewDetected"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I know, that's a very old question.
If you want use a color value, you can also use the short version of that with #ARGB
. Where A
is the value for the alpha channel.
In case of a white color there are the following transparency values:
#FFFF - 0%
#EFFF - 6,7%
#DFFF - 13,3%
#CFFF - 20,0%
#BFFF - 26,7%
#AFFF - 33,3%
#9FFF - 40,0%
#FFF8 - 46,7%
#7FFF - 53,3%
#6FFF - 60,0%
#5FFF - 66,7%
#4FFF - 73,3%
#3FFF - 80,0%
#2FFF - 86,7%
#1FFF - 93,3%
#0FFF - 100,0%
So you can for TextView
add the following line for 20% transparency:
<TextView
android:background="#CFFF"
... />
One way is to just leave merged feature branches open (and inactive):
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
feature-x 41:...
(2 branches)
$ hg branches -a
default 43:...
(1 branch)
Another way is to close a feature branch before merging using an extra commit:
$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
(1 branch)
The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch
, but one should know in advance which commit will be the last one.
Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches
and hg heads
anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.
Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:
Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf()
.
I think there is another way to do it, though. You can try ceil()
and floor()
to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil()
and floor()
only work on double
s though.
EDIT: Also, for floats, you can use truncf()
to truncate floats. The same +0.5 trick should work to do accurate rounding.
Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".
People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.
This solution applies in some cases - if possible:
If the iframe content page uses a subdomain of the page containing the iframe, the cookie is no longer blocked.
$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
foreach($val as $vals){
if ($key=='Youtube'){
echo $vals
}
}
}
Key = Youtube videos all meta keys for youtube videos and value
Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.
The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.
Something like this:
function reverseGeocode(latitude,longitude){
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
var address = addresses.Placemark[0].address;
var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
do_something_with_address(address, country, countrycode, locality);
});
}
function do_something_with_address(address, country, countrycode, locality) {
if (country==="USA") {
alert("USA A-OK!"); // or whatever
}
}
If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:
function reverseGeocode(latitude,longitude, callback){
// Function contents the same as above, then
callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);
If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.
Or simply:
view.getLayoutParams().width = 400;
view.requestLayout();
You can use like
:
"12-18" -like "*-*"
Or split
for contains
:
"12-18" -split "" -contains "-"
Instead of doing all these, one can simply use ".Result" to get the result from a particular task.
eg: List list = GetListAsync().Result;
Which as per the definition => Gets the result value of this Task < TResult >
I had sort of the opposite issue as the original poster: I was getting the full path when I only wanted the filename. I used Gabriƫl's solution to get just the filename, but in the process I discovered why you get the full path on some machines and not others.
Any computer joined to domain will give you back the full path for the filename. I tried this on several different computers with consistent results. I don't have an explanation for why, but at least in my testing it was consistent.
You have already have container-selinux installed for version 3.7 check if the following docker-ce version works for you , it did for me.
sudo yum -y install docker-ce-cli.x86_64 1:19.03.5-3.el7
I check Query Log to see the exact query that was executed as prepared statement.
From the bash man page:
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
So you can do this:
echo $'hello\tworld'
The function takes the first character of a String - str.charAt(0)
- puts it at the end and then calls itself - reverse()
- on the remainder - str.substring(1)
, adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)
When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1)
- it stops calling itself recursively and just returns the String passed in.
So it runs as follows:
reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
If I remember well, some CSS properties you apply to table
are not inherited as expected. So you should indeed apply the style directly to td
,tr
and th
elements.
If you need to add styling to each column, use the <col>
element in your table.
See an example here: http://jsfiddle.net/GlauberRocha/xkuRA/2/
NB: You can't have a margin
in a td
. Use padding
instead.
If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:
var min = myData.OrderBy( cv => cv.Date1 ).First();
The above will return the entire object. If you just want the date returned:
var min = myData.Min( cv => cv.Date1 );
Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.
From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:
What about the future of LINQ to SQL?
It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor
:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}