@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate localDate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime localDateTime;
no dependency required with Spring boot >= 2.2+
An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).
Here's an example of injecting an EntityManagerFactory:
package com.test.service;
import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;
@Path("/service")
public class TestService {
@PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
@GET
@Path("/get")
@Produces("application/json")
public List get() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
return entityManager.createQuery("from TestEntity").getResultList();
} finally {
entityManager.close();
}
}
}
The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.
Related question: Inject an EJB into JAX-RS (RESTful service)
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Normally we face this issue when there is a problem mapping JSON node with that of Java object. I faced the same issue because in the swagger the node was defined as of Type array and the JSON object was having only one element , hence the system was having difficulty in mapping one element list to an array.
In Swagger the element was defined as
Test:
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/definitions/TestNew"
}
While it should be
Test:
"$ref": "#/definitions/TestNew"
And TestNew
should be of type array
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
See this IEEE_754_types.h
header for the union types to extract: float
, double
and long double
, (endianness handled). Here is an extract:
/*
** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** Single Precision (float) -- Standard IEEE 754 Floating-point Specification
*/
# define IEEE_754_FLOAT_MANTISSA_BITS (23)
# define IEEE_754_FLOAT_EXPONENT_BITS (8)
# define IEEE_754_FLOAT_SIGN_BITS (1)
.
.
.
# if (IS_BIG_ENDIAN == 1)
typedef union {
float value;
struct {
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
};
} IEEE_754_float;
# else
typedef union {
float value;
struct {
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
};
} IEEE_754_float;
# endif
And see dtoa_base.c
for a demonstration of how to convert a double
value to string form.
Furthermore, check out section 1.2.1.1.4.2 - Floating-Point Type Memory Layout of the C/CPP Reference Book, it explains super well and in simple terms the memory representation/layout of all the floating-point types and how to decode them (w/ illustrations) following the actually IEEE 754 Floating-Point specification.
It also has links to really really good ressources that explain even deeper.
In August 2020
No more regular expression stuff
const str = "Test abc test test abc test test test abc test test abc";
const modifiedStr = str.replaceAll('abc', '');
console.log(modifiedStr);
_x000D_
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''
def compare(bin1, bin2):
return bin1.lstrip('0') == bin2.lstrip('0')
def add(bin1, bin2):
result = ''
blen = max((len(bin1), len(bin2))) + 1
bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
carry_s = '0'
for b1, b2 in list(zip(bin1, bin2))[::-1]:
count = (carry_s, b1, b2).count('1')
carry_s = '1' if count >= 2 else '0'
result += '1' if count % 2 else '0'
return result[::-1]
if __name__ == '__main__':
print(add('101', '100'))
I leave the subtraction func as an exercise for the reader.
Try fart.exe. It's a Find-and-replace-text utility that can be used in command batch programs.
This is what I am using as of now:
nnoremap <silent> <Leader>= :exe "resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>- :exe "resize " . (winheight(0) * 2/3)<CR>
nnoremap <silent> <Leader>0 :exe "vertical resize " . (winwidth(0) * 3/2)<CR>
nnoremap <silent> <Leader>9 :exe "vertical resize " . (winwidth(0) * 2/3)<CR>
In one line:
'Groupname' in user.groups.values_list('name', flat=True)
This evaluates to either True
or False
.
You need to do this:
var scope = {
splitterStyle: {
height: 100
}
};
And then apply this styling to the required elements:
<div id="horizontal" style={splitterStyle}>
In your code you are doing this (which is incorrect):
<div id="horizontal" style={height}>
Where height = 100
.
You can use the new Object.fromEntries()
method.
Example:
const array = [_x000D_
{key: 'a', value: 'b', redundant: 'aaa'},_x000D_
{key: 'x', value: 'y', redundant: 'zzz'}_x000D_
]_x000D_
_x000D_
const hash = Object.fromEntries(_x000D_
array.map(e => [e.key, e.value])_x000D_
)_x000D_
_x000D_
console.log(hash) // {a: b, x: y}
_x000D_
Not only strings are immutable reference types. Multi-cast delegates too. That is why it is safe to write
protected void OnMyEventHandler()
{
delegate handler = this.MyEventHandler;
if (null != handler)
{
handler(this, new EventArgs());
}
}
I suppose that strings are immutable because this is the most safe method to work with them and allocate memory. Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define
string s1 = "my string";
//some code here
string s2 = "my string";
Chances are that both instances of "my string" constant will be allocated in your assembly only once.
If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.
If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.
Or you can use this:
char *ExtractFileExt(char *FileName)
{
std::string s = FileName;
int Len = s.length();
while(TRUE)
{
if(FileName[Len] != '.')
Len--;
else
{
char *Ext = new char[s.length()-Len+1];
for(int a=0; a<s.length()-Len; a++)
Ext[a] = FileName[s.length()-(s.length()-Len)+a];
Ext[s.length()-Len] = '\0';
return Ext;
}
}
}
This code is cross-platform
You can use format operator for rounding the value up to 2 decimal places in python:
print(format(14.4499923, '.2f')) // output is 14.45
Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).
powershell -command "& {&'some-command' someParam}"
Also, here is a neat way to do multiple commands:
powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"
For example, this is how I ran my 2 commands:
powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"
The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />
<context:annotation-config />
Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.
Alternative constructors are the classic example.
Use mod_rewrite
as instructed in this tutorial from the CI wiki.
For future visitors.
As of now Android 4.2.2 platform includes Google Play services. Just use an emulator running Jelly Bean. Details can be found here:
Setup Google Play Services SDK
EDIT:
Another option is to use Genymotion (runs way faster)
EDIT 2:
As @gdw2 commented: "setting up the Google Play Services SDK does not install a working Google Play app -- it just enables certain services provided by the SDK"
After version 2.0 Genymotion does not come with Play Services by default, but it can be easily installed manually. Just download the right version from here and drag and drop into the virtual device (emulador).
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
Here is an example for how to extract the href
attrbiutes of all a
tags:
import requests as rq
from bs4 import BeautifulSoup as bs
url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')
hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
# print(href.get("href"))
links = href.get("href")
all_hrefs.append(links)
print(all_hrefs)
That's not how you do it.
>>> ''.join(['first', 'second', 'other'])
'firstsecondother'
is what you want.
If you do it in a for
loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):
>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
... s += item
...
>>> s
'firstsecondother'
This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.
The number 0
in {0:X}
refers to the position in the list or arguments. In this case 0
means use the first value, which is Blue
. Use {1:X}
for the second argument (Green
), and so on.
colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);
The syntax for the format parameter is described in the documentation:
Format Item Syntax
Each format item takes the following form and consists of the following components:
{ index[,alignment][:formatString]}
The matching braces ("{" and "}") are required.
Index Component
The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.
Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".
Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.
Alignment Component
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
Format String Component
The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.
Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.
I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.
#
indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.
So, #include
is a preprocessor directive that tells the preprocessor to include header files in the program.
< >
indicate the start and end of the file name to be included.
iostream
is a header file that contains functions for input/output operations (cin
and cout
).
Now to sum it up C++ to English translation of the command, #include <iostream>
is:
Dear preprocessor, please include all the contents of the header file iostream
at the very beginning of this program before compiler starts the actual compilation of the code.
A simple way would be:
print str(count) + ' ' + str(conv)
If you need more spaces, simply add them to the string:
print str(count) + ' ' + str(conv)
A fancier way, using the new syntax for string formatting:
print '{0} {1}'.format(count, conv)
Or using the old syntax, limiting the number of decimals to two:
print '%d %.2f' % (count, conv)
Just need to add font-size: 0;
to your element that contains text.
This works well.
This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.
<style type="text/css">
#footer {
position : absolute;
bottom : 0;
height : 40px;
margin-top : 40px;
}
</style>
<div id="footer">I am footer</div>
The height and margin-top should be the same so that the footer doesnt show over the content.
In the context of browser, Javascript can READ user-specified file. See Eric Bidelman's blog for detail about reading file using File API. However, it is not possible for browser-based Javascript to WRITE the file system of local computer without disabling some security settings because it is regarded as a security threat for any website to change your local file system arbitrarily.
Saying that, there are some ways to work around it depending what you are trying to do:
If it is your own site, you can embed a Java Applet in the web page. However, the visitor has to install Java on local machine and will be alerted about the security risk. The visitor has to allow the applet to be loaded. An Java Applet is like an executable software that has complete access to the local computer.
Chrome supports a file system which is a sandboxed portion of the local file system. See this page for details. This provides possibly for you to temporarily save things locally. However, this is not supported by other browsers.
If you are not limited to browser, Node.js has a complete file system interface. See here for its file system documentation. Note that Node.js can run not only on servers, but also any client computer including windows. The javascript test runner Karma is based on Node.js. If you just like to program in javascript on the local computer, this is an option.
It's working
Try below code
$('#example').dataTable({
"bProcessing": true,
"sAutoWidth": false,
"bDestroy":true,
"sPaginationType": "bootstrap", // full_numbers
"iDisplayStart ": 10,
"iDisplayLength": 10,
"bPaginate": false, //hide pagination
"bFilter": false, //hide Search bar
"bInfo": false, // hide showing entries
})
It is up to the browser but they behave in similar ways.
I have tested FF, IE7, Opera and Chrome.
F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".
CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.
If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.
Edit: Updated table
The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.
Updated table, 27 September 2010
+------------------------------------------------------------+
¦ UPDATED ¦ Firefox 3.x ¦
¦27 SEP 2010 ¦ +--------------------------------------------¦
¦ ¦ ¦ MSIE 8, 7 ¦
¦ Version 3 ¦ ¦ +-----------------------------------------¦
¦ ¦ ¦ ¦ Chrome 6.0 ¦
¦ ¦ ¦ ¦ +--------------------------------------¦
¦ ¦ ¦ ¦ ¦ Chrome 1.0 ¦
¦ ¦ ¦ ¦ ¦ +-----------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ Opera 10, 9 ¦
¦ ¦ ¦ ¦ ¦ ¦ +--------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
+------------+--+--+--+--+--+--------------------------------¦
¦ F5¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend: ¦
¦ CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since" ¦
¦ ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache" ¦
¦ ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache" ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦ CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦ ¦
+------------+--+--+--+--+--¦ ¦
¦ Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers ¦
¦ Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon. ¦
¦ Alt-Click¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦ ¦
+------------------------------------------------------------+
Versions tested:
Notes:
Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".
Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.
Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>
You can try this
$scope.$watch('tags ',function(){
$scope.tags = $filter('lowercase')($scope.tags);
});
You are sure you are linking to the same file and then editing that same file?
On some browser, you can use CTRL F5 to force a refresh (on the PC). On the Mac, it is Cmd Shift R
Firebug also has a net tab with "Disable Browser Cache".
But I want to give a warning here: even if you can hard refresh, how do you know your customers are getting the latest version? So you need to check, rather than just making sure you and your program manager can do a hard refresh and just go home and take the paycheck next month. If you want to do a job that change the world for the better, or leave the world a little bit better than you found it, you need to investigate more to make sure it works for your customers too (or else, sometimes the customer may call tech support, and tech support may read the script of "clear out the cookies and it will work", which is what happens to me sometimes). Some methods down at the bottom of this post can ensure the customers get the latest version.
If you are using Chrome and the DevTools is open, you can click and hold the Refresh icon in front of the address bar, and a box will pop up, and you can choose to "Hard Reload" or even "Empty Cache and Hard Reload":
If you use the Google Chrome debugger, it is the same, you can go to the Network section and make sure the "Disable cache (while DevTools is open)" is checked, in the Settings of the debugger panel.
Also, when you link the JavaScript file, use
<script src="my-js-file.js?v=1"></script>
or v=2
, and so forth, when you definitely want to refresh the file. Or you can go to the console and do a Date.now()
and get a timestamp, such as 1491313943549
, and use
<script src="my-js-file.js?t=1491313943549"></script>
Some building tools will do that automatically for you, or can be configured to do that, making it something like:
<script src="main.742a4952.js"></script>
which essentially will bust the cache.
Note that when you use the v=2
or t=1491313943549
, or main.742a4952.js
, you also have the advantage that for your users, they definitely will get the newer version as well.
Weak (Non-Identifying) Relationship
Entity is existence-independent of other enties
PK of Child doesn’t contain PK component of Parent Entity
Strong (Identifying) Relationship
Child entity is existence-dependent on parent
PK of Child Entity contains PK component of Parent Entity
Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.
I had to change @User3759685 above answer to this when the openpxyl updated. I was getting an error. Well @phihag reported this in the comments as well
for column_cells in ws.columns:
new_column_length = max(len(as_text(cell.value)) for cell in column_cells)
new_column_letter = (openpyxl.utils.get_column_letter(column_cells[0].column))
if new_column_length > 0:
ws.column_dimensions[new_column_letter].width = new_column_length + 1
I use the following method to calculate age:
$oDateNow = new DateTime();
$oDateBirth = new DateTime($sDateBirth);
// New interval
$oDateIntervall = $oDateNow->diff($oDateBirth);
// Output
echo $oDateIntervall->y;
This is the link I needed to fix the problem (install nodejs): https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager
I know I am late, but stumped into the question, and based on ThomasH's answer:
for i in range(4): print "i equals 3" if i==3 else None
output: None None None i equals 3
I propose to update as:
for i in range(4): print("i equals 3") if i==3 else print('', end='')
output: i equals 3
Note, I am in python3 and had to use two print commands. pass after else won't work. Wanted to just comment on ThomasH's answer, but can't because I don't have enough reputation yet.
I will add to @Aaron's answer with an approach that gives you the opportunity to style the dialog box in a better way. Here is an adjusted example:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
m_Text = input.getText().toString();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
Here is the example layout used to create the EditText dialog:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/content_padding_normal">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:imeOptions="actionDone"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
</FrameLayout>
The final result:
SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update
UPDATE table
SET col1 = NULL
WHERE col1 = ''
NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.
If you want to do it during your copy from one table to another, use this:
INSERT INTO newtable ( col1, othercolumn )
SELECT
NULLIF(col1, ''),
othercolumn
FROM table
As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.
Not dependent on Java Math.round() types
Use filter
:
newlist=filter(lambda x: len(x)>0, oldlist)
The drawbacks of using filter as pointed out is that it is slower than alternatives; also, lambda
is usually costly.
Or you can go for the simplest and the most iterative of all:
# I am assuming listtext is the original list containing (possibly) empty items
for item in listtext:
if item:
newlist.append(str(item))
# You can remove str() based on the content of your original list
this is the most intuitive of the methods and does it in decent time.
1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.
2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).
Say you have a table containing courses that are taken in a certain semester, and you have the following data:
|-----Primary Key----| uh oh |
V
CourseID | SemesterID | #Places | Course Name |
------------------------------------------------|
IT101 | 2009-1 | 100 | Programming |
IT101 | 2009-2 | 100 | Programming |
IT102 | 2009-1 | 200 | Databases |
IT102 | 2010-1 | 150 | Databases |
IT103 | 2009-2 | 120 | Web Design |
This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.
Primary Key |
CourseID | Course Name |
---------------------------|
IT101 | Programming |
IT102 | Databases |
IT103 | Web Design |
No redundancy!
Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:
|-----Primary Key----| uh oh |
V
Course | Semester | #Places | TeacherID | TeacherName |
---------------------------------------------------------------|
IT101 | 2009-1 | 100 | 332 | Mr Jones |
IT101 | 2009-2 | 100 | 332 | Mr Jones |
IT102 | 2009-1 | 200 | 495 | Mr Bentley |
IT102 | 2010-1 | 150 | 332 | Mr Jones |
IT103 | 2009-2 | 120 | 242 | Mrs Smith |
Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.
Primary Key |
TeacherID | TeacherName |
---------------------------|
332 | Mr Jones |
495 | Mr Bentley |
242 | Mrs Smith |
No redundancy!!
One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.
If you are already using SOLR, remain stick to it. If you are starting up, go for Elastic search.
Maximum major issues have been fixed in SOLR and it is quite mature.
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
Alt+Click. It works in Windows.
Details: Visual Studio Code Documentation
For others that arrive here, this exact message will also appear when using the env variable syntax for commands, for example ${which sh}
instead of the correct $(which sh)
Photoshop - right click layer -> blending options -> color overlay change color and save
Use Radium!
The following is an example from their website:
var Radium = require('radium');_x000D_
var React = require('react');_x000D_
var color = require('color');_x000D_
_x000D_
@Radium_x000D_
class Button extends React.Component {_x000D_
static propTypes = {_x000D_
kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired_x000D_
};_x000D_
_x000D_
render() {_x000D_
// Radium extends the style attribute to accept an array. It will merge_x000D_
// the styles in order. We use this feature here to apply the primary_x000D_
// or warning styles depending on the value of the `kind` prop. Since its_x000D_
// all just JavaScript, you can use whatever logic you want to decide which_x000D_
// styles are applied (props, state, context, etc)._x000D_
return (_x000D_
<button_x000D_
style={[_x000D_
styles.base,_x000D_
styles[this.props.kind]_x000D_
]}>_x000D_
{this.props.children}_x000D_
</button>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
// You can create your style objects dynamically or share them for_x000D_
// every instance of the component._x000D_
var styles = {_x000D_
base: {_x000D_
color: '#fff',_x000D_
_x000D_
// Adding interactive state couldn't be easier! Add a special key to your_x000D_
// style object (:hover, :focus, :active, or @media) with the additional rules._x000D_
':hover': {_x000D_
background: color('#0074d9').lighten(0.2).hexString()_x000D_
}_x000D_
},_x000D_
_x000D_
primary: {_x000D_
background: '#0074D9'_x000D_
},_x000D_
_x000D_
warning: {_x000D_
background: '#FF4136'_x000D_
}_x000D_
};
_x000D_
With the following,
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(5) << 25;
}
the output will be
00025
setfill
is set to the space character (' '
) by default. setw
sets the width of the field to be printed, and that's it.
If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.
Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.
See Common Sequence Operations:
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.
Also Value Comparisons for further details:
Lexicographical comparison between built-in collections works as follows:
- For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example,
[1,2] == (1,2)
is false because the type is not the same).- Collections that support order comparison are ordered the same as their first unequal elements (for example,
[1,2,x] <= [1,2,y]
has the same value asx <= y
). If a corresponding element does not exist, the shorter collection is ordered first (for example,[1,2] < [1,2,3]
is true).
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).
Note 1: <
and >
do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).
Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.
Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.
You need to change the loop from for ($i=1; $i<count($files); $i++)
to for ($i=0; $i<count($files); $i++)
:
So the correct code is
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
print $image ."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
?>
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
If you want to make sure the border is on the inside of your element, you can use
box-sizing:border-box;
this will place the following border on the inside of the element:
border: 10px solid black;
(similar result you'd get using the additonal parameter inset
on box-shadow, but instead this one is for the real border and you can still use your shadow for something else.)
Note to another answer above: as soon as you use any inset
on box-shadow
of a certain element, you are limited to a maximum of 2 box-shadows on that element and would require a wrapper div for further shadowing.
Both solutions should as well get you rid of the undesired 3D effects. Also note both solutions are stackable (see the example I've added in 2018)
.example-border {_x000D_
width:100px;_x000D_
height:100px;_x000D_
border:40px solid blue;_x000D_
box-sizing:border-box;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.example-shadow {_x000D_
width:100px;_x000D_
height:100px;_x000D_
float:left;_x000D_
margin-left:20px;_x000D_
box-shadow:0 0 0 40px green inset;_x000D_
}_x000D_
_x000D_
.example-combined {_x000D_
width:100px;_x000D_
height:100px;_x000D_
float:left;_x000D_
margin-left:20px;_x000D_
border:20px solid orange;_x000D_
box-sizing:border-box;_x000D_
box-shadow:0 0 0 20px red inset;_x000D_
}
_x000D_
<div class="example-border"></div>_x000D_
<div class="example-shadow"></div>_x000D_
<div class="example-combined"></div>
_x000D_
This is crude, but it works well. The Visual Studio on one of my projects (I turn MVC view building on to catch markup errors), well, the project becomes unresponsive while building. I can't cancel the build using the keyboard shortcuts.
So I made this batch file that sits on my quick launch task bar.
@echo off
echo KILL BILLd
for /L %%i in (1,1,10) do (
Taskkill /IM aspnet_compiler.exe /F
timeout 1
)
I also made the batch file launch minimized. The build stops and Visual Studio just throws in the error window that there was a problem building.
Please also consider to use
git clone --mirror path_to_source_repository
From the documentation:
Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.
pip
is a command line tool, not Python syntax.
In other words, run the command in your console, not in the Python interpreter:
pip install beautifulsoup4
You may have to use the full path:
C:\Python27\Scripts\pip install beautifulsoup4
or even
C:\Python27\Scripts\pip.exe install beautifulsoup4
Windows will then execute the pip
program and that will use Python to install the package.
Another option is to use the Python -m
command-line switch to run the pip
module, which then operates exactly like the pip
command:
python -m pip install beautifulsoup4
or
python.exe -m pip install beautifulsoup4
Anthony
try the below one. it will give ur expected output
select c.name as Fields from
tempdb.sys.columns c
inner join tempdb.sys.tables t
ON c.object_id = t.object_id
where t.name like '#MyTempTable%'
Single comment ctrl + / and also multiple line comment you can select multiple line and then ctrl + /. Then, to remove comment you can use ctrl + c for both single line and multiple line comment.
I have another situation where I think it is perfectly reasonable to call the destructor.
When writing a "Reset" type of method to restore an object to its initial state, it is perfectly reasonable to call the Destructor to delete the old data that is being reset.
class Widget
{
private:
char* pDataText { NULL };
int idNumber { 0 };
public:
void Setup() { pDataText = new char[100]; }
~Widget() { delete pDataText; }
void Reset()
{
Widget blankWidget;
this->~Widget(); // Manually delete the current object using the dtor
*this = blankObject; // Copy a blank object to the this-object.
}
};
Use the File.WriteAllText
method. It creates the file if it doesn't exist and overwrites it if it exists.
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
It's also cleaner to use @JoinTable
when an Entity could be the child in several parent/child relationships with different types of parents. To follow up with Behrang's example, imagine a Task can be the child of Project, Person, Department, Study, and Process.
Should the task
table have 5 nullable
foreign key fields? I think not...
+1 for TextMate on Mac OS X.
See also answers to this question. I recommend trying NetBeans if you're on Windows.
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
Add an onclick
to your DIV
tag.
@Transactional
Annotations should be placed around all operations that are inseparable.
Using @Transactional
transaction propagation are handled automatically.In this case if another method is called by current method,then that method will have the option of joining the ongoing transaction.
So lets take example:
We have 2 model's i.e. Country
and City
. Relational Mapping of Country
and City
model is like one Country
can have multiple Cities so mapping is like,
@OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;
Here Country mapped to multiple cities with fetching them Lazily
. So here comes role of @Transactinal
when we retrieve Country object from database then we will get all the data of Country object but will not get Set of cities because we are fetching cities LAZILY
.
//Without @Transactional
public Country getCountry(){
Country country = countryRepository.getCountry();
//After getting Country Object connection between countryRepository and database is Closed
}
When we want to access Set of Cities from country object then we will get null values in that Set because object of Set created only this Set is not initialize with there data to get values of Set we use @Transactional
i.e.,
//with @Transactional
@Transactional
public Country getCountry(){
Country country = countryRepository.getCountry();
//below when we initialize cities using object country so that directly communicate with database and retrieve all cities from database this happens just because of @Transactinal
Object object = country.getCities().size();
}
So basically @Transactional
is Service can make multiple call in single transaction without closing connection with end point.
Use DATE(NOW())
to compare dates
DATE(NOW())
will give you the date part of current date and DATE(duedate)
will give you the date part of the due date. then you can easily compare the dates
So you can compare it like
DATE(NOW()) = DATE(duedate)
OR
DATE(duedate) = CURDATE()
See here
FROM openjdk:8-jdk-alpine
RUN apk update && apk add wget openssl lsof procps curl
RUN apk update
RUN mkdir -p /apps/agent
RUN mkdir -p /apps/lib
ADD ./app/agent /apps/agent
ADD ./app/lib /apps/lib
ADD ./app/* /apps/app/
RUN ls -lrt /apps/app/
CMD sh /apps/app/launch.sh
by using DockerFile, I'm copying agent and lib directories to /apps/agent,/apps/lib directories and bunch of files to target.
A very easy solution worked for me:
if (62 % 50 != 0) {
var number = 62 / 50 + 1 // adding 1 is doing the actual "round up"
}
number contains value 2
Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.
While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for
), conditionals (<% if
) and transforms (<%= myString | uppercase %>
) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).
One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script>
type
, e.g. <script type="text/template">
. For your case:
<script type="text/template" data-template="listitem">
<a href="${url}" class="list-group-item">
<table>
<tr>
<td><img src="${img}"></td>
<td><p class="list-group-item-text">${title}</p></td>
</tr>
</table>
</a>
</script>
On document load, read your template and tokenize it using a simple String#split
var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
Notice that with our token, you get it in the alternating [text, property, text, property]
format. This lets us nicely map it using an Array#map
, with a mapping function:
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
Where props
could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }
.
Putting it all together assuming you've parsed and loaded your itemTpl
as above, and you have an items
array in-scope:
$('.search').keyup(function () {
$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector
and .innerHTML
.
A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.
In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html
method above.
const Item = ({ url, img, title }) => `
<a href="${url}" class="list-group-item">
<div class="image">
<img src="${img}" />
</div>
<p class="list-group-item-text">${title}</p>
</a>
`;
Then you could easily render it, even mapped from an array, like so:
$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.
event.target
gives you the native DOM node, then you need to use the regular DOM APIs to access attributes. Here are docs on how to do that:Using data attributes.
You can do either event.target.dataset.tag
or event.target.getAttribute('data-tag')
; either one works.
For everybody who still can't read in a simple .txt file with the Java scanner.
I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.
The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)
The Scanner shouldn't have any problem after this.
$date = new DateTime('2000-12-31');
$date->modify('+1 day');
echo $date->format('Y-m-d') . "\n";
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.
For more take a look at the MDN docs page for return
.
Here's my flavor without the loss of hover. I personally like it better than the standard bootstrap transitioning.
.btn-primary,_x000D_
.btn-primary:active,_x000D_
.btn-primary:visited {_x000D_
background-color: #8064A2 !important;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
background-color: #594671 !important;_x000D_
transition: all 1s ease;_x000D_
-webkit-transition: all 1s ease;_x000D_
-moz-transition: all 1s ease;_x000D_
-o-transition: all 1s ease;_x000D_
-ms-transition: all 1s ease;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<button class="btn btn-primary">Hover me!</button>
_x000D_
For me, it was having display: none;
#spinner-success-text {
display: none;
transition: all 1s ease-in;
}
#spinner-success-text.show {
display: block;
}
Removing it, and using opacity
instead, fixed the issue.
#spinner-success-text {
opacity: 0;
transition: all 1s ease-in;
}
#spinner-success-text.show {
opacity: 1;
}
Swift 5
button.layer.borderWidth = 2
To change the colour of the border use
button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)
Production source code:
// Remove this if you wanna be fired
You have to add repositories
to your build file. For maven repositories you have to prefix repository name with maven{}
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
On Android 5.1 Lollipop for my device, click on the Google Settings
icon > Security
> Scan device for security threats
.
Note that Google Settings
is separated from the Settings
app itself.
You could use a workflow for this.
# ./.github/workflows/rename.yaml
name: Rename Directory
on:
push:
jobs:
rename:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: git mv old_name new_name
- uses: EndBug/[email protected]
Then just delete the workflow file, which you can do in the UI
OR you could just use javac file1.java
and then also use javac file2.java
afterwards.
Code that calls COM object dlls (for example, to read proprietary data files), may work fine in a user interface but hang mysteriously from a service. The reason is that as of .Net 2.0 user interfaces assume STA (thread-safe) while services assume MTA ((before that, services assumed STA). Having to create an STA thread for every COM call in a service can add significant overhead.
Access Token
for Mobile Number and Country Code
(Server Side OR Client Side)You can get the mobile number
with your access_token
with this API
https://graph.accountkit.com/v1.1/me/?access_token=xxxxxxxxxxxx. Maybe, once you have the mobile number
and the id
, you can work with it to verify the user with your server & database
.
xxxxxxxxxx
above is the Access Token
{
"id": "61940819992708",
"phone": {
"number": "+91XX82923912",
"country_prefix": "91",
"national_number": "XX82923912"
}
}
Auth Code
for Access Token
(Server Side)If you have an Auth Code
instead, you can first get the Access Token
with this API
- https://graph.accountkit.com/v1.1/access_token?grant_type=authorization_code&code=xxxxxxxxxx&access_token=AA|yyyyyyyyyy|zzzzzzzzzz
xxxxxxxxxx
, yyyyyyyyyy
and zzzzzzzzzz
above are the Auth Code
, App ID
and App Secret
respectively.
{
"id": "619XX819992708",
"access_token": "EMAWdcsi711meGS2qQpNk4XBTwUBIDtqYAKoZBbBZAEZCZAXyWVbqvKUyKgDZBniZBFwKVyoVGHXnquCcikBqc9ROF2qAxLRrqBYAvXknwND3dhHU0iLZCRwBNHNlyQZD",
"token_refresh_interval_sec": XX92000
}
server-side
since the API
requires the APP Secret
which is not meant to be shared
for security reasons
.Good Luck.
Check the answer from Marc from C#: Good/best implementation of Swap method.
public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
T tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
}
which can be linq-i-fied like
public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
T tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
return list;
}
var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);
Try
$ awk 'NF>1{print $NF}' file
example.
line.
file.
To get the result in one line as in your example, try:
{
sub(/\./, ",", $NF)
str = str$NF
}
END { print str }
output:
$ awk -f script.awk file
example, line, file,
Pure bash:
$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.
First is correct way of checking whether a field value is null
while later won't work the way you expect it to because null
is special value which does not equal anything, so you can't use equality comparison using =
for it.
So when you need to check if a field value is null
or not, use:
where x is null
instead of:
where x = null
Here's my solution for a notification module I built some time ago. It returns output similar to Facebook's notifications dropdown (eg. 1 day ago, Just now, etc).
public function getTimeDifference($time) {
//Let's set the current time
$currentTime = date('Y-m-d H:i:s');
$toTime = strtotime($currentTime);
//And the time the notification was set
$fromTime = strtotime($time);
//Now calc the difference between the two
$timeDiff = floor(abs($toTime - $fromTime) / 60);
//Now we need find out whether or not the time difference needs to be in
//minutes, hours, or days
if ($timeDiff < 2) {
$timeDiff = "Just now";
} elseif ($timeDiff > 2 && $timeDiff < 60) {
$timeDiff = floor(abs($timeDiff)) . " minutes ago";
} elseif ($timeDiff > 60 && $timeDiff < 120) {
$timeDiff = floor(abs($timeDiff / 60)) . " hour ago";
} elseif ($timeDiff < 1440) {
$timeDiff = floor(abs($timeDiff / 60)) . " hours ago";
} elseif ($timeDiff > 1440 && $timeDiff < 2880) {
$timeDiff = floor(abs($timeDiff / 1440)) . " day ago";
} elseif ($timeDiff > 2880) {
$timeDiff = floor(abs($timeDiff / 1440)) . " days ago";
}
return $timeDiff;
}
According to the manual this should work:
Custom key/value method:
You can include an operator in the first parameter in order to control the comparison:
$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45
Search for $this->db->where();
and look at item #2.
One way(in one line) to do it is like this:
listemail.Add(new EmailData {FirstName = "John", LastName = "Smith", Location = "Los Angeles"});
Code coverage tools, such as Emma, Cobertura, and Clover, will instrument your code and record which parts of it gets invoked by running a suite of tests. This is very useful, and should be an integral part of your development process. It will help you identify how well your test suite covers your code.
However, this is not the same as identifying real dead code. It only identifies code that is covered (or not covered) by tests. This can give you false positives (if your tests do not cover all scenarios) as well as false negatives (if your tests access code that is actually never used in a real world scenario).
I imagine the best way to really identify dead code would be to instrument your code with a coverage tool in a live running environment and to analyse code coverage over an extended period of time.
If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.
I have never personally seen this done, and do not know how the aforementioned tools can be used to instrument and analyse code that is not being invoked through a test suite - but I am sure they can be.
I did it like this
var owner = new Form { TopMost = true };
Task.Delay(30000).ContinueWith(t => {
owner.Invoke(new Action(()=>
{
if (!owner.IsDisposed)
{
owner.Close();
}
}));
});
var dialogRes = MessageBox.Show(owner, msg, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden
is used for visibility
Change the date range to "General" format and save the workbook once, and change them back to date format (eg, numberformat = "d/m/yyyy"
) before save & close the book. savechanges
parameter is true.
Resurrecting a very old thread yet again, since none of the answers here worked very well for me.
I found a simple way that seems pretty robust and simple. It worked for me. The idea:
Example:
static class Program
{
[DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AllocConsole();
[DllImport( "kernel32", SetLastError = true )]
static extern bool AttachConsole( int dwProcessId );
static void Main(string[] args)
{
bool consoleMode = Boolean.Parse(args[0]);
if (consoleMode)
{
if (!AttachConsole(-1))
AllocConsole();
Console.WriteLine("consolemode started");
// ...
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
A word of caution : it seems that if you try writing to the console prior to attaching or allocing a console, this approach doesn't work. My guess is the first time you call Console.Write/WriteLine, if there isn't already a console then Windows automatically creates a hidden console somewhere for you. (So perhaps Anthony's ShowConsoleWindow answer is better after you've already written to the console, and my answer is better if you've not yet written to the console). The important thing to note is that this doesn't work:
static void Main(string[] args)
{
Console.WriteLine("Welcome to the program"); //< this ruins everything
bool consoleMode = Boolean.Parse(args[0]);
if (consoleMode)
{
if (!AttachConsole(-1))
AllocConsole();
Console.WriteLine("consolemode started"); //< this doesn't get displayed on the parent console
// ...
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
$result = mysql_query($query) or die("Data not found.");
$rows=array();
while($r=mysql_fetch_assoc($result))
{
$rows[]=$r;
}
header("Content-type:application/json");
echo json_encode($rows);
This project has been tested with Xcode 10 and Swift 4.2.
It can be just a Single View App.
Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell
. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
}
We will connect this outlet later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
Notes
UICollectionViewDataSource
and UICollectionViewDelegate
are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout
protocol to change the size of the views programmatically, but it isn't necessary.Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.
Make sure that your defaults in the Attribute Inspector are also
The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.
Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell"
in ViewController.swift.
And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell
, our custom class that we made.
myLabel
in the MyCollectionViewCell
class. (You can Control-drag.)delegate
and dataSource
to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.
The example above works but it is rather ugly. Here are a few things you can play with:
Background color
In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.
Cell spacing
Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.
Cell shape
If you want rounded corners, a border, and the like, you can play around with the cell layer
. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan
in code above.
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
See this answer for other things you can do with the layer (shadow, for example).
Changing the color when tapped
It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController
class:
// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.cyan
}
Here is the updated look:
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
This works in Hibernate 4(Tested).
String hql="select count(*) from Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;
Where getCurrentSession() is:
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
Use this:
function get_millis(){
list($usec, $sec) = explode(' ', microtime());
return (int) ((int) $sec * 1000 + ((float) $usec * 1000));
}
Bye
In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.
--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
SELECT *
FROM dbo.SYSOBJECTS
WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
@StartDate DATETIME,
@EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
--Declare local variables
--Temporarily holds @EndDate during date reversal.
DECLARE @Swap DATETIME
--If the Start Date is null, return a NULL and exit.
IF @StartDate IS NULL
RETURN NULL
--If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
IF @EndDate IS NULL
SELECT @EndDate = @StartDate
--Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
--Usually faster than CONVERT.
--0 is a date (01/01/1900 00:00:00.000)
SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
@EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)
--If the inputs are in the wrong order, reverse them.
IF @StartDate > @EndDate
SELECT @Swap = @EndDate,
@EndDate = @StartDate,
@StartDate = @Swap
--Calculate and return the number of workdays using the input parameters.
--This is the meat of the function.
--This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
RETURN (
SELECT
--Start with total number of days including weekends
(DATEDIFF(dd,@StartDate, @EndDate)+1)
--Subtact 2 days for each full weekend
-(DATEDIFF(wk,@StartDate, @EndDate)*2)
--If StartDate is a Sunday, Subtract 1
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
THEN 1
ELSE 0
END)
--If EndDate is a Saturday, Subtract 1
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
THEN 1
ELSE 0
END)
)
END
GO
If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.
Manually wrapping in BytesIO is no longer needed since PIL >= 2.8.0. Just use Image.open(response.raw)
Adding on top of Vinícius's comment:
You should pass stream=True
as noted https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content
So
img = Image.open(requests.get(url, stream=True).raw)
For those who are getting the error as:
I/O error on POST request for "anothermachine:31112/url/path";: class path
resource [fileName.csv] cannot be resolved to URL because it does not exist.
It can be resolved by using the
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
If the file is not present in the classpath, and an absolute path is required.
This code:
$monthly_index = array_shift(unpack('H*', date('m/Y')));
Need to be changed into:
$date_time = date('m/Y');
$unpack = unpack('H*', $date_time);
array_shift($unpack);
If you:
git push origin master
it will push to the bare repo.
It sounds like your alice repo isn't tracking correctly.
cat .git/config
This will show the default remote and branch.
If you
git push -u origin master
You should start tracking that remote and branch. I'm not sure if that option has always been in git.
In essence its job is very similar to IEnumerable<T>
- to represent a queryable data source - the difference being that the various LINQ methods (on Queryable
) can be more specific, to build the query using Expression
trees rather than delegates (which is what Enumerable
uses).
The expression trees can be inspected by your chosen LINQ provider and turned into an actual query - although that is a black art in itself.
This is really down to the ElementType
, Expression
and Provider
- but in reality you rarely need to care about this as a user. Only a LINQ implementer needs to know the gory details.
Re comments; I'm not quite sure what you want by way of example, but consider LINQ-to-SQL; the central object here is a DataContext
, which represents our database-wrapper. This typically has a property per table (for example, Customers
), and a table implements IQueryable<Customer>
. But we don't use that much directly; consider:
using(var ctx = new MyDataContext()) {
var qry = from cust in ctx.Customers
where cust.Region == "North"
select new { cust.Id, cust.Name };
foreach(var row in qry) {
Console.WriteLine("{0}: {1}", row.Id, row.Name);
}
}
this becomes (by the C# compiler):
var qry = ctx.Customers.Where(cust => cust.Region == "North")
.Select(cust => new { cust.Id, cust.Name });
which is again interpreted (by the C# compiler) as:
var qry = Queryable.Select(
Queryable.Where(
ctx.Customers,
cust => cust.Region == "North"),
cust => new { cust.Id, cust.Name });
Importantly, the static methods on Queryable
take expression trees, which - rather than regular IL, get compiled to an object model. For example - just looking at the "Where", this gives us something comparable to:
var cust = Expression.Parameter(typeof(Customer), "cust");
var lambda = Expression.Lambda<Func<Customer,bool>>(
Expression.Equal(
Expression.Property(cust, "Region"),
Expression.Constant("North")
), cust);
... Queryable.Where(ctx.Customers, lambda) ...
Didn't the compiler do a lot for us? This object model can be torn apart, inspected for what it means, and put back together again by the TSQL generator - giving something like:
SELECT c.Id, c.Name
FROM [dbo].[Customer] c
WHERE c.Region = 'North'
(the string might end up as a parameter; I can't remember)
None of this would be possible if we had just used a delegate. And this is the point of Queryable
/ IQueryable<T>
: it provides the entry-point for using expression trees.
All this is very complex, so it is a good job that the compiler makes it nice and easy for us.
For more information, look at "C# in Depth" or "LINQ in Action", both of which provide coverage of these topics.
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
ul {
list-style-type: none;
}
ul li:before {
content:'*'; /* Change this to unicode as needed*/
width: 1em !important;
margin-left: -1em;
display: inline-block;
}
I need to see your submit button html tag for better help. I am not familiar with php and how it handles the postback, but I guess depending on what you want to do, you have three options:
onclick
button on the client-side: In this case you only need to call a javascript function.function foo() {_x000D_
alert("Submit button clicked!");_x000D_
return true;_x000D_
}
_x000D_
<input type="submit" value="submit" onclick="return foo();" />
_x000D_
If you want to handle the click on the server-side, you should first make sure that the form tag method attribute is set to post
:
<form method="post">
You can use onsubmit
event from form
itself to bind your function to it.
<form name="frm1" method="post" onsubmit="return greeting()">_x000D_
<input type="text" name="fname">_x000D_
<input type="submit" value="Submit">_x000D_
</form>
_x000D_
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
Place the link location in the action=""
of a wrapping form
tag.
Your first link would be:
<form action="1.html">
<input type="submit" class="button_active" value="1">
</form>
You could simply create a method to get the object by it's name.
public Party getPartyByName(String name) {
for(Party party : parties) {
if(name.equalsIgnoreCase(party.name)) {
return party;
}
}
return null;
}
Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.
Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.
In my particular case, I am using Babylon.js to create a 3D scene and my whole page consists of one full screen canvas. The 3D engine has its own zooming functionality but on iOS the pinch-to-zoom interferes with that. I updated the the @Joseph answer to overcome my problem. To disable it, I figured out that I need to pass the {passive: false} as an option to the event listener. The following code works for me:
window.addEventListener(
"touchmove",
function(event) {
if (event.scale !== 1) {
event.preventDefault();
}
},
{ passive: false }
);
I had to COPY
and untar java package in my docker image.
When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz
This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!
You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected
<?php
echo $htmlHeader;
while($stuff){
echo $stuff;
}
echo "<script>window.location = 'http://www.yourdomain.com'</script>";
?>
There are many articles about writing code to import an excel file, but this is a manual/shortcut version:
If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.
The quickest way to get your Excel file into SQL is by using the import wizard:
The next window is 'Choose a Data Source', select Excel:
In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).
Click the 'Browse' button to select the path to the Excel file you want to import.
On the 'Specify Table Copy or Query' window:
'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.
I'm using GIMP 2.8.1. I hope this will work for you:
Open the "Windows" menu and select "Single-Window Mode".
Simple ;)
Use a cast:
public enum MyEnum : int {
A = 0,
B = 1,
AB = 2,
}
int val = (int)MyEnum.A;
Both these work for me. Maybe post a complete example?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PaneBackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox vbox = new VBox();
root.setCenter(vbox);
ToggleButton toggle = new ToggleButton("Toggle color");
HBox controls = new HBox(5, toggle);
controls.setAlignment(Pos.CENTER);
root.setBottom(controls);
// vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
// .then("-fx-background-color: cornflowerblue;")
// .otherwise("-fx-background-color: white;"));
vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
.then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
.otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I'd use
files=(*)
And then if you need data about the file, such as size, use the stat
command on each file.
In case anyone is wondering how to use Marionette in C#.
FirefoxProfile profile = new FirefoxProfile(); // Your custom profile
var service = FirefoxDriverService.CreateDefaultService("DirectoryContainingTheDriver", "geckodriver.exe");
// Set the binary path if you want to launch the release version of Firefox.
service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
var option = new FirefoxProfileOptions(profile) { IsMarionette = true };
var driver = new FirefoxDriver(
service,
option,
TimeSpan.FromSeconds(30));
Overriding FirefoxOptions to provide the function to add additional capability and set Firefox profile because selenium v53 doesn't provide that function yet.
public class FirefoxProfileOptions : FirefoxOptions
{
private DesiredCapabilities _capabilities;
public FirefoxProfileOptions()
: base()
{
_capabilities = DesiredCapabilities.Firefox();
_capabilities.SetCapability("marionette", this.IsMarionette);
}
public FirefoxProfileOptions(FirefoxProfile profile)
: this()
{
_capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile.ToBase64String());
}
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
_capabilities.SetCapability(capabilityName, capabilityValue);
}
public override ICapabilities ToCapabilities()
{
return _capabilities;
}
}
Note: Launching with profile doesn't work with FF 47, it works with FF 50 Nightly.
However, we tried to convert our test to use Marionette, and it's just not viable at the moment because the implementation of the driver is either not completed or buggy. I'd suggest people downgrade their Firefox at this moment.
You might find the Semantic Versioning Specification useful.
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:
[bits 32]
.
.
and [ebp-4], 0
You can use this awesome library to compress. Add dependency in app-level gradel:
dependencies {
implementation 'id.zelory:compressor:3.0.0'
}
And then just compress the actual image file like this:
val compressedImageFile = Compressor.compress(context, actualImageFile)
I had a button where the background-image
had a shadow below it so the text alignment was off from the top. Changing the line-height
wouldn't help. I added padding-bottom
to it and it worked.
So what you have to do is determine the line-height
you want to play with. So, for example, if I have a button who's height is truly 90px
but I want the line-height to be 80px
I would have something like this:
input[type=butotn].mybutton{
background: url(my/image.png) no-repeat center top; /*Image is 90px x 150px*/
width: 150px;
height: 80px; /*shadow at the bottom is 10px (90px-10px)*/
padding-bottom: 10px; /*the padding will make up for the lost height while maintaining the line-height to the proper height */
}
I hope this helps.
I spent too much time to figure out this problem for me.
I had PHP version 5.5 and I needed to upgrade to 5.6.
In versions < 5.6 Guzzle will use it's own cacert.pem file, but in higher versions of PHP it will use system's cacert.pem file.
I also downloaded file from here https://curl.haxx.se/docs/caextract.html and set it in php.ini.
Answer found in Guzzles StreamHandler.php file https://github.com/guzzle/guzzle/blob/0773d442aa96baf19d7195f14ba6e9c2da11f8ed/src/Handler/StreamHandler.php#L437
// PHP 5.6 or greater will find the system cert by default. When // < 5.6, use the Guzzle bundled cacert.
You can also use CURRENT_TIMESTAMP
for this.
According to BOL CURRENT_TIMESTAMP
is the ANSI SQL
euivalent to GETDATE()
DECLARE @LastChangeDate AS DATE;
SET @LastChangeDate = CURRENT_TIMESTAMP;
Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:
Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.
You can however use pointers to allocate a 'block' of memory, for example like this:
int *some_integers = new int[20000]
This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.
Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:
delete [] some_integers;
Hope that helps.
For me didn't work any from the above solutions and below it is what worked (I had already checked out Parallelize Build
and added React
)
1. Open XCode --> To Libraries add `$LibraryWhichDoesNotWork.xcodeproj$`
2. Then for your app in the `Build Phases` add to the `Link Binary with Libraries` the file `lib$LibraryWhichDoesNotWork$.a`
This should do the trick:
import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine
# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')
# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get
function with the textvariable you had set.
Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >>
method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.
First let's generate a nice filename, but that's really just for being pedantic:
$name = "sync_common"
$currdate = get-date -f yyyy-MM-dd
$logfile = "c:\scripts\$name\log\$name-$currdate.txt"
And here's where the trick begins:
start-transcript -append -path $logfile
write-output "starting sync"
robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
some_other.exe /exeparams 2>&1 | Write-Output
...
write-output "ending sync"
stop-transcript
With start-transcript
and stop-transcript
you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.
In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.
Either way, running every single command with start-process
is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output
code to each line which runs external commands.
Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.
If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.
@import "foo/*" // import all the files in the foo folder
@import "bar/**/*" // import all the files in the bar tree
To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."
Some would argue that organizing your files into directories can REDUCE complexity.
My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.
To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.
Suppose this is your file structure:
/BulutDepoProject
/bin
Main.exe
/FolderIcon
Folder.ico
Main.cs
You need to write your path relative to the Main.exe
file. So, you want to access Folder.ico
, in your Main.cs
you can use:
String path = "..\\FolderIcon\\Folder.ico"
That seemed to work for me!
In my case the problem was the JAVA_HOME variable was set an installed jre.
An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
public class VerticalItemDecoration extends RecyclerView.ItemDecoration {
private boolean verticalOrientation = true;
private int space = 10;
public VerticalItemDecoration(int value, boolean verticalOrientation) {
this.space = value;
this.verticalOrientation = verticalOrientation;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
//skip first item in the list
if (parent.getChildAdapterPosition(view) != 0) {
if (verticalOrientation) {
outRect.set(space, 0, 0, 0);
} else if (!verticalOrientation) {
outRect.set(0, space, 0, 0);
}
}
}
}
mCompletedShippingRecyclerView.addItemDecoration(new VerticalItemDecoration(20,false));
For what it is worth, I tried all the solutions in this question and in this related question and none resolved my issue until I uninstalled and re-installed VirtualBox. This process upgraded the VirtualBox from version 4.2.16 to 4.3.22 (my previous one had been lying unused on the system for a few months).
Then boot2docker
and docker
worked without any other adjustments.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
The app that contains the custom tags must be in INSTALLED_APPS
. So Are you sure that your directory is in INSTALLED_APPS
?
From the documentation:
The app that contains the custom tags must be in
INSTALLED_APPS
in order for the{% load %}
tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.
To explain in common usecase/purpose or layman way:
TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.
keyStore : Used to store the server keys (both public and private) along with signed cert.
During the SSL handshake,
A client tries to access https://
And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)
Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?
Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.
Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS
If you want to replace the existing database completely use the WITH REPLACE option:
RESTORE DATABASE <YourDatabase>
FROM DISK='<the path to your backup file>\<YourDatabase>.bak'
WITH REPLACE
I know this question is old but the accepted answer does not work anymore and since this is the fist link on google search i'll tell how i solved this problem.
for eclipse using ubuntu:
go to Window->Preferences->Ant->Runtime->Select Ant_Home_Entries and click on add external jars then find in file explorer where your jdk is (default is in /usr/lib/jvm/) and in the lib folder of your jdk you will find the tool.jar. select this one and click apply.
try to build your project and things should work!
note: i hadn't used ant for a long time but needed it for ycsb couchbase workload generator (http://www.couchbase.com/wiki/display/couchbase/Load+Generator+Setup) if anyone is/was stuck on this.
Also, just would like to add here that just because any other OO language has some kind of interfaces and abstraction too doesn't mean they have the same meaning and purpose as in PHP. The use of abstraction/interfaces is slightly different while interfaces in PHP actually don't have a real function. They merely are used for semantic and scheme-related reasons. The point is to have a project as much flexible as possible, expandable and safe for future extensions regardless whether the developer later on has a totally different plan of use or not.
If your English is not native you might lookup what Abstraction and Interfaces actually are. And look for synonyms too.
And this might help you as a metaphor:
INTERFACE
Let's say, you bake a new sort of cake with strawberries and you made up a recipe describing the ingredients and steps. Only you know why it's tasting so well and your guests like it. Then you decide to publish your recipe so other people can try that cake as well.
The point here is
- to make it right
- to be careful
- to prevent things which could go bad (like too much strawberries or something)
- to keep it easy for the people who try it out
- to tell you how long is what to do (like stiring)
- to tell which things you CAN do but don't HAVE to
Exactly THIS is what describes interfaces. It is a guide, a set of instructions which observe the content of the recipe. Same as if you would create a project in PHP and you want to provide the code on GitHub or with your mates or whatever. An interface is what people can do and what you should not. Rules that hold it - if you disobey one, the entire construct will be broken.
ABSTRACTION
To continue with this metaphor here... imagine, you are the guest this time eating that cake. Then you are trying that cake using the recipe now. But you want to add new ingredients or change/skip the steps described in the recipe. So what comes next? Plan a different version of that cake. This time with black berries and not straw berries and more vanilla cream...yummy.
This is what you could consider an extension of the original cake. You basically do an abstraction of it by creating a new recipe because it's a lil different. It has a few new steps and other ingredients. However, the black berry version has some parts you took over from the original - these are the base steps that every kind of that cake must have. Like ingredients just as milk - That is what every derived class has.
Now you want to exchange ingredients and steps and these MUST be defined in the new version of that cake. These are abstract methods which have to be defined for the new cake, because there should be a fruit in the cake but which? So you take the black berries this time. Done.
There you go, you have extended the cake, followed the interface and abstracted steps and ingredients from it.
The right way to do this is simple:
def rate(T):
if (T > 200):
return 200*exp(-T)
else:
return 400*exp(-T)
There is absolutely no advantage to using lambda
here. The only thing lambda
is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda
to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.
The rate
function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).
From a comment:
Well the function needed to fit in one line, which i didn't think you could do with a named function?
I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:
>>> def foo(x): return x + 1
Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.
Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval
so you can use them, you actually just want to pass Python functions around as functions and use them as functions.
But on the off chance that this really is what you need here: Just use exec
instead of eval
.
You didn't mention which version of Python you're using. In 3.x, the exec
function has the exact same signature as the eval
function:
exec(my_function_string, my_globals, my_locals)
In 2.7, exec
is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.
In earlier 2.x (before 2.6, I think?) you have to do it like this instead:
exec my_function_string in my_globals, my_locals
To override the error that you might experience in Chrome (and probably in Safari), try to set the Ajax parameter as dataType: "json"
. Then you shouldn't call parseJSON()
on the obj
because the response you'll get comes deserialized.
If you don't want to save method into jQuery.fn you can use
[].reverse.call($('li'));
Use the PHP function serialize()
to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize()
they can be converted to arrays again if needed.
Given a String str:
str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
@Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
Functional requirements specifies a function that a system or system component must be able to perform. It can be documented in various ways. The most common ones are written descriptions in documents, and use cases.
Use cases can be textual enumeration lists as well as diagrams, describing user actions. Each use case illustrates behavioural scenarios through one or more functional requirements. Often, though, an analyst will begin by eliciting a set of use cases, from which the analyst can derive the functional requirements that must be implemented to allow a user to perform each use case.
Functional requirements is what a system is supposed to accomplish. It may be
A typical functional requirement will contain a unique name and number, a brief summary, and a rationale. This information is used to help the reader understand why the requirement is needed, and to track the requirement through the development of the system.
LBushkin have already explained more about Non-functional requirements. I will add more.
Non-functional requirements are any other requirement than functional requirements. This are the requirements that specifies criteria that can be used to judge the operation of a system, rather than specific behaviours.
Non-functional requirements are in the form of "system shall be ", an overall property of the system as a whole or of a particular aspect and not a specific function. The system's overall properties commonly mark the difference between whether the development project has succeeded or failed.
Non-functional requirements - can be divided into two main categories:
- Performance requirements
- Interface requirements
- Operational requirements
- Resource requirements
- Verification requirements
- Acceptance requirements
- Documentation requirements
- Security requirements
- Portability requirements
- Quality requirements
- Reliability requirements
- Maintainability requirements
- Safety requirements
Whether or not a requirement is expressed as a functional or a non-functional requirement may depend:
Ex. A system may be required to present the user with a display of the number of records in a database. This is a functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the number needs to be updated in real time, the system architects must ensure that the system is capable of updating the [displayed] record count within an acceptably short interval of the number of records changing.
References:
Based on the the8472 answer and https://developer.mozilla.org/en-US/docs/Web/API/Element/matches here is cross-platform 2017 solution:
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
function findAncestor(el, sel) {
if (typeof el.closest === 'function') {
return el.closest(sel) || null;
}
while (el) {
if (el.matches(sel)) {
return el;
}
el = el.parentElement;
}
return null;
}
More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:
if conditionX:
print('yes')
else:
print('nah')
, becomes:
print('yes') if conditionX else print('nah')
Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.
You need to isntall pdo_pgsql package
This is how a snapshot looks like for a repository and in this case is not enabled, which means that the repository referred in here is stable and there's no need for updates.
<project>
...
<repositories>
<repository>
<id>lds-main</id>
<name>LDS Main Repo</name>
<url>http://code.lds.org/nexus/content/groups/main-repo</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
Another case would be for:
<snapshots>
<enabled>true</enabled>
</snapshots>
which means that Maven will look for updates for this repository. You can also specify an interval for the updates with tag.
The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.
static class Program
{
public static string globalString = "This is a global string.";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
And use it as such:
public partial class Form1 : Form
{
public Form1()
{
Program.globalString = "Accessible in Form1.";
InitializeComponent();
}
}
Another potential use is as an alternative to stashing (which some people don't like, see e.g. https://codingkilledthecat.wordpress.com/2012/04/27/git-stash-pop-considered-harmful/).
For example, if I'm working on a branch and need to fix something urgently on master, I can just do:
git commit -am "In progress."
then checkout master and do the fix. When I'm done, I return to my branch and do
git reset --soft HEAD~1
to continue working where I left off.
Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.
CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.
I don't think you can skip rows in a different format with BULK INSERT
/BCP
.
When I run this:
TRUNCATE TABLE so1029384
BULK INSERT so1029384
FROM 'C:\Data\test\so1029384.txt'
WITH
(
--FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)
SELECT * FROM so1029384
I get:
col1 col2 col3
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
***A NICE HEADER HERE***
0000001234 SSNV 00013893-03JUN09
0000005678 ABCD 00013893-03JUN09
0000009112 0000 00013893-03JUN09
0000009112 0000 00013893-03JUN09
It looks like it requires the '|' even in the header data, because it reads up to that into the first column - swallowing up a newline into the first column. Obviously if you include a field terminator parameter, it expects that every row MUST have one.
You could strip the row with a pre-processing step. Another possibility is to select only complete rows, then process them (exluding the header). Or use a tool which can handle this, like SSIS.
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
These are all informative answers, but none are quite getting at the core of what the difference is between %s
and %d
.
%s
tells the formatter to call the str()
function on the argument and since we are coercing to a string by definition, %s
is essentially just performing str(arg)
.
%d
on the other hand, is calling int()
on the argument before calling str()
, like str(int(arg))
, This will cause int
coercion as well as str
coercion.
For example, I can convert a hex value to decimal,
>>> '%d' % 0x15
'21'
or truncate a float.
>>> '%d' % 34.5
'34'
But the operation will raise an exception if the argument isn't a number.
>>> '%d' % 'thirteen'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
So if the intent is just to call str(arg)
, then %s
is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.
With the f-string
notation, when you leave the formatter out, the default is str
.
>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
The same is true with string.format
; the default is str
.
>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'
In newer versions of phpMyAdmin access permissions for user-names + ip-addresses can be set up inside the phpMyAdmin's config.inc.php file. This is a much better and more robust method of restricting access (over hard-coding URLs and IP addresses into Apache's httpd.conf).
Here is a full example of how to switch to white-listing all users (no one outside this list will be allowed access), and also how to restrict user root to the local system and network only.
$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
'deny % from all', // deny everyone by default, then -
'allow % from 127.0.0.1', // allow all local users
'allow % from ::1',
//'allow % from SERVER_ADDRESS', // allow all from server IP
// allow user:root access from these locations (local network)
'allow root from localhost',
'allow root from 127.0.0.1',
'allow root from 10.0.0.0/8',
'allow root from 172.16.0.0/12',
'allow root from 192.168.0.0/16',
'allow root from ::1',
// add more usernames and their IP (or IP ranges) here -
);
Source: How to Install and Secure phpMyAdmin on localhost for Windows
This gives you much more fine-grained access restrictions than Apache's URL permissions or an .htaccess file can provide, at the MySQL user name level.
Make sure that the user you are login in with, has its MySQL Host:
field set to 127.0.0.1
or ::1
, as phpMyAdmin and MySQL are on the same system.
Add a backward slash in FIELDS TERMINATED BY '\;'
For Example:
CREATE TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;
I have tested it, and it worked.
DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.
That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.
DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.
RIGHT: SELECT DISTINCT foo, ticket_id FROM table...
Output a row for each distinct pairing of values across ticket_id and foo.
WRONG: SELECT foo, DISTINCT ticket_id FROM table...
If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
It's ambiguous as written.
You need to do two additional things after following the link that you have mentioned in your post:
One have to map the changed login cridentials in phpmyadmin's config.inc.php
and second, you need to restart your web and mysql servers..
php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php
and in that file put your current mysql password at line
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here
Given
l1 = [a,b]
l2 = [b,a]
assertCountEqual(l1, l2) # True
In Python >= 2.7, the above function was named:
assertItemsEqual(l1, l2) # True
import unittest2
assertItemsEqual(l1, l2) # True
Via six
module (Any Python version)
import unittest
import six
class MyTest(unittest.TestCase):
def test(self):
six.assertCountEqual(self, self.l1, self.l2) # True
Talking about functional PHP, I have this more generic answer:
array_map(function($arr){
$ret = $arr;
$ret['value'] = $ret['url'];
unset($ret['url']);
return $ret;
}, $tag);
}
I add an answer because I think a one line solution is always good!
Atop of your myRscript.R
file, add the following line:
eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))
Then submit your script with something like:
R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &
For example:
R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &
Then:
> ls()
[1] "N" "l" "name"
Follow the steps mentioned for using support ActionBar in Android Studio(0.4.2) :
Download the Android Support Repository from Android SDK Manager, SDK Manager icon will be available on Android Studio tool bar (or Tools -> Android -> SDK Manager
).
After download you will find your Support repository here
$SDK_DIR\extras\android\m2repository\com\android\support\appcompat-v7
Open your main module's build.gradle file and add following dependency for using action bar in lower API level
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Sync your project with gradle using the tiny Gradle icon available in toolbar (or Tools -> Android -> Sync Project With Gradle Files
).
There is some issue going on with Android Studio 0.4.2 so check this as well if you face any issue while importing classes in code.
Import Google Play Services library in Android Studio
If Required follow the steps as well :
This is bug in Android Studio 0.4.2 and fixed for Android Studio 0.4.3 release.
Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.
Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.
Try using now.date()
to get a Date
object rather than a DateTime
.
If that doesn't work, then converting that to a string should work:
now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Here is a condensed replacement for the ConvertToLetter function that in theory should work for all possible positive integers. For example, 1412 produces "BBH" as the result.
Public Function ColumnNumToStr(ColNum As Integer) As String
Dim Value As Integer
Dim Rtn As String
Rtn = ""
Value = ColNum - 1
While Value > 25
Rtn = Chr(65 + (Value Mod 26)) & Rtn
Value = Fix(Value / 26) - 1
Wend
Rtn = Chr(65 + Value) & Rtn
ColumnNumToStr = Rtn
End Function
This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
You specified both jQuery and Javascript in the tags so here's both approaches.
jQuery
var selector = '.nav li';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/
Pure Javascript:
var selector, elems, makeActive;
selector = '.nav li';
elems = document.querySelectorAll(selector);
makeActive = function () {
for (var i = 0; i < elems.length; i++)
elems[i].classList.remove('active');
this.classList.add('active');
};
for (var i = 0; i < elems.length; i++)
elems[i].addEventListener('mousedown', makeActive);
Fiddle: http://jsfiddle.net/rn3nc/1
jQuery with event delegation:
Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new li
s to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav
:
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/1/
The subtle difference is that the handler is bound to the .nav
now, so when you click the li
the event bubbles up the DOM to the .nav
which invokes the handler if the element clicked matches your selector
argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.
It's really quite interesting. Read more about it here: http://api.jquery.com/on/
gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo"
and #include <zap>
will search on your system, I recommend:
$ touch a.c
$ gcc -v -E a.c
...
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/lib/gcc/i686-apple-darwin9/4.0.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"
This is one way to see the search lists for included files, including (if any) directories into which #include "..."
will look but #include <...>
won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ...
here;-) on any system on which gcc runs properly.
Derek's answer above didn't work for me. I am using VS 2013 Ultimate and after signing out of Visual Studio, when i tried to sign in as another user, it gave error.
Then when connecting to the Team Project i saw the option to switch user, which is what i wanted all along.
You need to give relative
or absolute
or fixed
positioning to your container (#shop
) and set its zIndex
to say 100.
You also need to give say relative
positioning to your elements with the class content
and lower zIndex
say 97.
Do the above-mentioned with your images too and set their zIndex
to 91.
And then position your button higher by setting its position to absolute
and zIndex
to 95
See the DEMO
HTML
<div id="shop">
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
</div>
CSS
#shop{
background-image: url("images/shop_bg.png");
background-repeat: repeat-x;
height:121px;
width: 984px;
margin-left: 20px;
margin-top: 13px;
position:relative;
z-index:100
}
#shop .content{
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
z-index:97
}
img{
position:relative;
z-index:91
}
.span{
width:70px;
height:40px;
border:1px solid red;
position:absolute;
z-index:95;
right:60px;
bottom:-20px;
}
To get a copy in a file on the local file-system, this rickety utility from the Windows start button menu worked: "C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe"
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "ok";
}
A solution using DateTime
(that also regards the timezone).
$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
echo "OK";
}
Yes, you can do a 3 table join for an update statement. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
Use this code to add years or months or days or hours or minutes or seconds to a given date
echo date("Y-m-d H:i:s", strtotime("+1 years", strtotime('2014-05-22 10:35:10'))); //2015-05-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 months", strtotime('2014-05-22 10:35:10')));//2014-06-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 days", strtotime('2014-05-22 10:35:10')));//2014-05-23 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 hours", strtotime('2014-05-22 10:35:10')));//2014-05-22 11:35:10
echo date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:36:10
echo date("Y-m-d H:i:s", strtotime("+1 seconds", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:35:11
You can also subtract replacing + to -
To position the datepicker next to the input field you could use following code.
$('#datepicker').datepicker({
beforeShow: function(input, inst)
{
inst.dpDiv.css({marginLeft: input.offsetWidth + 'px'});
}
});
I am not able to run my own build on the other suggestions here. I even tried different versions of maven-compiler-plugin: 3.1, 3.7.0, etc.
I made it work adding this:
<testSourceDirectory>/src/test/java</testSourceDirectory>
I tried this approach because it seems like the /src/test/java directory is considered a java class that is why it is compiled the same time as /src/test/java. So my hunch were right in my case.
Maybe it is to others too, so just try this one.
Prior to PHP 5.5, the the PHP docs used to say:
empty() only checks variables as anything else will result in a parse error
In PHP < 5.5 you weren't able use empty()
directly on a function's return value. Instead, you could assign the return from getError()
to a variable and run empty()
on the variable.
In PHP >= 5.5 this is no longer necessary.
To Change Button title:
[mybtn setTitle:@"My Button" forState:UIControlStateNormal];
[mybtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
For Disable:
[mybtn setEnabled:NO];
You can achieve this by setting the android:noHistory
attribute to "true"
in the relevant <activity>
entries in your AndroidManifest.xml
file. For example:
<activity
android:name=".AnyActivity"
android:noHistory="true" />
Something like this, I think. find_if_counted.hpp
:
#ifndef FIND_IF_COUNTED_HPP
#define FIND_IF_COUNTED_HPP
#include <algorithm>
namespace find_if_counted_impl
{
template <typename Func>
struct func_counter
{
explicit func_counter(Func& func, unsigned &count) :
_func(func),
_count(count)
{
}
template <typename T>
bool operator()(const T& t)
{
++_count;
return _func(t);
}
private:
Func& _func;
unsigned& _count;
};
}
// generic find_if_counted,
// returns the index of the found element, otherwise returns find_if_not_found
const size_t find_if_not_found = static_cast<size_t>(-1);
template <typename InputIterator, typename Func>
size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
{
unsigned count = 0;
find_if_counted_impl::func_counter<Func> f(func, count);
InputIterator result = find_if(start, finish, f);
if (result == finish)
{
return find_if_not_found;
}
else
{
return count - 1;
}
}
#endif
Example:
#include "find_if_counted.hpp"
#include <cstdlib>
#include <iostream>
#include <vector>
typedef std::vector<int> container;
int rand_number(void)
{
return rand() % 20;
}
bool is_even(int i)
{
return i % 2 == 0;
}
int main(void)
{
container vec1(10);
container vec2(10);
std::generate(vec1.begin(), vec1.end(), rand_number);
std::generate(vec2.begin(), vec2.end(), rand_number);
unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);
if (index == find_if_not_found)
{
std::cout << "vec1 has no even numbers." << std::endl;
}
else
{
std::cout << "vec1 had an even number at index: " << index <<
" vec2's corresponding number is: " << vec2[index] << std::endl;
}
}
Though I feel like I'm doing something silly... :X Any corrections are welcome, of course.
I am giving it for Windows
If you are using python-3
py -m pip install --upgrade pip
py -m pip install <package-name>
If you are using python-2
py -2 -m pip install --upgrade pip
py -2 -m pip install <package-name>
It worked for me
On Linux it's Monospace
10 pt. (the exact monospace font used may vary on different Linux distributions or versions), on Windows it's Consolas
10 pt., and on OS X it's Menlo Regular
12 pt.
(The color scheme is Neon
, the syntax highlighting is from PackageDev
, and the font is Liberation Mono
This information is found in the Packages/Default
directory (where Packages
is the directory opened by the Preferences ? Browse Packages...
menu option), in the Preferences (OS).sublime-settings
file where OS
is one of Windows
, Linux
, or OSX
.
You should only customize the font (or any other setting) in Packages/User/Preferences.sublime-settings
, opened by Preferences ? Settings—User
, as Settings—Default
is over-written on upgrade, and also serves as a backup in case you really screw something up in your user settings. This is the case for both the main Sublime settings as well as those for extra packages/plugins.
These default fonts are the same in Sublime Text 2, Sublime Text 3, and the new version currently in development.