How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…
To sum with decimal use this:
In the javascript change parseInt with parseFloat and add this line tot.toFixed(2); for this result:
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseFloat(arr[i].value))
tot += parseFloat(arr[i].value);
}
document.getElementById('total').value = tot;
tot.toFixed(2);
}
Use step=".01" min="0" type="number" in the input filed
Qty1 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="number" step=".01" min="0" name="total" id="total"/>
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*; public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];
if($symbol == '+')
{
$add = $cal1 + $cal2;
echo "Addition is:".$add;
}
else if($symbol == '-')
{
$subs = $cal1 - $cal2;
echo "Substraction is:".$subs;
}
else if($symbol == '*')
{
$mul = $cal1 * $cal2;
echo "Multiply is:".$mul;
}
else if($symbol == '/')
{
$div = $cal1 / $cal2;
echo "Division is:".$div;
}
else
{
echo "Oops ,something wrong in your code son";
}
?>
Here's how I usually do it. For example, to calculate 1717 mod 2
:
1717 / 2
. The answer is 858.52
) to get 1716
1717
) minus the number you got from the previous step (1716
) -- 1717-1716=1
.So 1717 mod 2
is 1
.
To sum this up all you have to do is multiply the numbers before the decimal point with the mod then subtract it from the original number.
Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.
When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator
that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.
So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.
Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.
You can use:
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied. I think the previous poster is correct that the Date() object always returns a GMT it's not until you go to do something with the date object that it gets converted to the local time zone.
JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage
var obj = {"nissan": "sentra", "color": "green"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
var obj = JSON.parse(localStorage.getItem('myStorage'));
Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE
was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Public Class Impersonation
Implements IDisposable
Public Enum LogonTypes
''' <summary>
''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on
''' by a terminal server, remote shell, or similar process.
''' This logon type has the additional expense of caching logon information for disconnected operations;
''' therefore, it is inappropriate for some client/server applications,
''' such as a mail server.
''' </summary>
LOGON32_LOGON_INTERACTIVE = 2
''' <summary>
''' This logon type is intended for high performance servers to authenticate plaintext passwords.
''' The LogonUser function does not cache credentials for this logon type.
''' </summary>
LOGON32_LOGON_NETWORK = 3
''' <summary>
''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without
''' their direct intervention. This type is also for higher performance servers that process many plaintext
''' authentication attempts at a time, such as mail or Web servers.
''' The LogonUser function does not cache credentials for this logon type.
''' </summary>
LOGON32_LOGON_BATCH = 4
''' <summary>
''' Indicates a service-type logon. The account provided must have the service privilege enabled.
''' </summary>
LOGON32_LOGON_SERVICE = 5
''' <summary>
''' This logon type is for GINA DLLs that log on users who will be interactively using the computer.
''' This logon type can generate a unique audit record that shows when the workstation was unlocked.
''' </summary>
LOGON32_LOGON_UNLOCK = 7
''' <summary>
''' This logon type preserves the name and password in the authentication package, which allows the server to make
''' connections to other network servers while impersonating the client. A server can accept plaintext credentials
''' from a client, call LogonUser, verify that the user can access the system across the network, and still
''' communicate with other servers.
''' NOTE: Windows NT: This value is not supported.
''' </summary>
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
''' <summary>
''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
''' The new logon session has the same local identifier but uses different credentials for other network connections.
''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
''' NOTE: Windows NT: This value is not supported.
''' </summary>
LOGON32_LOGON_NEW_CREDENTIALS = 9
End Enum
<DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
End Function
Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
If Not ok Then
Dim errorCode = Marshal.GetLastWin32Error()
Throw New ApplicationException(String.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode))
End If
WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
End Sub
Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext
Public Sub Dispose() Implements System.IDisposable.Dispose
Me.WindowsImpersonationContext.Dispose()
Me._SafeTokenHandle.Dispose()
End Sub
Public NotInheritable Class SafeTokenHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
<DllImport("kernel32.dll")> _
<ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
<SuppressUnmanagedCodeSecurity()> _
Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Public Sub New()
MyBase.New(True)
End Sub
Protected Overrides Function ReleaseHandle() As Boolean
Return CloseHandle(handle)
End Function
End Class
End Class
You need to Use with a Using
statement to contain some code to run impersonated.
I had a similar issue in Azure Data Factory with the : character.
I resolved the problem by substituting : with %3A
as shown here.
For example, I substituted
date1=2020-01-25T00:00:00.000Z
with
date1=2020-01-25T00%3A00%3A00.000Z
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)]
actually encompasses. []
is one-way binding syntax and ()
is event binding syntax. When used together - [()]
Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.
The reason you cannot use [()]
with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.
See Angular Template Syntax for more info.
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
In modern browsers it's relatively painless to style the <select>
in CSS. With appearance: none
the only tricky part is replacing the arrow (if that's what you want). Here's a solution that uses an inline data:
URI with plain-text SVG:
select {_x000D_
-moz-appearance: none;_x000D_
-webkit-appearance: none;_x000D_
appearance: none;_x000D_
_x000D_
background-repeat: no-repeat;_x000D_
background-size: 0.5em auto;_x000D_
background-position: right 0.25em center;_x000D_
padding-right: 1em;_x000D_
_x000D_
background-image: url("data:image/svg+xml;charset=utf-8, \_x000D_
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 60 40'> \_x000D_
<polygon points='0,0 60,0 30,40' style='fill:black;'/> \_x000D_
</svg>");_x000D_
}
_x000D_
<select>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
_x000D_
<select style="font-size: 2rem;">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>
_x000D_
The rest of the styling (borders, padding, colors, etc.) is fairly straightforward.
This works in all the browsers I just tried (Firefox 50, Chrome 55, Edge 38, and Safari 10). One note about Firefox is that if you want to use the #
character in the data URI (e.g. fill: #000
) you need to escape it (fill: %23000
).
If your intention is test the service without care about the rest call, I will suggest to not use any annotation in your unit test to simplify the test.
So, my suggestion is refactor your service to receive the resttemplate using injection constructor. This will facilitate the test. Example:
@Service
class SomeService {
@AutoWired
SomeService(TestTemplateObjects restTemplateObjects) {
this.restTemplateObjects = restTemplateObjects;
}
}
The RestTemplate as component, to be injected and mocked after:
@Component
public class RestTemplateObjects {
private final RestTemplate restTemplate;
public RestTemplateObjects () {
this.restTemplate = new RestTemplate();
// you can add extra setup the restTemplate here, like errorHandler or converters
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
}
And the test:
public void test() {
when(mockedRestTemplateObject.get).thenReturn(mockRestTemplate);
//mock restTemplate.exchange
when(mockRestTemplate.exchange(...)).thenReturn(mockedResponseEntity);
SomeService someService = new SomeService(mockedRestTemplateObject);
someService.getListofObjectsA();
}
In this way, you have direct access to mock the rest template by the SomeService constructor.
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
You're the victim of the classic deadlock. task.Wait()
or task.Result
is a blocking call in UI thread which causes the deadlock.
Don't block in the UI thread. Never do it. Just await it.
private async void Button_Click(object sender, RoutedEventArgs
{
var task = GetResponseAsync<MyObject>("my url");
var items = await task;
}
Btw, why are you catching the WebException
and throwing it back? It would be better if you simply don't catch it. Both are same.
Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse
method. StreamReader.ReadToEnd
is a blocking call --you should be using StreamReader.ReadToEndAsync
.
Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.
Your method should look something like the following when you've addressed all the above concerns.
public static async Task<List<T>> GetResponseAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = await strReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<List<T>>(text);
}
You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):
For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:
{{true?true:false}}
I tried the above answers as of vscode 1.42.1 and they worked inasmuch as to get me a git bash terminal. So, bottom line this setting works just for opening a bash shell from terminal:
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
However it has the unwanted side effect of also being the shell used to build things and that breaks the MS C++ chain because the \
character used for path separator is understood by bash as an escape character. The complete fix for me then required me to add this extra variable, setting it to powershell:
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
Now, I can have my bash terminal and Ctrl-Shift-B
or F5
work without problems.
Oh, and as other posters mentioned, the source for this information is VSCode's documentation.
While the official docs are happy not to provide switch, I have seen a solution using dictionaries.
For example:
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
Then the equivalent switch block is invoked:
options[num]()
This begins to fall apart if you heavily depend on fall through.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
<xsl:if test="not contains(hhref,'1234')">
This is actually an area ripe for discussion, with many subtle techniques available. It is important that you select/develop a technique that meets your needs including: screen readers, images/css/scripting on/off combinations, seo, etc.
Here are some good resources to get started down the road of standardista image replacement techniques:
http://faq.css-standards.org/Image_Replacement
This is sonxurxo's solution in Kotlin, if anyone needs it.
private fun getUnsafeOkHttpClient(): OkHttpClient {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
return OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
.hostnameVerifier { _, _ -> true }.build()
}
You might want to consider using console.log
with the built-in "arguments" object:
console.log(arguments); // would have shown you [0] null, [1] yourResult
This will always output all of your arguments, no matter how many arguments you have.
UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')
Two suggestions:
Use a HashSet instead of an ArrayList. This will speed up the contains() checks considerably if you have a long list
Make sure Customer.equals() and Customer.hashCode() are implemented properly, i.e. they should be based on the combined values of the underlying fields in the customer object.
Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));
StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {
sb.append(inFile1.nextLine());
}
String[] yourArray = sb.toString().split(", ");
I have faced the same issue with COMDLG32.OCX and MSFLXGRD.OCX in Windows 10 and Visual Studio 2010. It's an MFC application.
Then I downloaded its zip file from the google after extracting copy them at following paths:
C:\Windows\System32 (*For 32-bit machine*)
C:\Windows\SysWOW64 (*For 64-bit machine*)
Then run Command Prompt as an Administrator then run the following commands:
For Windows 64-bit systems c:\windows\SysWOW64\ regsvr32 comdlg32.ocx
c:\windows\SysWOW64\regsvr32 msflxgrd.ocx (My machine is 64-bit configuration)
For Windows 32-bit systems c:\windows\System32\ regsvr32 comdlg32.ocx
c:\windows\System32\regsvr32 msflxgrd.ocx
On successfully updation of the above cmds it shows succeed message.
Take a look at this A List Apart article. The pertinent CSS is:
@font-face {
font-family: "Kimberley";
src: url(http://www.princexml.com/fonts/larabie/kimberle.ttf) format("truetype");
}
h1 { font-family: "Kimberley", sans-serif }
The above will work in Chrome/Safari/FireFox. As Paul D. Waite pointed out in the comments you can get it to work with IE if you convert the font to the EOT format.
The good news is that this seems to degrade gracefully in older browsers, so as long as you're aware and comfortable with the fact that not all users will see the same font, it's safe to use.
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
Another way that doesn't use group by:
SELECT * FROM tblpm n
WHERE date_updated=(SELECT date_updated FROM tblpm n
ORDER BY date_updated desc LIMIT 1)
Using a regex as you described is the simple way (as far as I am aware). If you want a range you could use [^a-f].
This is an update for dcodesmith's answer https://stackoverflow.com/a/21369918/1668200
The proposed solution also works when the text is longer (i.e. the lines need to wrap): Updated Fiddle
When you're using a grid system, you might need to do one of the following (at least this is true for Foundation 6 - couldn't reproduce it in the Fiddle):
box-sizing:content-box;
to the list or its containertext-indent:-2em;
to -1.5em
P.S.: I wanted to add this as an edit to the original answer, but it was rejected.
In case you need more shorting your code, you can creating new type for helper
type Strings []string
func (ss Strings) ToInterfaceSlice() []interface{} {
iface := make([]interface{}, len(ss))
for i := range ss {
iface[i] = ss[i]
}
return iface
}
then
a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()
If you have just a few places where you wish to create this effect, you can use the following html code that requires no css. Just insert it.
<a href="TARGET URL GOES HERE"><img src="URL OF FIRST IMAGE GOES HERE"
onmouseover="this.src='URL OF IMAGE ON HOVER GOES HERE'"
onmouseout="this.src='URL OF FIRST IMAGE GOES HERE AGAIN'" /></A>
Be sure to write the quote marks exactly as they are here, or it will not work.
If needed small changes in CSS use \9 it targets IE8 and below (IE6, IE7, IE8)
.element {
color:green \9;
}
Best way is to use conditional comments in HTML, like this:
<!--[if IE 8]>
<style>...</style>
<![endif]-->
Maybe it has nothing to do here, but it could be useful for someone.
I installed jdk on: D:\Program Files\Java\jdk1.7.0_06\bin
So I added it to %PATH%
variable and checked it on cmd and everything was ok, but Eclipse kept showing me that error.
I used quotation marks on %PATH%
so it reads something like:
%SYSTEMROOT%\System32;"D:\Program Files\Java\jdk1.7.0_06\bin"
and problem solved.
Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.
When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.
>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False
Sometimes this error occurs when you use your schema (dbo) in your query in a wrong way.
for example if you write:
select dbo.prd.name
from dbo.product prd
you will get the error.
In this situations change it to:
select prd.name
from dbo.product prd
Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.
def __init__(self, city="Berlin"):
self.city = city
t="one,two,three"
a=($(echo "$t" | tr ',' '\n'))
echo "${a[2]}"
Prints three
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
I see a similar problem...
I need to spool CSV file from SQLPLUS, but the output has 250 columns.
What I did to avoid annoying SQLPLUS output formatting:
set linesize 9999
set pagesize 50000
spool myfile.csv
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
the problem is you will lose column header names...
you can add this:
set heading off
spool myfile.csv
select col1_name||';'||col2_name||';'||col3_name||';'||col4_name||';'||col5_name||';'||col6_name||';'||col7_name||';'||col8_name||';'||col9_name||';'||col10_name||';'||col11_name||';'||col12_name||';'||col13_name||';'||col14_name||';'||col15_name||';'||col16_name||';'||col17_name||';'||col18_name||';'||col19_name||';'||col20_name||';'||col21_name||';'||col22_name||';'||col23_name||';'||col24_name||';'||col25_name||';'||col26_name||';'||col27_name||';'||col28_name||';'||col29_name||';'||col30_name from dual;
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
I know it`s kinda hardcore, but it works for me...
This worked for me..
select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view
You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.
This will simply solve your problem.
Not an actual answer but more as a reference.
If you are using the jaxws Maven plugin and you get the same error message, add the mentioned property to the plugin configuration:
...
<plugin>
<groupId>org.jvnet.jax-ws-commons</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.3</version>
<configuration>
<!-- Needed with JAXP 1.5 -->
<vmArgs>
<vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
</vmArgs>
</configuration>
</plugin>
I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
How about just using a containing div which has overflow set to hidden and some padding at the bottom? This seems like much the simplest solution.
Sorry to say I didn't think of this myself but saw it somewhere else.
Using an element to wrap the element getting the box-shadow and a overflow: hidden on the wrapper you could make the extra box-shadow disappear and still have a usable border. This also fixes the problem where the element is smaller as it seems, because of the spread.
Like this:
#wrapper { padding-bottom: 10px; overflow: hidden; } #elem { box-shadow: 0 0 10px black; }
Content goes here
Still a clever solution when it has to be done in pure CSS!
As said by Jorgen Evens.
Number one difference for me: if HAVING
was removed from the SQL language then life would go on more or less as before. Certainly, a minority queries would need to be rewritten using a derived table, CTE, etc but they would arguably be easier to understand and maintain as a result. Maybe vendors' optimizer code would need to be rewritten to account for this, again an opportunity for improvement within the industry.
Now consider for a moment removing WHERE
from the language. This time the majority of queries in existence would need to be rewritten without an obvious alternative construct. Coders would have to get creative e.g. inner join to a table known to contain exactly one row (e.g. DUAL
in Oracle) using the ON
clause to simulate the prior WHERE
clause. Such constructions would be contrived; it would be obvious there was something was missing from the language and the situation would be worse as a result.
TL;DR we could lose HAVING
tomorrow and things would be no worse, possibly better, but the same cannot be said of WHERE
.
From the answers here, it seems that many folk don't realize that a HAVING
clause may be used without a GROUP BY
clause. In this case, the HAVING
clause is applied to the entire table expression and requires that only constants appear in the SELECT
clause. Typically the HAVING
clause will involve aggregates.
This is more useful than it sounds. For example, consider this query to test whether the name
column is unique for all values in T
:
SELECT 1 AS result
FROM T
HAVING COUNT( DISTINCT name ) = COUNT( name );
There are only two possible results: if the HAVING
clause is true then the result with be a single row containing the value 1
, otherwise the result will be the empty set.
You may want to use the onLoad
event, as in the following example:
<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>
The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)
If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location
, as in the following example:
<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>
Anything wrong with a one-liner?
$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
Explanation
-p
processes, then prints <>
line by line-i
activates in-place editing. Files are backed up using the .bak
extensionA workaround to achieve the same specially if you want to use checkbox with for loop is to store the state of the checkbox inside an array and change it based on the index of the *ngFor
loop. This way you can change the state of the checkbox in your component.
app.component.html
<div *ngFor="let item of items; index as i">
<input type="checkbox" [checked]="category[i]" (change)="checkChange(i)">
{{item.name}}
</div>
app.component.ts
items = [
{'name':'salad'},
{'name':'juice'},
{'name':'dessert'},
{'name':'combo'}
];
category= []
checkChange(i){
if (this.category[i]){
this.category[i] = !this.category[i];
}
else{
this.category[i] = true;
}
}
With : i << 2
const data = context.getImageData(x, y, width, height).data;
const pixels = [];
for (let i = 0, dx = 0; dx < data.length; i++, dx = i << 2) {
if (data[dx+3] <= 8)
console.log("transparent x= " + i);
}
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
Tests whether windowsize
is greater than 500
and lesser than 600
meaning that neither values 500
or 600
itself will result in the condition becoming true.
if (windowsize > 500 && windowsize < 600) {
// ...
}
Maybe you might try the web to send the file with proper Content-Type header and with the header like this:
Content-Disposition: inline; filename="xxx.xxx"
Here is a discussion about these headers: How to force files to open in browser instead of download (pdf)?
Or just search on google for content-disposition.
function invertArray(array,arrayWidth,arrayHeight) {
var newArray = [];
for (x=0;x<arrayWidth;x++) {
newArray[x] = [];
for (y=0;y<arrayHeight;y++) {
newArray[x][y] = array[y][x];
}
}
return newArray;
}
If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)
Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.
now,your server side code format look like,
{
"collapse_key": "CHAT_MESSAGE_CONTACT",
"data": {
"loc_key": "CHAT_MESSAGE_CONTACT",
"loc_args": ["John Doe", "Contact Exchange"],
"text": "John Doe shared a contact in the group Contact Exchange",
"custom": {
"chat_id": 241233,
"msg_id": 123
},
"badge": 1,
"sound": "sound1.mp3",
"mute": true
}
}
NOTE: see this line in above code
"text": "John Doe shared a contact in the group Contact Exchange"
in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.
onMessageReceived()
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getData().toString());
if (remoteMessage == null)
return;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
/* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
Log.e(TAG, "Data Payload: " + remoteMessage);
try {
Map<String, String> params = remoteMessage.getData();
JSONObject json = new JSONObject(params);
Log.e("JSON_OBJECT", json.toString());
Log.e(TAG, "onMessageReceived: " + json.toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
RadioGroup radioGroup = new RadioGroup(context);
RadioButton radioBtn1 = new RadioButton(context);
RadioButton radioBtn2 = new RadioButton(context);
RadioButton radioBtn3 = new RadioButton(context);
radioBtn1.setText("Less");
radioBtn2.setText("Normal");
radioBtn3.setText("More");
radioGroup.addView(radioBtn1);
radioGroup.addView(radioBtn2);
radioGroup.addView(radioBtn3);
radioBtn2.setChecked(true);
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
TLDR; Here's why:
The reason this works is because
gulp
tries to run yourgulpfile.js
using your locally installed version ofgulp
, see here. Hence the reason for a global and local install of gulp.
Essentially, when you install gulp
locally the script isn't in your PATH
and so you can't just type gulp
and expect the shell to find the command. By installing it globally the gulp
script gets into your PATH
because the global node/bin/
directory is most likely on your path.
To respect your local dependencies though, gulp
will use your locally installed version of itself to run the gulpfile.js
.
I know this is 8 years old, but no one seems to have actually read and answered the question.
You can call .values() on a dict to get a list of the inner dicts and thus access them by index.
>>> mydict = {
... 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
... 'Grapes':{'Arabian':'25','Indian':'20'} }
>>>mylist = list(mydict.values())
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}
>>>myInnerList1 = list(mylist[0].values())
>>>myInnerList1
['16', 10, 5]
>>>myInnerList2 = list(mylist[1].values())
>>>myInnerList2
['25', '20']
Axtavt answer is correct.
This is how your resolver should look like (annotations based):
@Bean
UrlBasedViewResolver resolver(){
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
Obviously the name of your views directory should change based on your project.
As the other answers suggest, editing/removing credentials in the Manage Windows Credentials
work and does the job. However, you need to do this each time when the password changes or credentials do not work for some work. Using ssh key
has been extremely useful for me where I don't have to bother about these again once I'm done creating a ssh-key
and adding them on the server repository (github/bitbucket/gitlab).
Generating a new ssh-key
Open Git Bash.
Paste the text below, substituting in your repo's email address.
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Then you'll be asked to type a secure passphrase. You can type a passphrase, hit enter and type the passphrase again.
Or, Hit enter twice for empty passphrase.
Copy this on the clipboard:
clip < ~/.ssh/id_rsa.pub
And then add this key into your repo's profile. For e.g, on github->setting->SSH keys -> paste the key that you coppied ad hit add
You're done once and for all!
I use this,
input:-webkit-autofill { -webkit-box-shadow: 0 0 0px 1000px white inset !important; }
input:focus:-webkit-autofill { -webkit-box-shadow: 0 0 0px 1000px white inset !important; }
/* You can use color:#color to change the color */
In EntityFramework 6 please try:
Add-Migration Initial
in order to update the initial migration file.
In addition to @ShinDarth answer.
I did what he said but my package did not updated the angular version, and I know that this post is about angular-cli
, but i think that this can help too.
-ng new projectname
that generated a package.-npm install
.Now my ng serve
is working again, maybe there is a better way to do all that, if someone know, please share, because this is a pain to do with all projects that need update.
I am posting a new answer, as I do not have enough reputation to comment on the one provided by Antonio (see: https://stackoverflow.com/a/1957777).
In case you want the SOAP message to be printed in a file (e.g. via Log4j), you may use:
OutputStream os = new ByteArrayOutputStream();
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
soapMsg.writeTo(os);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(os.toString());
Please note that under certain circumstances, the method call writeTo() may not behave as expected (see: https://community.oracle.com/thread/1123104?tstart=0 or https://www.java.net/node/691073), therefore the following code will do the trick:
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
com.sun.xml.ws.api.message.Message msg = new com.sun.xml.ws.message.saaj.SAAJMessage(soapMsg);
com.sun.xml.ws.api.message.Packet packet = new com.sun.xml.ws.api.message.Packet(msg);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(packet.toString());
Note: I wrote this answer when Entity Framework 4 was actual. The point of this answer was not to get into trivial .Any()
vs .Count()
performance testing. The point was to signal that EF is far from perfect. Newer versions are better... but if you have part of code that's slow and it uses EF, test with direct TSQL and compare performance rather than relying on assumptions (that .Any()
is ALWAYS faster than .Count() > 0
).
While I agree with most up-voted answer and comments - especially on the point Any
signals developer intent better than Count() > 0
- I've had situation in which Count is faster by order of magnitude on SQL Server (EntityFramework 4).
Here is query with Any
that thew timeout exception (on ~200.000 records):
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& !a.NewsletterLogs.Any(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr)
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
Count
version executed in matter of milliseconds:
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& a.NewsletterLogs.Count(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr) == 0
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
I need to find a way to see what exact SQL both LINQs produce - but it's obvious there is a huge performance difference between Count
and Any
in some cases, and unfortunately it seems you can't just stick with Any
in all cases.
EDIT: Here are generated SQLs. Beauties as you can see ;)
ANY
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created] FROM [dbo].[Contact] AS [Extent1] WHERE ([Extent1].[CompanyId] = @p__linq__0) AND ([Extent1].[ContactStatusId] <= 3) AND ( NOT EXISTS (SELECT 1 AS [C1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId]) )) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
COUNT
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Project1].[ContactId] AS [ContactId], [Project1].[CompanyId] AS [CompanyId], [Project1].[ContactName] AS [ContactName], [Project1].[FullName] AS [FullName], [Project1].[ContactStatusId] AS [ContactStatusId], [Project1].[Created] AS [Created] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created], (SELECT COUNT(1) AS [A1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId])) AS [C1] FROM [dbo].[Contact] AS [Extent1] ) AS [Project1] WHERE ([Project1].[CompanyId] = @p__linq__0) AND ([Project1].[ContactStatusId] <= 3) AND (0 = [Project1].[C1]) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
Seems that pure Where with EXISTS works much worse than calculating Count and then doing Where with Count == 0.
Let me know if you guys see some error in my findings. What can be taken out of all this regardless of Any vs Count discussion is that any more complex LINQ is way better off when rewritten as Stored Procedure ;).
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
If for whatever reason the power goes or the Visual Studio IDE crashes it can cause this problem inside your bin/debug bin/release...
Just delete the content and recompile (from personal experience when my toe hit the reset button!)
Many of the answers on this thread work, but it's my understanding if you're trying to do anything dynamic you'll eventually need to call:
[self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
I often need to run more code per condition, by using: ( , , )
multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
split
returns an Iterator
, which you can convert into a Vec
using collect
: split_line.collect::<Vec<_>>()
. Going through an iterator instead of returning a Vec
directly has several advantages:
split
is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>()
, or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next()
. This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".split
makes no assumption on the way you want to store the result. You can use a Vec
, but you can also use anything that implements FromIterator<&str>
, for example a LinkedList
or a VecDeque
, or any custom type that implements FromIterator<&str>
.You can add a TextView
to your linear layout programmatically like this:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
TextView txt1 = new TextView(MyClass.this);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);
invert isBefore method of moment to check if a date is same as today or in future like this:
!moment(yourDate).isBefore(moment(), "day");
For example String.Format("{0:0,0}", 1);
returns 01, for me is not valid
This works for me
19950000.ToString("#,#", CultureInfo.InvariantCulture));
output 19,950,000
Try this:
schtasks /change /ENABLE /tn "Auto Restart" /s mycomutername /u mycomputername\username/p mypassowrd
csvde -f test.csv
This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.
You will have to go through that output file and get rid off the unnecessary content.
Public variable declarations in classes is the easiest way:
On target class:
public class MyFragment extends Fragment {
public MyCallerFragment caller; // Declare the caller var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Do what you want with the vars
caller.str = "I changed your value!";
caller.i = 9999;
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
On caller class:
public class MyCallerFragment extends Fragment {
public Integer i; // Declared public var
public String str; // Declared public var
...
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
myFragment = new MyFragment();
myFragment.caller = this;
transaction.replace(R.id.nav_host_fragment, myFragment)
.addToBackStack(null).commit();
...
}
If you want to use the main activity it is easy too:
On main activity class:
public class MainActivity extends AppCompatActivity {
public String str; // Declare public var
public EditText myEditText; // You can declare public elements too.
// Taking care that you have it assigned
// correctly.
...
}
On called class:
public class MyFragment extends Fragment {
private MainActivity main; // Declare the activity var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Assign the main activity var
main = (MainActivity) getActivity();
// Do what you want with the vars
main.str = "I changed your value!";
main.myEditText.setText("Wow I can modify the EditText too!");
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.
For more combinations use your creativity. :)
(See answer below for a Angular 1.3 solution.)
The issue here is that the search will execute every time the model changes, which is every keyup action on an input.
There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http, $timeout) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
// This is what you will bind the filter to
$scope.filterText = '';
// Instantiate these variables outside the watch
var tempFilterText = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
tempFilterText = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = tempFilterText;
}, 250); // delay 250 ms
})
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
<span>{{entry.content}}</span>
</div>
This may be a bit of effort but you could download my open-source wiki project from codeplex:
http://shuttlewiki.codeplex.com
It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.
The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)
The ShuttleWiki project shows how to use it in the post-build event.
I ran into the same issue recently working with a batch file on a network share drive in Windows 7.
Another way that worked for me was to map the server to a drive through Windows Explorer: Tools -> Map network drive. Give it a drive letter and folder path to \yourserver. Since I work with the network share often mapping to it makes it more convenient, and it resolved the “UNC path are not supported” error.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
You could do it like this:
<a>
with a class, say "cancel"set up the dialog by acting on all elements with class="cancel":
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
}
}
});
return false;
});
(plus your other options)
The key points here are:
However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...
If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):
css
div.row-fluid [class*="span"] .center-in-span {
float: none;
margin: 0 auto;
text-align: center;
display: block;
width: auto;
height: auto;
}
html
<div class="row-fluid">
<div class="span12">
<img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<p class="center-in-span">this is text</p>
</div>
</div>
USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.
To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.
EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.
Let me know if this is thorough enough for easy implementation.
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
Correct or Incorrect: Please execute test locally and decide for yourself!
Edit/Remove is faster in LinkedList
than ArrayList
.
ArrayList
, backed by Array
, which needs to be double the size, is worse in large volume application.
Below is the unit test result for each operation.Timing is given in Nanoseconds.
Operation ArrayList LinkedList
AddAll (Insert) 101,16719 2623,29291
Add (Insert-Sequentially) 152,46840 966,62216
Add (insert-randomly) 36527 29193
remove (Delete) 20,56,9095 20,45,4904
contains (Search) 186,15,704 189,64,981
Here's the code:
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class ArrayListVsLinkedList {
private static final int MAX = 500000;
String[] strings = maxArray();
////////////// ADD ALL ////////////////////////////////////////
@Test
public void arrayListAddAll() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
arrayList.addAll(stringList);
watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
}
@Test
public void linkedListAddAll() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
watch.start();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
watch.totalTime("Linked List addAll() = "); //2623,29291 Nanoseconds
}
//Note: ArrayList is 26 time faster here than LinkedList for addAll()
///////////////// INSERT /////////////////////////////////////////////
@Test
public void arrayListAdd() {
Watch watch = new Watch();
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
for (String string : strings)
arrayList.add(string);
watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
}
@Test
public void linkedListAdd() {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
watch.start();
for (String string : strings)
linkedList.add(string);
watch.totalTime("Linked List add() = "); //966,62216 Nanoseconds
}
//Note: ArrayList is 9 times faster than LinkedList for add sequentially
/////////////////// INSERT IN BETWEEN ///////////////////////////////////////
@Test
public void arrayListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
arrayList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
arrayList.add(insertString0);
arrayList.add(insertString1);
arrayList.add(insertString2);
arrayList.add(insertString3);
watch.totalTime("Array List add() = ");//36527
}
@Test
public void linkedListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
linkedList.add(insertString0);
linkedList.add(insertString1);
linkedList.add(insertString2);
linkedList.add(insertString3);
watch.totalTime("Linked List add = ");//29193
}
//Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
////////////////// DELETE //////////////////////////////////////////////////////
@Test
public void arrayListRemove() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.remove(searchString0);
arrayList.remove(searchString1);
watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
}
@Test
public void linkedListRemove() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.remove(searchString0);
linkedList.remove(searchString1);
watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
}
//Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
///////////////////// SEARCH ///////////////////////////////////////////
@Test
public void arrayListSearch() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.contains(searchString0);
arrayList.contains(searchString1);
watch.totalTime("Array List addAll() time = ");//186,15,704
}
@Test
public void linkedListSearch() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.contains(searchString0);
linkedList.contains(searchString1);
watch.totalTime("Linked List addAll() time = ");//189,64,981
}
//Note: Linked List is 500 Milliseconds faster than ArrayList
class Watch {
private long startTime;
private long endTime;
public void start() {
startTime = System.nanoTime();
}
private void stop() {
endTime = System.nanoTime();
}
public void totalTime(String s) {
stop();
System.out.println(s + (endTime - startTime));
}
}
private String[] maxArray() {
String[] strings = new String[MAX];
Boolean result = Boolean.TRUE;
for (int i = 0; i < MAX; i++) {
strings[i] = getString(result, i);
result = !result;
}
return strings;
}
private String getString(Boolean result, int i) {
return String.valueOf(result) + i + String.valueOf(!result);
}
}
I have ran into that same problem. I actually developed my using server side programming, but I did a quick search to try and help you out and found this.
Seems alright, didn't look at the source too much, but seems to be purely JavaScript.
Take look:
http://www.rainforestnet.com/datetimepicker/datetimepicker.htm
Here is the demo page link:
http://www.rainforestnet.com/datetimepicker/datetimepicker-demo.htm
good luck
I do not have a USB serial device, but there must be a way to find the real ports using the HAL libraries directly:
====================================================================
#! /usr/bin/env bash
#
# Uses HAL to find existing serial hardware
#
for sport in $(hal-find-by-capability --capability serial) ; do
hal-get-property --udi "${sport}" --key serial.device
done
====================================================================
The posted python-dbus code nor this sh script lists the bluetooth /dev/rfcomm* devices, so it is not the best solution.
Note that on other unix platforms, the serial ports are not named ttyS? and even in linux, some serial cards allow you to name the devices. Assuming a pattern in the serial devices names is wrong.
To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.
Like others have said, specify a negative selectedIndex
on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.
<select onchange="myCallback();" onfocus="this.selectedIndex=-1;this.blur();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script type="text/javascript">
$.fn.alwaysChange = function(callback) {
return this.each(function(){
var elem = this;
var $this = $(this);
$this.change(function(){
if(callback) callback($this.val());
}).focus(function(){
elem.selectedIndex = -1;
elem.blur();
});
});
}
$('select').alwaysChange(function(val){
// Optional change event callback,
// shorthand for $('select').alwaysChange().change(function(){});
});
</script>
You can see a working demo here.
If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.
SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
cch.cchid = (
SELECT MAX(cchid)
FROM client_calling_history
WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
)
This is the way i fix my problem. and it now work when i writing this answer:
Firstly, i try all the most fix way above,
remove Pods_xxx.framework from the link libraries and framework in target's build phases is helpful, and the issue will disappear, but the coming problem is i can't import the Pods.framework anymore.
And Then, i try to reinit the xcworkspace config, so that i can figure out the real problem. so i run
pod deintergate
and then install my pod again:
pod install
this work prefectly, but the problem is still in there, but i figure out the real problem is the Pods_xxx.framworks not be compiled succeed by cocoapods build script. I think this is the true way to fix the problem.
Finally, i try to edit my project's scheme:
and i add Pods scheme into manage:
and build this Pods.framework separately, and you will find the Pods.framework icon become truly again:
and i think now you have fix your "framework not found Pods_xxxx.framework" problem but actually i have another problem coming:
so i go to the build setting, and edit the "Framework Search Path"
with "${inherited}"
,
and now all the problems goes out, cheer!!!!:)
Try:
while on that page, in the address bar of a stock Android browser, type:
about:debug
(Note nothing happens, but some new options have been enabled.)
Works on the devices I have tried. Read more on Android browser's about:debug, what do those settings do?
Edit: What also helps to retrieve more information like line number is to add this code to your script:
window.onerror = function (message, url, lineNo){
console.log('Error: ' + message + '\n' + 'Line Number: ' + lineNo);
return true;
}
The first one catches all subclasses of Throwable
(this includes Exception
and Error
), the second one catches all subclasses of Exception
.
Error
is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception
is programmatically recoverable. Its subclass RuntimeException
indicates a programming error and is usually not to be caught as well.
:not()
pseudo class:For selecting everything but a certain element (or elements). We can use the :not()
CSS pseudo class. The :not()
pseudo class requires a CSS
selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.
/* This query selects All div elements except for */_x000D_
div:not(.foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
<nav id="foo">test</nav>_x000D_
<nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>
_x000D_
We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
app.get('/category', function(req, res) {
var string = query
res.redirect('/?valid=' + string);
});
in the ejs you can directly use valid:
<% var k = valid %>
I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command
grep -r --color foo /opt
with no issue. With Cygwin /
represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.
Uninstall what Git you have and install the Cygwin git package, save yourself the headache.
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
def head(iterable):
try:
return iter(iterable).next()
except StopIteration:
return None
print head(xrange(42, 1000) # 42
print head([]) # None
BTW: I'd rework your general program flow into something like this:
lists = [
["first", "list"],
["second", "list"],
["third", "list"]
]
def do_something(element):
if not element:
return
else:
# do something
pass
for li in lists:
do_something(head(li))
(Avoiding repetition whenever possible)
i used eltima make virtual serial port for my modbus application debug work. it is really very good application at development stage to check serial port program without connecting hardware.
I'm using
Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"
to format a column
So I guess
Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"
would do the trick for you.
More: NumberFormat function.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
A one-line version of this excellent answer to plot the line of best fit is:
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
Using np.unique(x)
instead of x
handles the case where x
isn't sorted or has duplicate values.
Unidecode is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text.
Example:
accented_string = u'Málaga'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaga'and is of type 'str'
Interfaces do not contain any implementation.
Bitmap memoryImage;
//Set full width, height for image
memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
Size s = new Size(memoryImage.Width, memoryImage.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
try
{
str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
@"\Screenshot.png");//Set folder to save image
}
catch { };
memoryImage.save(str);
Bash 3.0+ can use this syntax:
for i in {1..10} ; do ... ; done
..which avoids spawning an external program to expand the sequence (such as seq 1 10
).
Of course, this has the same problem as the for(())
solution, being tied to bash and even a particular version (if this matters to you).
File size by MySQL type:
I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.
Latest version of SpringBoot makes uploading multiple files very easy also. On the browser side you just need the standard HTML upload form, but with multiple input elements (one per file to upload, which is very important), all having the same element name (name="files" for the example below)
Then in your Spring @Controller class on the server all you need is something like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> upload(
@RequestParam("files") MultipartFile[] uploadFiles) throws Exception
{
...now loop over all uploadFiles in the array and do what you want
return new ResponseEntity<>(HttpStatus.OK);
}
Those are the tricky parts. That is, knowing to create multiple input elements each named "files", and knowing to use a MultipartFile[] (array) as the request parameter are the tricky things to know, but it's just that simple. I won't get into how to process a MultipartFile entry, because there's plenty of docs on that already.
#Script for calculating various values in MB
echo "Please enter some input: "
read input_variable
echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'
Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.
First specification of url-pattern
a web.xml
file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern>
as follows:
http://server.com/server/status/synopsis = Matches
http://server.com/server/status/complete?date=today = Matches
http://server.com/server/status = Matches
http://server.com/server/server1/status = Does not match
Second specification of url-pattern
A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern>
as follows:
http://server.com/server/US/Oregon/Portland.map = Matches
http://server.com/server/US/server/Seattle.map = Matches
http://server.com/server/Paris.France.map = Matches
http://server.com/server/US/Oregon/Portland.MAP = Does not match, the extension is uppercase
http://example.com/examples/interface/description/mail.mapi =Does not match, the extension is mapi rather than map`
Third specification of url-mapping
,A mapping that contains the pattern <url-pattern>/</url-pattern>
matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.
The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.
The servlet-mapping element below maps the server
servlet instance to the default mapping.
<servlet-mapping>
<servlet-name>server</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
For the context that contains this element, any request that is not handled by another mapping is forwarded to the server
servlet.
And Most importantly we should Know about Rule for URL path mapping
Reference URL Pattern
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example1</title>
<link rel="stylesheet" href="css/style.css" >
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function display_case(){
var num = document.getElementById('number').value;
switch(num){
case (num = "1"):
document.getElementById("result").innerHTML = "You select day Sunday";
break;
case (num = "2"):
document.getElementById("result").innerHTML = "You select day Monday";
break;
case (num = "3"):
document.getElementById("result").innerHTML = "You select day Tuesday";
break;
case (num = "4"):
document.getElementById("result").innerHTML = "You select day Wednesday";
break;
case (num = "5"):
document.getElementById("result").innerHTML = "You select day Thusday";
break;
case (num = "6"):
document.getElementById("result").innerHTML = "You select day Friday";
break;
case (num = "7"):
document.getElementById("result").innerHTML = "You select day Saturday";
break;
default:
document.getElementById("result").innerHTML = "You select day Invalid Weekday";
break
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Switch Case Example </h2>
<p>Enter a Number Between 1 to 7</p>
<input type="text" id="number" />
<button onclick="display_case();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
And if you want to avoid the restart of the application, you can move out the appSettings
section:
<appSettings configSource="Config\appSettings.config"/>
to a separate file. And in combination with ConfigurationSaveMode.Minimal
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);
you can continue to use the appSettings
section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.
Please try following
if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
echo "WORKING"
else
echo "Out of range!"
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
The Bootstrap 3 documentation talks about this in the CSS documentation tab in the section labelled "Requires custom widths", which states:
Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
If you use your browser and Firebug or Chrome tools to suppress or reduce the "width" style, you should see things line up they way you want. Clearly you can then create the appropriate CSS to fix the issue.
However, I find it odd that I need to do this at all. I couldn't help but feel this manipulation was both annoying and in the long term, error prone. Ultimately, I used a dummy class and some JS to globally shim all my inline inputs. It was small number of cases, so not much of a concern.
Nonetheless, I too would love to hear from someone who has the "right" solution, and could eliminate my shim/hack.
Hope this helps, and props to you for not blowing a gasket at all the people that ignored your request as a Bootstrap 3 concern.
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
If you are constructing the connection string within the app then you would use your command of connString. If you are using a connection string in the web config. Then you use the "name" of that string.
If you're using xml.etree.ElementTree.parse
to parse from a file, then you can use xml.etree.ElementTree.fromstring
to parse from text.
This solution unlock me after couple of hours of research :
In the configuration initialize the core() option
@Override
public void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.etc
}
Initialize your Credential, Origin, Header and Method as your wish in the corsFilter.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
I didn't need to use this class:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
}
Suppose you have a Customer Entity mapped to CUSTOMER_INFORMATION table and you want to get list of distinct firstName of customer. You can use below snippet to get the same.
Query distinctFirstName = session.createQuery("select ci.firstName from Customer ci group by ci.firstName");
Object [] firstNamesRows = distinctFirstName.list();
I hope it helps. So here we are using group by instead of using distinct keyword.
Also previously I found it difficult to use distinct keyword when I want to apply it to multiple columns. For example I want of get list of distinct firstName, lastName then group by would simply work. I had difficulty in using distinct in this case.
<span> is an inline tag, a <p> is a block tag, used for paragraphs. Browsers will render a blank line below a paragraph, whereas <span>s will render on the same line.
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
Here an answer for those who'd like to have preinitialized lists of lists. Needs Java 8+.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Scratch {
public static void main(String[] args) {
int M = 4;
int N = 3;
// preinitialized array (== list of lists) of strings, sizes not fixed
List<List<String>> listOfListsOfString = initializeListOfListsOfT(M, N, "-");
System.out.println(listOfListsOfString);
// preinitialized array (== list of lists) of int (primitive type), sizes not fixed
List<List<Integer>> listOfListsOfInt = initializeListOfListsOfInt(M, N, 7);
System.out.println(listOfListsOfInt);
}
public static <T> List<List<T>> initializeListOfListsOfT(int m, int n, T initValue) {
return IntStream
.range(0, m)
.boxed()
.map(i -> new ArrayList<T>(IntStream
.range(0, n)
.boxed()
.map(j -> initValue)
.collect(Collectors.toList()))
)
.collect(Collectors.toList());
}
public static List<List<Integer>> initializeListOfListsOfInt(int m, int n, int initValue) {
return IntStream
.range(0, m)
.boxed()
.map(i -> new ArrayList<>(IntStream
.range(0, n)
.map(j -> initValue)
.boxed()
.collect(Collectors.toList()))
)
.collect(Collectors.toList());
}
}
Output:
[[-, -, -], [-, -, -], [-, -, -], [-, -, -]]
[[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7]]
Side note for those wondering about IntStream
:
IntStream
.range(0, m)
.boxed()
is equivalent to
Stream
.iterate(0, j -> j + 1)
.limit(n)
edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.
Another approach is using the shortid package from npm.
It is very easy to use:
var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF
and has some compelling features:
ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.
- By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
- Non-sequential so they are not predictable.
- Can generate any number of ids without duplicates, even millions per day.
- Apps can be restarted any number of times without any chance of repeating an id.
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
DateTime dt;
TimeZoneInfo tzf;
tzf = TimeZoneInfo.FindSystemTimeZoneById("TimeZone String");
dt = TimeZoneInfo.ConvertTime(DateTime.Now, tzf);
lbltime.Text = dt.ToString();
There are a number of work-flows you can use. The main point is not to break history in a published branch unless you've communicated with everyone who might consume the branch and are willing to do surgery on everyone's clones. It's best not to do that if you can avoid it.
Your outlined steps have merit. If you need the dev branch to be stable right away, do it that way. You have a number of tools for Debugging with Git that will help you find the right branch point, and then you can revert all the commits between your last stable commit and HEAD.
Either revert commits one at a time, in reverse order, or use the <first_bad_commit>..<last_bad_commit>
range. Hashes are the simplest way to specify the commit range, but there are other notations. For example, if you've pushed 5 bad commits, you could revert them with:
# Revert a series using ancestor notation.
git revert --no-edit dev~5..dev
# Revert a series using commit hashes.
git revert --no-edit ffffffff..12345678
This will apply reversed patches to your working directory in sequence, working backwards towards your known-good commit. With the --no-edit flag, the changes to your working directory will be automatically committed after each reversed patch is applied.
See man 1 git-revert
for more options, and man 7 gitrevisions
for different ways to specify the commits to be reverted.
Alternatively, you can branch off your HEAD, fix things the way they need to be, and re-merge. Your build will be broken in the meantime, but this may make sense in some situations.
Of course, if you're absolutely sure that no one has pulled from the repository since your bad pushes, and if the remote is a bare repository, then you can do a non-fast-forward commit.
git reset --hard <last_good_commit>
git push --force
This will leave the reflog intact on your system and the upstream host, but your bad commits will disappear from the directly-accessible history and won't propagate on pulls. Your old changes will hang around until the repositories are pruned, but only Git ninjas will be able to see or recover the commits you made by mistake.
The basic difference :
Linear regression is basically a regression model which means its will give a non discreet/continuous output of a function. So this approach gives the value. For example : given x what is f(x)
For example given a training set of different factors and the price of a property after training we can provide the required factors to determine what will be the property price.
Logistic regression is basically a binary classification algorithm which means that here there will be discreet valued output for the function . For example : for a given x if f(x)>threshold classify it to be 1 else classify it to be 0.
For example given a set of brain tumour size as training data we can use the size as input to determine whether its a benine or malignant tumour. Therefore here the output is discreet either 0 or 1.
*here the function is basically the hypothesis function
JavaScript has an eval
function that evaluates a string and executes it as code:
eval(settings.functionName + '(' + t.parentNode.id + ')');
quick answer
#include<stdio.h>
#include<time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);
return 0;
}
You can remove database directly as:
$ mysqladmin -h [host] -u [user] -p drop [database_name]
[Enter Password]
Do you really want to drop the 'hairfree' database [y/N]: y
Sure, why not? Let's say you have a Person
table, with id
, name
, age
, and parent_id
, where parent_id
is a foreign key to the same table. You wouldn't need to normalize the Person
table to Parent
and Child
tables, that would be overkill.
Person
| id | name | age | parent_id |
|----|-------|-----|-----------|
| 1 | Tom | 50 | null |
| 2 | Billy | 15 | 1 |
Something like this.
I suppose to maintain consistency, there would need to be at least 1 null value for parent_id
, though. The one "alpha male" row.
EDIT: As the comments show, Sam found a good reason not to do this. It seems that in MySQL when you attempt to make edits to the primary key, even if you specify CASCADE ON UPDATE
it won’t propagate the edit properly. Although primary keys are (usually) off-limits to editing in production, it is nevertheless a limitation not to be ignored. Thus I change my answer to:- you should probably avoid this practice unless you have pretty tight control over the production system (and can guarantee no one will implement a control that edits the PKs). I haven't tested it outside of MySQL.
IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.
Window menu, New Horizontal/Vertical Tab Group there will do, I think.
You can use String.Replace which basically removes all occurrences
line.Replace(@"\", "");
Here is the way to do it:
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0
hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]
It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.
Options:
- The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
- The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
- The -v option will display the names of columns as a header line.
- The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.
du
returns three columns with the following format: +-------------------------------------------------------------------+
| size | disk_space_consumed_with_all_replicas | full_path_name |
+-------------------------------------------------------------------+
##Example command:
hadoop fs -du /user/hadoop/dir1 \
/user/hadoop/file1 \
hdfs://nn.example.com/user/hadoop/dir1
Exit Code: Returns 0 on success and -1 on error.
The Rails
implements the method descendants
, but models not necessarily ever inherits from ActiveRecord::Base
, for example, the class that includes the module ActiveModel::Model
will have the same behavior as a model, just doesn't will be linked to a table.
So complementing what says the colleagues above, the slightest effort would do this:
Monkey Patch of class Class
of the Ruby:
class Class
def extends? constant
ancestors.include?(constant) if constant != self
end
end
and the method models
, including ancestors, as this:
The method Module.constants
returns (superficially) a collection of symbols
, instead of constants, so, the method Array#select
can be substituted like this monkey patch of the Module
:
class Module
def demodulize
splitted_trail = self.to_s.split("::")
constant = splitted_trail.last
const_get(constant) if defines?(constant)
end
private :demodulize
def defines? constant, verbose=false
splitted_trail = constant.split("::")
trail_name = splitted_trail.first
begin
trail = const_get(trail_name) if Object.send(:const_defined?, trail_name)
splitted_trail.slice(1, splitted_trail.length - 1).each do |constant_name|
trail = trail.send(:const_defined?, constant_name) ? trail.const_get(constant_name) : nil
end
true if trail
rescue Exception => e
$stderr.puts "Exception recovered when trying to check if the constant \"#{constant}\" is defined: #{e}" if verbose
end unless constant.empty?
end
def has_constants?
true if constants.any?
end
def nestings counted=[], &block
trail = self.to_s
collected = []
recursivityQueue = []
constants.each do |const_name|
const_name = const_name.to_s
const_for_try = "#{trail}::#{const_name}"
constant = const_for_try.constantize
begin
constant_sym = constant.to_s.to_sym
if constant && !counted.include?(constant_sym)
counted << constant_sym
if (constant.is_a?(Module) || constant.is_a?(Class))
value = block_given? ? block.call(constant) : constant
collected << value if value
recursivityQueue.push({
constant: constant,
counted: counted,
block: block
}) if constant.has_constants?
end
end
rescue Exception
end
end
recursivityQueue.each do |data|
collected.concat data[:constant].nestings(data[:counted], &data[:block])
end
collected
end
end
Monkey patch of String
.
class String
def constantize
if Module.defines?(self)
Module.const_get self
else
demodulized = self.split("::").last
Module.const_get(demodulized) if Module.defines?(demodulized)
end
end
end
And, finally, the models method
def models
# preload only models
application.config.eager_load_paths = model_eager_load_paths
application.eager_load!
models = Module.nestings do |const|
const if const.is_a?(Class) && const != ActiveRecord::SchemaMigration && (const.extends?(ActiveRecord::Base) || const.include?(ActiveModel::Model))
end
end
private
def application
::Rails.application
end
def model_eager_load_paths
eager_load_paths = application.config.eager_load_paths.collect do |eager_load_path|
model_paths = application.config.paths["app/models"].collect do |model_path|
eager_load_path if Regexp.new("(#{model_path})$").match(eager_load_path)
end
end.flatten.compact
end
If you are using Selenium web driver with Python, you can use PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.
PyVirtualDisplay needs Xvfb as a dependency. On Ubuntu, first install Xvfb:
sudo apt-get install xvfb
Then install PyVirtualDisplay from PyPI:
pip install pyvirtualdisplay
Sample Selenium script in Python in a headless mode with PyVirtualDisplay:
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# Now Firefox will run in a virtual display.
# You will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
EDIT
The initial answer was posted in 2014 and now we are at the cusp of 2018. Like everything else, browsers have also advanced. Chrome has a completely headless version now which eliminates the need to use any third-party libraries to hide the UI window. Sample code is as follows:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options
)
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()
From an answer to Force a browser to save file as after clicking link:
<a href="path/to/file" download>Click here to download</a>
You can't call it asynchronously, since there is no asynchronous property support, only async methods. As such, there are two options, both taking advantage of the fact that asynchronous methods in the CTP are really just a method that returns Task<T>
or Task
:
// Make the property return a Task<T>
public Task<IEnumerable> MyList
{
get
{
// Just call the method
return MyAsyncMethod();
}
}
Or:
// Make the property blocking
public IEnumerable MyList
{
get
{
// Block via .Result
return MyAsyncMethod().Result;
}
}
Examples from Apache use this:
CloseableHttpClient httpclient = HttpClients.createDefault();
The class org.apache.http.impl.client.HttpClients
is there since version 4.3.
The code for HttpClients.createDefault()
is the same as the accepted answer in here.
Installing from RPM is generally better, because:
Red Hat has added through the EPEL repository:
sudo yum install -y epel-release
sudo yum install -y python34
# Install pip3
sudo yum install -y python34-setuptools # install easy_install-3.4
sudo easy_install-3.4 pip
You can create your virtualenv using pyvenv
:
pyvenv /tmp/foo
With CentOS7, pip3.6
is provided as a package :)
sudo yum install -y epel-release
sudo yum install -y python36 python36-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
If you use the pyvenv
script, you'll get a WARNING:
$ pyvenv-3.6 /tmp/foo
WARNING: the pyenv script is deprecated in favour of `python3.6 -m venv`
The IUS Community provides some up-to-date packages for RHEL & CentOS. The guys behind are from Rackspace, so I think that they are quite trustworthy...
Check the right repo for you here:
sudo yum install -y https://repo.ius.io/ius-release-el6.rpm
sudo yum install -y python36u python36u-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
sudo yum install -y https://repo.ius.io/ius-release-el7.rpm
sudo yum install -y python36u python36u-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
First prototype using plain old grep
and cut
:
grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"
If that's fast enough and gives the proper output, you're done.
This can be done for free using GIMP.
It uses the ability of GIMP to have each layer a different size.
I created the following layers sized correctly.
Notes
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
Anding an integer with 0xFF
leaves only the least significant byte. For example, to get the first byte in a short s
, you can write s & 0xFF
. This is typically referred to as "masking". If byte1
is either a single byte type (like uint8_t
) or is already less than 256 (and as a result is all zeroes except for the least significant byte) there is no need to mask out the higher bits, as they are already zero.
See tristopiaPatrick Schlüter's answer below when you may be working with signed types. When doing bitwise operations, I recommend working only with unsigned types.
There are a lot of ways to do this but the best is to use handler like below
long millisecDelay=3000
Handler().postDelayed({
// do your work here
},millisecDelay)
I've found a solution by creating the following function:
CREATE FUNCTION [dbo].[JoinTexts]
(
@delimiter VARCHAR(20) ,
@whereClause VARCHAR(1)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @Texts VARCHAR(MAX)
SELECT @Texts = COALESCE(@Texts + @delimiter, '') + T.Texto
FROM SomeTable AS T
WHERE T.SomeOtherColumn = @whereClause
RETURN @Texts
END
GO
Usage:
SELECT dbo.JoinTexts(' , ', 'Y')
In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:
YourHash.has_key? :yourkey
The answer to the question was already posted by the @latemail in the comments above. You can use regular expressions for the second and subsequent arguments of filter
like this:
dplyr::filter(df, !grepl("RTB",TrackingPixel))
Since you have not provided the original data, I will add a toy example using the mtcars
data set. Imagine you are only interested in cars produced by Mazda or Toyota.
mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
If you would like to do it the other way round, namely excluding Toyota and Mazda cars, the filter
command looks like this:
dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
Had the same problem, but solved it in a different way. It might not be the best solution, but its a solution.
in app.config:
<add key="errorMailFirst" value="[email protected]"/>
<add key="errorMailSeond" value="[email protected]"/>
Then in my configuration wrapper class, I add a method to search keys.
public List<string> SearchKeys(string searchTerm)
{
var keys = ConfigurationManager.AppSettings.Keys;
return keys.Cast<object>()
.Where(key => key.ToString().ToLower()
.Contains(searchTerm.ToLower()))
.Select(key => ConfigurationManager.AppSettings.Get(key.ToString())).ToList();
}
For anyone reading this, i agree that creating your own custom configuration section is cleaner, and more secure, but for small projects, where you need something quick, this might solve it.
sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;
connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;
truncate table tmp;
exit;
EOF
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
The command you're looking for is rem
, short for "remark".
There is also a shorthand version ::
that some people use, and this sort of looks like #
if you squint a bit and look at it sideways. I originally preferred that variant since I'm a bash
-aholic and I'm still trying to forget the painful days of BASIC :-)
Unfortunately, there are situations where ::
stuffs up the command line processor (such as within complex if
or for
statements) so I generally use rem
nowadays. In any case, it's a hack, suborning the label infrastructure to make it look like a comment when it really isn't. For example, try replacing rem
with ::
in the following example and see how it works out:
if 1==1 (
rem comment line 1
echo 1 equals 1
rem comment line 2
)
You should also keep in mind that rem
is a command, so you can't just bang it at the end of a line like the #
in bash
. It has to go where a command would go. For example, only the second of these two will echo the single word hello
:
echo hello rem a comment.
echo hello & rem a comment.
Try this code
final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String string = editText.getText().toString();
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
});
Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
Maybe this url can help you: Activating Browser Modes with Doctype
Edit: Today we were able to override the compatibility view with:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
Found the port esp32 was connected to by -
ls /dev/*
You would get a long list and you can find the port you need
It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.
So ...
new ModelAndView(view, name, value);
is equivalent to:
Map model = ...
model.put(name, value);
new ModelAndView(view, model);
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>
, <iframe>
or <object>
. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.
For More Information: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
I have an alternate solution for this problem, which I am going to demonstrate by using PHP:
iframe.php:
<iframe src="target_url.php" width="925" height="2400" frameborder="0" ></iframe>
target_url.php:
<?php
echo file_get_contents("http://www.example.com");
?>
I hit this error because I was specifying a label attribute in my geom (geom_text
) but was specifying a color in the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
geom_text(angle=45, label=df$V1, size=2)
To fix this, I just moved the label attribute out of the geom and into the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
geom_text(angle=45, size=2)
As of this writing, it was necessary to:
<ProgressBar
android:minHeight="20dip"
android:maxHeight="20dip"/>
make new style
.container {
position: relative;
}
.center-nav {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: auto;
max-width: 200px;
text-align: center;
}
.center-nav li{
text-align: center;
width:100%;
}
Replace website name UL with below
<ul class="nav navbar-nav center-nav">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
Hope this helps..
Hey please add code in your project,it is easy and i think will solve your problem.
int count = 10;
private void timer1_Tick(object sender, EventArgs e)
{
count--;
if (count != 0 && count > 0)
{
label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
}
else
{
label1.Text = "game over";
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Interval = 1;
timer1.Tick += new EventHandler(timer1_Tick);
}
Its complete if it can test and branch (has an 'if')
you can use -> Reporter.log("");
You don't need to fiddle around with any command :)
Once the XCode is updated, open the Xcode IDE program. Please accept terms and conditions.
You are all set to go :))
I'm using python 3.4, requests 2.19.1:
'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel
It far easier to use the scripting runtime which is installed by default on Windows
Just go project Reference and check Microsoft Scripting Runtime and click OK.
Then you can use this code which is way better than the default file commands
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
TempS = TS.ReadLine
Final = Final & TempS & vbCrLf
Loop
TS.Close
Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing
As for what is wrong with your original code here you are reading each line of the text file.
Input #iFileNo, sFileText
Then here you write it out
Write #iFileNo, sFileText
sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.
So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.
Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo
iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo
Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).
If you need to process the incoming data then you need to do something like this.
Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
C.Add sFileText
Loop
Close #iFileNo
For Each vTemp in C
Process vTemp
Next sTemp
iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo
ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select
You can install the apk on your phone, then
connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
This taken from Find package name for Android apps to use Intent to launch Market app from web
You could try using float:left;
or display:inline-block;
.
Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.
However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block
will have less of an impact though, so probably best to try that first.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Copy the project files from the original source and paste it somewhere and then import from the Android Studio.
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
I would do it in the simplest way, so anyone can understand what happens, even if there are smarter ways:
my $text = "";
while (my $line = <FILE>) {
$text .= $line;
}
Actually, you can achieve this pretty easy. Simply specify the line height as a number:
<p style="line-height:1.5">
<span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
<span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>
The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.
For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.
try
sudo dnf update
and then
sudo dnf install gcc-c++
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
Take a look on this answer to another related question. It shows how to enable, disable and to see the logs on live servers without restarting.
Here is a summary:
If you don't want or cannot restart the MySQL server you can proceed like this on your running server:
Create your log tables (see answer)
Enable Query logging on the database (Note that the string 'table' should be put literally and not substituted by any table name. Thanks Nicholas Pickering)
SET global general_log = 1;
SET global log_output = 'table';
select * from mysql.general_log;
SET global general_log = 0;
TRUNCATE mysql.general_log
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
$dateValue = strtotime($q);
$yr = date("Y", $dateValue) ." ";
$mon = date("m", $dateValue)." ";
$date = date("d", $dateValue);
Escaping the double quotes with backslashes is the only way to do this in Java.
Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)
One other option would be to put the String into some kind of text file that you would then read at runtime
Font-awesome provides a great solution out of the box:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
////////////////////////// 1] File to Byte [] ///////////////////
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
/////////////////////// 2] Byte [] to File ///////////////////////////
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
the boolean value of an empty QuerySet is also False, so you could also just do...
...
if not user_object:
do insert or whatever etc.
There is a javascript port of the PHP function "number_format".
I find it very usefull as it is easy to use and recognisable for PHP developers.
function number_format (number, decimals, dec_point, thousands_sep) {
var n = number, prec = decimals;
var toFixedFix = function (n,prec) {
var k = Math.pow(10,prec);
return (Math.round(n*k)/k).toString();
};
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);
//fix for IE parseFloat(0.55).toFixed(0) = 0;
var abs = toFixedFix(Math.abs(n), prec);
var _, i;
if (abs >= 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec);
} else {
s = s.replace('.', dec);
}
var decPos = s.indexOf(dec);
if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
}
else if (prec >= 1 && decPos === -1) {
s += dec+new Array(prec).join(0)+'0';
}
return s;
}
(Comment block from the original, included below for examples & credit where due)
// Formats a number with grouped thousands
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/number_format
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://getsprink.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + bugfix by: Howard Yeend
// + revised by: Luke Smith (http://lucassmith.name)
// + bugfix by: Diogo Resende
// + bugfix by: Rival
// + input by: Kheang Hok Chin (http://www.distantia.ca/)
// + improved by: davook
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Jay Klehr
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Amir Habibi (http://www.residence-mixte.com/)
// + bugfix by: Brett Zamir (http://brett-zamir.me)
// * example 1: number_format(1234.56);
// * returns 1: '1,235'
// * example 2: number_format(1234.56, 2, ',', ' ');
// * returns 2: '1 234,56'
// * example 3: number_format(1234.5678, 2, '.', '');
// * returns 3: '1234.57'
// * example 4: number_format(67, 2, ',', '.');
// * returns 4: '67,00'
// * example 5: number_format(1000);
// * returns 5: '1,000'
// * example 6: number_format(67.311, 2);
// * returns 6: '67.31'
// * example 7: number_format(1000.55, 1);
// * returns 7: '1,000.6'
// * example 8: number_format(67000, 5, ',', '.');
// * returns 8: '67.000,00000'
// * example 9: number_format(0.9, 0);
// * returns 9: '1'
// * example 10: number_format('1.20', 2);
// * returns 10: '1.20'
// * example 11: number_format('1.20', 4);
// * returns 11: '1.2000'
// * example 12: number_format('1.2000', 3);
// * returns 12: '1.200'
Run WampServer: Apache->service->test port 80.
Find out what application which occupies the port 80(e.g. skype)
Shut down and restarts WampServer.
A simple approach is to output as html, which pandas does out of the box:
df.to_html('temp.html')
If this is for Cygwin, it installs "pip" as "pip2". Just create a softlink to "pip2" in the same location where "pip2" is installed.
I had this same problem described in the following way: If I typed
$ git diff
Git simply returned to the prompt with no error.
If I typed
$ git diff <filename>
Git simply returned to the prompt with no error.
Finally, by reading around I noticed that git diff
actually calls the mingw64\bin\diff.exe
to do the work.
Here's the deal. I'm running Windows and had installed another Bash utility and it changed my path so it no longer pointed to my mingw64\bin directory.
So if you type:
git diff
and it just returns to the prompt you may have this problem.
The actual diff.exe which is run by
git
is located in your mingw64\bin directory
Finally, to fix this, I actually copied my mingw64\bin
directory to the location Git was looking for it in. I tried it and it still didn't work.
Then, I closed my Git Bash window and opened it again went to my same repository that was failing and now it works.
Option #1: Use Clear() function to empty the List<T>
and retain it's capacity.
Count is set to 0, and references to other objects from elements of the collection are also released.
Capacity remains unchanged.
Option #2 - Use Clear() and TrimExcess() functions to set List<T>
to initial state.
Count is set to 0, and references to other objects from elements of the collection are also released.
Trimming an empty
List<T>
sets the capacity of the List to the default capacity.
Definitions
Count = number of elements that are actually in the List<T>
Capacity = total number of elements the internal data structure can hold without resizing.
Clear() Only
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Clear() and TrimExcess()
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);