You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json
with the dns key, as
{
"dns": ["your_dns_address", "8.8.8.8"]
}
In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.
Before proceeding, save daemon.json and restart the docker service.
sudo service docker restart
Once fixed, retry to run the build command.
I am also facing same issue in Hortonworks
At the time I restart the Ambari agents and servers then the issue has been resolved.
systemctl stop ambari-agent
systemctl stop ambari-server
Source :Full Article With Resolution
systemctl start ambari-agent
systemctl start ambari-server
For those using JaVers, given an audited entity class, you may want to ignore the properties causing the LazyInitializationException
exception (e.g. by using the @DiffIgnore
annotation).
This tells the framework to ignore those properties when calculating the object differences, so it won't try to read from the DB the related objects outside the transaction scope (thus causing the exception).
I recommend to use bellow formula suggested on Apache:
MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)
Find my script here which is running on Rhel 6.7. you can made change according to your OS.
#!/bin/bash
echo "HostName=`hostname`"
#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit
Instead of using relative paths, you could also use the predefined macros of VS to achieve this.
$(ProjectDir)
points to the directory of your .vcproj
file, $(SolutionDir)
is the directory of the .sln
file.
You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:
In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):
You can use the Macros by typing $(MACRO_NAME)
(note the $
and the round brackets).
You should be able to uninstall it using sc.exe (I think it is included in the Windows Resource Kit) by running the following in an "administrator" command prompt:
sc.exe delete <service name>
where <service name>
is the name of the service itself as you see it in the service management console, not of the exe.
You can find sc.exe in the System folder and it needs Administrative privileges to run. More information in this Microsoft KB article.
Alternatively, you can directly call the DeleteService() api. That way is a little more complex, since you need to get a handle to the service control manager via OpenSCManager() and so on, but on the other hand it gives you more control over what is happening.
You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:
public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}
public int Method2(string input)
{
//... do something different
return 1;
}
public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
}
Use this plugin Moment Duration Format.
Example:
moment.duration(123, "minutes").format("h:mm");
It's not what the OP asked for (capturing groups) but you can extract the numbers using:
S='This is a sample 123 text and some 987 numbers'
echo "$S" | sed 's/ /\n/g' | sed -r '/([0-9]+)/ !d'
Gives the following:
123
987
You may also want to try two backslashes (\\")
to escape the escape character.
package main
import "encoding/json"
func main() {
in := []byte(`{ "votes": { "option_A": "3" } }`)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
raw["count"] = 1
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
println(string(out))
}
This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
jquery makes it easier:
$(document).on('click','#btnPrepend',function(){//do something})
Here is an article about event delegation event delegation article
Try this:
myList1 = myList1.Concat(myList2).ToList();
Concat returns an IEnumerable<T> that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List<T>, you'll have to call ToList() on the IEnumerable<T> that is returned.
I'm an Eclipse/Android beginner as well, but hopefully my simple debugging process can help...
You set breakpoints in Eclipse by right-clicking next to the line you want to break at and selecting "Toggle Breakpoint". From there you'll want to select "Debug" rather than the standard "Run", which will allow you to step through and so on. Use the filters provided by LogCat (referenced in your tutorial) so you can target the messages you want rather than wading through all the output. That will (hopefully) go a long way in helping you make sense of your errors.
As for other good tutorials, I was searching around for a few myself, but didn't manage to find any gems yet.
Just a tiny bit of info that might help others; if you do something along the lines of searching all assemblies in some directory for classes that inherit/implement classes/interfaces, then make sure you clean out stale assemblies if you get this error pertaining to one of your own assemblies.
The scenario would be something like:
In short: A ---loads--> B (stale) ---references---> C
If this happens, the only telltale sign is the namespace and classname in the error message. Examine it closely. If you can't find it anywhere in your solution, you are likely trying to load a stale assembly.
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark"
and the property in code is FirstName
then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
If it is disabled, go to Control Panel->Administrative Tools->Services, and look for the SQL Server Agent. Right-click, and select Properties From the Startup Type dropdown, change from Disabled to Automatic.
In standard Markdown, place an anchor <a name="abcd"></a>
where you want to link to and refer to it on the same page by [link text](#abcd)
.
(This uses name=
and not id=
, for reasons explained in this answer.)
Remote references can use [link text](http://...#abcd)
of course.
This works like a dream, provided you have control over the source and target texts. The anchor can even appear in a heading, thus:
### <a name="head1234"></a>A Heading in this SO entry!
produces:
and we can even link to it so:
and we can even [link](#head1234) to it so:
(On SO, the link doesn't work because the anchor is stripped.)
I've solved this problem by deleting the google-services.json file and downloading it again from Firebase console.
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.
Problem ->
Class A {
private final B b; // must initialize in ctor/instance block
public A(B b) { this.b = b };
}
Class B {
private final A a; // must initialize in ctor/instance block
public B(A a) { this.a = a };
}
// Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'A': Requested bean is currently in creation: Is there an unresolvable circular reference?
Solution 1 ->
Class A {
private B b;
public A( ) { };
//getter-setter for B b
}
Class B {
private A a;
public B( ) { };
//getter-setter for A a
}
Solution 2 ->
Class A {
private final B b; // must initialize in ctor/instance block
public A(@Lazy B b) { this.b = b };
}
Class B {
private final A a; // must initialize in ctor/instance block
public B(A a) { this.a = a };
}
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
Do not bind to a specific port. Instead, bind to port 0:
sock.bind(('', 0))
The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1]
, and pass it on to the slaves so that they can connect back.
Use shift method
array.shift(n) => Remove first n elements from array
array.shift(1) => Remove first element
You can try next code:
function unique_randoms($min, $max, $count) {
$arr = array();
while(count($arr) < $count){
$tmp =mt_rand($min,$max);
if(!in_array($tmp, $arr)){
$arr[] = $tmp;
}
}
return $arr;
}
In my case, everything was working properly then suddenly stopped worked because I think Resharper altered some changes which caused the problem. My project was divided into the data layer, service and presentation layer. I had Entity framework installed and referenced in my data layer but still the error didn't go away. Uninstalling and reinstalling didn't work either. Finally, I solved it by making the data layer the Startup project, making migration, updating the database and changing the Startup project back to my presentation layer.
gvim version: 8.2
location of .gvimrc: %userprofile%/.gvimrc
" .gvimrc
colorscheme darkblue
Which color is allows me to choose?
Find your install directory and go to the directory of colors
.
in my case is:
%PROGRAMFILES(X86)%\Vim\vim82\colors
blue.vim
darkblue.vim
slate.vim
...
README.txt
you can't make easisly a slideup slidedown with css3 tha's why I've turned JensT script into a plugin with javascript fallback and callback.
in this way if you have a modern brwowser you can use the css3 csstransition. if your browser does not support it gracefuly use the old fashioned slideUp slideDown.
/* css */
.csstransitions .mosneslide {
-webkit-transition: height .4s ease-in-out;
-moz-transition: height .4s ease-in-out;
-ms-transition: height .4s ease-in-out;
-o-transition: height .4s ease-in-out;
transition: height .4s ease-in-out;
max-height: 9999px;
overflow: hidden;
height: 0;
}
the plugin
(function ($) {
$.fn.mosne_slide = function (
options) {
// set default option values
defaults = {
delay: 750,
before: function () {}, // before callback
after: function () {} // after callback;
}
// Extend default settings
var settings = $.extend({},
defaults, options);
return this.each(function () {
var $this = $(this);
//on after
settings.before.apply(
$this);
var height = $this.height();
var width = $this.width();
if (Modernizr.csstransitions) {
// modern browsers
if (height > 0) {
$this.css(
'height',
'0')
.addClass(
"mosne_hidden"
);
} else {
var clone =
$this.clone()
.css({
'position': 'absolute',
'visibility': 'hidden',
'height': 'auto',
'width': width
})
.addClass(
'mosne_slideClone'
)
.appendTo(
'body'
);
var newHeight =
$(
".mosne_slideClone"
)
.height();
$(
".mosne_slideClone"
)
.remove();
$this.css(
'height',
newHeight +
'px')
.removeClass(
"mosne_hidden"
);
}
} else {
//fallback
if ($this.is(
":visible"
)) {
$this.slideUp()
.addClass(
"mosne_hidden"
);
} else {
$this.hide()
.slideDown()
.removeClass(
"mosne_hidden"
);
}
}
//on after
setTimeout(function () {
settings.after
.apply(
$this
);
}, settings.delay);
});
}
})(jQuery);;
how to use it
/* jQuery */
$(".mosneslide").mosne_slide({
delay:400,
before:function(){console.log("start");},
after:function(){console.log("done");}
});
you can find a demo page here http://www.mosne.it/playground/mosne_slide_up_down/
I've checked your source code and find to change to yellow you need to adds the yellow background color to : #left-padding, #right-padding, html, #hd, #main and #yui-main.
Hope it's what you wanted. See ya
Open the project you want to add it.
Right click on the name.
Then select, add in the active project.
Then the cpp
file will get its link to cbp
.
It is very simple. check for string empty condition in while condition.
You can use strlen function to check for the string length.
#include<stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (strlen(url)<=0);
return(0);
}
check first character is '\0'
#include <stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (url[0]=='\0');
return(0);
}
For your reference:
C arrays:
https://www.javatpoint.com/c-array
https://scholarsoul.com/arrays-in-c/
C strings:
https://www.programiz.com/c-programming/c-strings
https://scholarsoul.com/string-in-c/
https://en.wikipedia.org/wiki/C_string_handling
you want after days find date this code try..
public Date getToDateAfterDays(Integer day) {
Date nowdate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(nowdate);
cal.add(Calendar.DATE, day);
return cal.getTime();
}
playing with globals() makes it possible:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
one result:
'alphabet'
'random'
('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')
I used random because you don't explain which names of "variables" to give, and which values to create. Because i don't think it's possible to create a name without making it binded to an object.
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
A TextinputLayout
is not a view, but a Layout
, as very nicely described by Dimitrios Tsigouris in his blog post here. Therefore, you don't need a Style
, which is for Views
only, but use a Theme
. Following the blog post, I ended up with the following solution:
Start in your styles.xml
with
<style name="TextInputLayoutAppearance" parent="Widget.Design.TextInputLayout">
<!-- reference our hint & error styles -->
<item name="android:textColor">@color/your_colour_here</item>
<item name="android:textColorHint">@color/your_colour_here</item>
<item name="colorControlNormal">@color/your_colour_here</item>
<item name="colorControlActivated">@color/your_colour_here</item>
<item name="colorControlHighlight">@color/your_colour_here</item>
</style>
And in your layout add
<com.google.android.material.textfield.TextInputLayout
android:theme="@style/TextInputLayoutAppearance"
...
source myscript.sh
is also feasible.
Description for linux command source
:
source is a Unix command that evaluates the file following the command,
as a list of commands, executed in the current context
If you know the path of the class or the jar containing the class then add it to your classpath while running it. You can use the classpath as mentioned here:
on Windows
java -classpath .;yourjar.jar YourMainClass
on UNIX/Linux
java -classpath .:yourjar.jar YourMainClass
Using git rm --cached *file*
is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.
I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.
Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.
Anyway, all it requires is git update-index --assume-unchanged *path/to/file*
.
As far as I understand, this is the most notable thing to keep in mind:
Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.
Can't stand aside,
So we have linear system:
A1 * x + B1 * y = C1
A2 * x + B2 * y = C2
let's do it with Cramer's rule, so solution can be found in determinants:
x = Dx/D
y = Dy/D
where D is main determinant of the system:
A1 B1
A2 B2
and Dx and Dy can be found from matricies:
C1 B1
C2 B2
and
A1 C1
A2 C2
(notice, as C column consequently substitues the coef. columns of x and y)
So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L
for storing our coefs A, B, C of the line equations and intestead of pretty x
, y
we'll have [0]
, [1]
, but anyway. Thus, what I wrote above will have the following form further in the code:
for D
L1[0] L1[1]
L2[0] L2[1]
for Dx
L1[2] L1[1]
L2[2] L2[1]
for Dy
L1[0] L1[2]
L2[0] L2[2]
Now go for coding:
line
- produces coefs A, B, C of line equation by two points provided,
intersection
- finds intersection point (if any) of two lines provided by coefs.
from __future__ import division
def line(p1, p2):
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return A, B, -C
def intersection(L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x,y
else:
return False
Usage example:
L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])
R = intersection(L1, L2)
if R:
print "Intersection detected:", R
else:
print "No single intersection point detected"
You can use following code too:
foreach (var item in listBox1.Items.Cast<string>().ToList())
{
string removelistitem = "OBJECT";
if (item.Contains(removelistitem))
{
listBox1.Items.Remove(item);
}
}
Code > Preferences > Keyboard Shortcuts
emmet wrap
I fixed the same problem on Google Chrome with the following:
Choose Customize and control Google Chrome (the button in the top right corner).
Choose Settings.
Go to Extensions.
Unmark all the extensions there. (They should show as Enable instead of Enabled.)
In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.
A "large" object is never a constant expression in C, even if the object is declared as const
.
Moreover, in C language, the term "constant" refers to literal constants (like 1
, 'a'
, 0xFF
and so on), enum members, and results of such operators as sizeof
. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.
For example, this is NOT a constant
const int N = 5; /* `N` is not a constant in C */
The above N
would be a constant in C++, but it is not a constant in C. So, if you try doing
static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant.
This is the reason why, in C language, we predominantly use #define
to declare named constants, and also resort to #define
to create named aggregate initializers.
Well, it looks like Access can't do aggregates in UPDATE queries. But it can do aggregates in SELECT queries. So create a query with a definition like:
SELECT func_id, min(tax_code) as MinOfTax_Code
FROM Functions
INNER JOIN Tax
ON (Functions.Func_Year = Tax.Tax_Year)
AND (Functions.Func_Pure <= Tax.Tax_ToPrice)
GROUP BY Func_Id
And save it as YourQuery. Now we have to work around another Access restriction. UPDATE queries can't operate on queries, but they can operate on multiple tables. So let's turn the query into a table with a Make Table query:
SELECT YourQuery.*
INTO MinOfTax_Code
FROM YourQuery
This stores the content of the view in a table called MinOfTax_Code. Now you can do an UPDATE query:
UPDATE MinOfTax_Code
INNER JOIN Functions ON MinOfTax_Code.func_id = Functions.Func_ID
SET Functions.Func_TaxRef = [MinOfTax_Code].[MinOfTax_Code]
Doing SQL in Access is a bit of a stretch, I'd look into Sql Server Express Edition for your project!
You can also use this code to adjust to all carousel images.
.carousel-item{
width: 100%; /*width you want*/
height: 500px; /*height you want*/
overflow: hidden;
}
.carousel-item img{
width: 100%;
height: 100%;
object-fit: cover;
}
If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.
For example, if you have a class called MyCustomObject
, that has a property called LongPropertyName
, you can use a custom resolver like this…
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MyCustomObject))
{
if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "Short";
}
}
return property;
}
}
Then call for serialization and supply the resolver:
var result = JsonConvert.SerializeObject(myCustomObjectInstance,
new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });
And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}
More info on custom resolvers here
Thanks to everyone who answered the question, it really helped clarify things for me. In the end Scott Stanchfield's answer got the closest to how I ended up understanding it, but since I didn't understand him when he first wrote it, I am trying to restate the problem so that hopefully someone else will benefit.
I'm going to restate the question in terms of List, since it has only one generic parameter and that will make it easier to understand.
The purpose of the parametrized class (such as List<Date>
or Map<K, V>
as in the example) is to force a downcast and to have the compiler guarantee that this is safe (no runtime exceptions).
Consider the case of List. The essence of my question is why a method that takes a type T and a List won't accept a List of something further down the chain of inheritance than T. Consider this contrived example:
List<java.util.Date> dateList = new ArrayList<java.util.Date>();
Serializable s = new String();
addGeneric(s, dateList);
....
private <T> void addGeneric(T element, List<T> list) {
list.add(element);
}
This will not compile, because the list parameter is a list of dates, not a list of strings. Generics would not be very useful if this did compile.
The same thing applies to a Map<String, Class<? extends Serializable>>
It is not the same thing as a Map<String, Class<java.util.Date>>
. They are not covariant, so if I wanted to take a value from the map containing date classes and put it into the map containing serializable elements, that is fine, but a method signature that says:
private <T> void genericAdd(T value, List<T> list)
Wants to be able to do both:
T x = list.get(0);
and
list.add(value);
In this case, even though the junit method doesn't actually care about these things, the method signature requires the covariance, which it is not getting, therefore it does not compile.
On the second question,
Matcher<? extends T>
Would have the downside of really accepting anything when T is an Object, which is not the APIs intent. The intent is to statically ensure that the matcher matches the actual object, and there is no way to exclude Object from that calculation.
The answer to the third question is that nothing would be lost, in terms of unchecked functionality (there would be no unsafe typecasting within the JUnit API if this method was not genericized), but they are trying to accomplish something else - statically ensure that the two parameters are likely to match.
EDIT (after further contemplation and experience):
One of the big issues with the assertThat method signature is attempts to equate a variable T with a generic parameter of T. That doesn't work, because they are not covariant. So for example you may have a T which is a List<String>
but then pass a match that the compiler works out to Matcher<ArrayList<T>>
. Now if it wasn't a type parameter, things would be fine, because List and ArrayList are covariant, but since Generics, as far as the compiler is concerned require ArrayList, it can't tolerate a List for reasons that I hope are clear from the above.
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
This is usually caused by having the .xcodeproj file open instead of .xcworkspace.
When you run 'pod install' for the first time, it will create an .xcworkspace file, which includes your original .xcodeproj and a Pods project. You'll need to close your .xcodeproj and open the .xcworkspace instead.
This is a common issue when creating a project through Xcode's new project wizard - I often forget that I'm not in a workspace, which is required to get Cocoapods to link correctly.
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!
var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();
This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)
BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:
var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
var shoppingCart = _dataContext.ShoppingCart
.Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
.ToList();
This will return 5 results from DB. Using 'contains' would be wrong in this case.
Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.
Personally, I use ... | Out-Null
because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null
and [void] ...
. $null = ...
is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null
and ... > $null
come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null
), compared to putting $null =
or [void]
before the expression to determine what happens after executing it.
Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help
command or your favorite search engine to try to find out what Out-Null
does. You get a useful result immediately, right? Now try to do the same with [void]
and $null =
. Not so easy, is it?
Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void]
, $null =
, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*
* I am presuming that Out-Null
is clear and well-known, which I don't know to be $true
. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.
Here's one implementation, what works like $.prop(name[,value])
or $.attr(name[,value])
function. If b
variable is filled, visibility is set according to that, and this
is returned (allowing to continue with other properties), otherwise it returns visibility value.
jQuery.fn.visible = function (b) {
if(b === undefined)
return this.css('visibility')=="visible";
else {
this.css('visibility', b? 'visible' : 'hidden');
return this;
}
}
Example:
$("#result").visible(true).on('click',someFunction);
if($("#result").visible())
do_something;
I had what I believe the same issue is. I found that I needed to adjust the Apache configuration to include a ServerName or ServerAlias for the host.
This code failed:
public class a {
public static void main(String [] a) throws Exception {
java.net.URLConnection c = new java.net.URL("https://mydomain.com/").openConnection();
c.setDoOutput(true);
c.getOutputStream();
}
}
And this code worked:
public class a {
public static void main(String [] a) throws Exception {
java.net.URLConnection c = new java.net.URL("https://google.com/").openConnection();
c.setDoOutput(true);
c.getOutputStream();
}
}
Wireshark revealed that during the TSL/SSL Hello the warning Alert (Level: Warning, Description: Unrecognized Name), Server Hello Was being sent from the server to the client. It was only a warning, however, Java 7.1 then responded immediately back with a "Fatal, Description: Unexpected Message", which I assume means the Java SSL libraries don't like to see the warning of unrecognized name.
From the Wiki on Transport Layer Security (TLS):
112 Unrecognized name warning TLS only; client's Server Name Indicator specified a hostname not supported by the server
This led me to look at my Apache config files and I found that if I added a ServerName or ServerAlias for the name sent from the client/java side, it worked correctly without any errors.
<VirtualHost mydomain.com:443>
ServerName mydomain.com
ServerAlias www.mydomain.com
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
You can see your current session settings by querying nls_session_parameters
:
select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';
VALUE
----------------------------------------
.,
That may differ from the database defaults, which you can see in nls_database_parameters
.
In this session your query errors:
select to_number('100,12') from dual;
Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 - "invalid number"
I could alter my session, either directly with alter session
or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):
alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;
TO_NUMBER('100,12')
-------------------
100,12
In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.
But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number()
; though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:
alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;
TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
100.12
By default the result is still displayed with my session settings, so the decimal separator is still a period.
If you're not on exact root of C:/ drive then first of all use cd../.. and then use query mysql -u username -p passsword
using the above lines you can access to mysql database.
Two things you might try:
Implement a try/parse model:
public class Organisation {
public string Name { get; set; }
[JsonConverter(typeof(RichDudeConverter))]
public IPerson Owner { get; set; }
}
public interface IPerson {
string Name { get; set; }
}
public class Tycoon : IPerson {
public string Name { get; set; }
}
public class Magnate : IPerson {
public string Name { get; set; }
public string IndustryName { get; set; }
}
public class Heir: IPerson {
public string Name { get; set; }
public IPerson Benefactor { get; set; }
}
public class RichDudeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IPerson));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// pseudo-code
object richDude = serializer.Deserialize<Heir>(reader);
if (richDude == null)
{
richDude = serializer.Deserialize<Magnate>(reader);
}
if (richDude == null)
{
richDude = serializer.Deserialize<Tycoon>(reader);
}
return richDude;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Left as an exercise to the reader :)
throw new NotImplementedException();
}
}
Or, if you can do so in your object model, implement a concrete base class between IPerson and your leaf objects, and deserialize to it.
The first can potentially fail at runtime, the second requires changes to your object model and homogenizes the output to the lowest common denominator.
With the new ValueTuple
from C# 7 (VS 2017 and above), there is a new solution:
List<(int,string)> mylist= new List<(int,string)>();
Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.
It's a struct opposing to Tuple
, which is a class. It also has the advantage over the Tuple
class that you could create a named tuple, like this:
var mylist = new List<(int myInt, string myString)>();
That way you can access like mylist[0].myInt
and mylist[0].myString
Python doesn't have built-in eof detection function but that functionality is available in two ways: f.read(1)
will return b''
if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.tell()
to see if current seek position is at the end. If you want EOF testing not to change the current file position then you need bit of extra code.
Below are both implementations.
Using tell() method
import os
def is_eof(f):
cur = f.tell() # save current position
f.seek(0, os.SEEK_END)
end = f.tell() # find the size of file
f.seek(cur, os.SEEK_SET)
return cur == end
Using read() method
def is_eof(f):
s = f.read(1)
if s != b'': # restore position
f.seek(-1, os.SEEK_CUR)
return s == b''
How to use this
while not is_eof(my_file):
val = my_file.read(10)
Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.
Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?
Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).
from numpy import arange
from timeit import Timer
Nelements = 10000
Ntimeits = 10000
x = arange(Nelements)
y = range(Nelements)
t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list: %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))
which on my systems (while I'm running a backup) gives:
numpy: 3.004e-05
list: 5.363e-04
How it looks:
Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:
WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";
outubeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);
Web view xml code
<WebView
android:id="@+id/youtube_web_view"
android:layout_width="match_parent"
android:layout_height="200dp"/>
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
USE This Assembly Referance in your Project
Add a reference to System.Net.Http.Formatting.dll
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Well, I think checking the type of variable can be done this way.
public <T extends Object> void checkType(T object) {
if (object instanceof Integer)
System.out.println("Integer ");
else if(object instanceof Double)
System.out.println("Double ");
else if(object instanceof Float)
System.out.println("Float : ");
else if(object instanceof List)
System.out.println("List! ");
else if(object instanceof Set)
System.out.println("Set! ");
}
This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps!
P.S Yes, I know that this doesn't check for primitives as well.
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
No Answer is true
The true Answer is Edit Column to NVARCHAR and you found Automatically trim Execute but this code UPDATE Table SET Name = RTRIM(LTRIM(Name)) use it only with Nvarchar if use it with CHAR or NCHAR it will not work
You could use the android.text.StaticLayout
class to specify the bounds required and then call getHeight()
. You can draw the text (contained in the layout) by calling its draw(Canvas)
method.
An abstract method is defined only so that it can be overridden in a subclass. However, static methods can not be overridden. Therefore, it is a compile-time error to have an abstract, static method.
Now the next question is why static methods can not be overridden??
It's because static methods belongs to a particular class and not to its instance. If you try to override a static method you will not get any compilation or runtime error but compiler would just hide the static method of superclass.
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
How about this: location.href.slice(0, - ((location.search + location.hash).length))
LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
The HTTPConnection
object from the httplib
module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out httplib2
; it's a great library.
abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:
def distance(a, b):
if (a < 0) and (b < 0) or (a > 0) and (b > 0):
return abs( abs(a) - abs(b) )
if (a < 0) and (b > 0) or (a > 0) and (b < 0):
return abs( abs(a) + abs(b) )
print distance(-25, -15)
print distance(25, -15)
print distance(-25, 15)
print distance(25, 15)
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )
I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.
All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak
, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak
) and the table that you are writing to (dbo.foo
) have the exact same column names.
This is what worked for me using a hybrid of a bunch of different answers:
USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
([rown0]
,[row1]
,[row2]
,[row3]
,...
,[rown])
SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO
This version of my answer is helpful if you have primary and foreign keys.
In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:
function myFunc(requiredArg, optionalArg = 'defaultValue') {
// do stuff
}
More about them in this article on MDN.
This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.
EDIT (2019-06-12):
Default parameters are now widely supported by modern browsers.
All versions of Internet Explorer do not support this feature. However, Chrome, Firefox, and Edge currently support it.
System.GC.Collect()
forces garbage collector to run. This is not recommended but can be used if situations arise.
SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.
The simplest approach is not to match delimiters, i.e. commas, with a complex additional logic to match what is actually intended (the data which might be quoted strings), just to exclude false delimiters, but rather match the intended data in the first place.
The pattern consists of two alternatives, a quoted string ("[^"]*"
or ".*?"
) or everything up to the next comma ([^,]+
). To support empty cells, we have to allow the unquoted item to be empty and to consume the next comma, if any, and use the \\G
anchor:
Pattern p = Pattern.compile("\\G\"(.*?)\",?|([^,]*),?");
The pattern also contains two capturing groups to get either, the quoted string’s content or the plain content.
Then, with Java 9, we can get an array as
String[] a = p.matcher(input).results()
.map(m -> m.group(m.start(1)<0? 2: 1))
.toArray(String[]::new);
whereas older Java versions need a loop like
for(Matcher m = p.matcher(input); m.find(); ) {
String token = m.group(m.start(1)<0? 2: 1);
System.out.println("found: "+token);
}
Adding the items to a List
or an array is left as an excise to the reader.
For Java 8, you can use the results()
implementation of this answer, to do it like the Java 9 solution.
For mixed content with embedded strings, like in the question, you can simply use
Pattern p = Pattern.compile("\\G((\"(.*?)\"|[^,])*),?");
But then, the strings are kept in their quoted form.
For the record, what killed the process on my Raspberry 3B+ (running raspbian) was Ctrl+'. On my French AZERTY keyboard, the touch ' is also number 4.
Build Settings > Enable Bitcode > No
If you're brave and willing to roll your own, you could start with a PostScript library and augment it to deal with PDF, taking advantage of Adobe's free online PDF reference.
The base dn is dc=example,dc=com
.
I don't know about openca, but I will try this answer since you got very little traffic so far.
A base dn is the point from where a server will search for users. So I would try to simply use admin
as a login name.
If openca behaves like most ldap aware applications, this is what is going to happen :
admin
will be done by the server starting at the base dn (dc=example,dc=com
).cn=admin,dc=example,dc=com
) will be used to bind with the supplied password.Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :
dn
your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com
.objectClass
for your admin
user. It will be either inetOrgPerson
or user
. There will be others like top
, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson)
. Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user))
. Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.
def findReplace(find, replace):
import os
src = os.path.join(os.getcwd(), os.pardir)
for path, dirs, files in os.walk(os.path.abspath(src)):
for name in files:
if name.endswith('.py'):
filepath = os.path.join(path, name)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)
Try with this code. I hope it's useful for you.
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.
The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?
Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.
Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.
In short:
==
operator checks if their instance values are equal, "equal to"
===
operator checks if the references point the same instance, "identical to"
Long Answer:
Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. Class references stay in Run Time Stack (RTS) and their instances stay in Heap area of Memory. When you control equality with ==
it means if their instances are equal to each other. It doesn't need to be same instance to be equal. For this you need to provide a equality criteria to your custom class. By default, custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator ==
and “not equal to” operator !=
. To do this your custom class needs to conform Equatable
protocol and it's static func == (lhs:, rhs:) -> Bool
function
Let's look at example:
class Person : Equatable {
let ssn: Int
let name: String
init(ssn: Int, name: String) {
self.ssn = ssn
self.name = name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.ssn == rhs.ssn
}
}
P.S.:
Since ssn(social security number) is a unique number, you don't need to compare if their name are equal or not.
let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")
if person1 == person2 {
print("the two instances are equal!")
}
Although person1 and person2 references point two different instances in Heap area, their instances are equal because their ssn numbers are equal. So the output will be the two instance are equal!
if person1 === person2 {
//It does not enter here
} else {
print("the two instances are not identical!")
}
===
operator checks if the references point the same instance, "identical to"
. Since person1 and person2 have two different instance in Heap area, they are not identical and the output the two instance are not identical!
let person3 = person1
P.S:
Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.
if person3 === person1 {
print("the two instances are identical!")
}
They are identical and the output will be the two instances are identical!
This worked for me:
location / {
alias /path/to/my/indexfile/;
try_files $uri /index.html;
}
This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build
will be found if they are in the same directory as index.html
.
If the static files were in another directory, for some reason, you'd also need something like:
# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
alias /path/to/my/staticfiles/;
}
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
If you have HashMap<String, SomeObject> hashMap
then:
hashMap.values().toArray();
Will return an Object[]
. If instead you want an array of the type SomeObject
, you could use:
hashMap.values().toArray(new SomeObject[0]);
Some performance measurements, using timeit
instead of trying to do it manually with time
.
First, Apple 2.7.2 64-bit:
In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.05 s per loop
Now, python.org 3.3.0 64-bit:
In [83]: %timeit collections.deque((x for x in range(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.32 s per loop
In [84]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.31 s per loop
In [85]: %timeit collections.deque((x for x in iter(range(10000000)) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.33 s per loop
Apparently, 3.x range
really is a bit slower than 2.x xrange
. And the OP's xrange
function has nothing to do with it. (Not surprising, as a one-time call to the __iter__
slot isn't likely to be visible among 10000000 calls to whatever happens in the loop, but someone brought it up as a possibility.)
But it's only 30% slower. How did the OP get 2x as slow? Well, if I repeat the same tests with 32-bit Python, I get 1.58 vs. 3.12. So my guess is that this is yet another of those cases where 3.x has been optimized for 64-bit performance in ways that hurt 32-bit.
But does it really matter? Check this out, with 3.3.0 64-bit again:
In [86]: %timeit [x for x in range(10000000) if x%4 == 0]
1 loops, best of 3: 3.65 s per loop
So, building the list
takes more than twice as long than the entire iteration.
And as for "consumes much more resources than Python 2.6+", from my tests, it looks like a 3.x range
is exactly the same size as a 2.x xrange
—and, even if it were 10x as big, building the unnecessary list is still about 10000000x more of a problem than anything the range iteration could possibly do.
And what about an explicit for
loop instead of the C loop inside deque
?
In [87]: def consume(x):
....: for i in x:
....: pass
In [88]: %timeit consume(x for x in range(10000000) if x%4 == 0)
1 loops, best of 3: 1.85 s per loop
So, almost as much time wasted in the for
statement as in the actual work of iterating the range
.
If you're worried about optimizing the iteration of a range object, you're probably looking in the wrong place.
Meanwhile, you keep asking why xrange
was removed, no matter how many times people tell you the same thing, but I'll repeat it again: It was not removed: it was renamed to range
, and the 2.x range
is what was removed.
Here's some proof that the 3.3 range
object is a direct descendant of the 2.x xrange
object (and not of the 2.x range
function): the source to 3.3 range
and 2.7 xrange
. You can even see the change history (linked to, I believe, the change that replaced the last instance of the string "xrange" anywhere in the file).
So, why is it slower?
Well, for one, they've added a lot of new features. For another, they've done all kinds of changes all over the place (especially inside iteration) that have minor side effects. And there'd been a lot of work to dramatically optimize various important cases, even if it sometimes slightly pessimizes less important cases. Add this all up, and I'm not surprised that iterating a range
as fast as possible is now a bit slower. It's one of those less-important cases that nobody would ever care enough to focus on. No one is likely to ever have a real-life use case where this performance difference is the hotspot in their code.
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/
For another one-liner solution:
def count_letters(word): return len(filter(lambda x: x not in " ", word))
This works by using the filter function, which lets you pick the elements of a list that return true when passed to a boolean-valued function that you pass as the first argument. I'm using a lambda function to make a quick, throwaway function for that purpose.
>>> count_letters("This is a test")
11
You could easily extend this to exclude any selection of characters you like:
def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word))
>>> count_letters ("This is a test", "aeiou ")
7
Edit: However, you wanted to get your own code to work, so here are some thoughts. The first problem is that you weren't setting a list for the Counter object to count. However, since you're looking for the total number of letters, you need to join the words back together again rather than counting each word individually. Looping to add up the number of each letter isn't really necessary because you can pull out the list of values and use "sum" to add them.
Here's a version that's as close to your code as I could make it, without the loop:
from collections import Counter
import string
def count_letters(word):
wordsList = string.split(word)
count = Counter("".join(wordsList))
return sum(dict(count).values())
word = "The grey old fox is an idiot"
print count_letters(word)
Edit: In response to a comment asking why not to use a for loop, it's because it's not necessary, and in many cases using the many implicit ways to perform repetitive tasks in Python can be faster, simpler to read, and more memory-efficient.
For example, I could have written
joined_words = []
for curr_word in wordsList:
joined_words.extend(curr_word)
count = Counter(joined_words)
but in doing this I wind up allocating an extra array and executing a loop through the Python interpreter that my solution:
count = Counter("".join(wordsList))
would execute in a chunk of optimized, compiled C code. My solution isn't the only way to simplify that loop, but it's one way.
Try adding the following to your InventoryApp class
@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...
spring-boot will scan for components in packages below com.nice.application
, so if your controller is in com.nice.controller
you need to scan for it explicitly.
If I'm not mistaken, you should be applying this rule to the li, not the ul.
ul li {list-style-type: disc;}
I usually use
#define INFINITY (1e999)
or
const double INFINITY = 1e999
which works at least in IEEE 754 contexts because the highest representable double value is roughly 1e308
. 1e309
would work just as well, as would 1e99999
, but three nines is sufficient and memorable. Since this is either a double literal (in the #define
case) or an actual Inf
value, it will remain infinite even if you're using 128-bit (“long double”) floats.
If you pass an Exception class to assertRaises()
, a context manager is provided. This can improve the readability of your tests:
# raise exception if Application created with bad data
with self.assertRaises(pySourceAidExceptions.PathIsNotAValidOne):
application = Application("abcdef", "")
This allows you to test error cases in your code.
In this case, you are testing the PathIsNotAValidOne
is raised when you pass invalid parameters to the Application constructor.
open terminal and type the below command and hit enter
sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
Just use = IF(A1="Bla*","YES","NO")
. When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.
The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color.
yourLabel.textColor = hiddenLabel.textColor
The only way I could change the text color programmatically was by using the standard colors, UIColor.white
, UIColor.green
...
form.MySelect.options[form.MySelect.selectedIndex].value
If you want to check the python version in a particular cond environment you can also use conda list python
I use this,
$request = (count($_REQUEST) > 1)?$_REQUEST:$_GET;
the statement validates if $_REQUEST has more than one parameter (the first parameter in $_REQUEST will be the request uri which can be used when needed, some PHP packages wont return $_GET so check if its more than 1 go for $_GET, By default, it will be $_POST.
Let's not forget good old parameters. When starting your *.bat or *.cmd file you can add up to nine parameters after the command file name:
call myscript.bat \\path\to\my\file.ext type
call myscript.bat \\path\to\my\file.ext "Del /F"
The myscript.bat could be something like this:
@Echo Off
Echo The path of this scriptfile %~0
Echo The name of this scriptfile %~n0
Echo The extension of this scriptfile %~x0
Echo.
If "%~2"=="" (
Echo Parameter missing, quitting.
GoTo :EOF
)
If Not Exist "%~1" (
Echo File does not exist, quitting.
GoTo :EOF
)
Echo Going to %~2 this file: %~1
%~2 "%~1"
If %errorlevel% NEQ 0 (
Echo Failed to %~2 the %~1.
)
@Echo On
c:\>c:\bats\myscript.bat \\server\path\x.txt type
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat
Going to type this file: \\server\path\x.txt
This is the content of the file:
Some alphabets: ABCDEFG abcdefg
Some numbers: 1234567890
c:\>c:\bats\myscript.bat \\server\path\x.txt "del /f "
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat
Going to del /f this file: \\server\path\x.txt
c:\>
sys.argv
represents the command line options you execute a script with.
sys.argv[0]
is the name of the script you are running. All additional options are contained in sys.argv[1:]
.
You are attempting to open a file that uses sys.argv[1]
(the first argument) as what looks to be the directory.
Try running something like this:
python ConcatenateFiles.py /tmp
I have been in similar situation before. In Command prompt, you type 'start-ssh-agent' and voila! The ssh-agent will be started. Input the passphrase if it asked you.
As other answers have mentioned, the following calls will compute the hash:
MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);
The purpose of splitting it up into that many functions is to let you stream large datasets.
For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update
on them.
MD5Context md5;
MD5Init(&md5);
fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
...
// Now finish to get the final hash value.
MD5Final(digest, &md5);
I know that this is an old question but I am just going to place this here:
To prevent skype from using port 80 and port 443, open the Skype window, then click on the Tools menu and select Options.
Click on the Advanced tab, and go to the Connection sub-tab.
Uncheck the checkbox for Use port 80 and 443 as an alternative for additional incoming connections option.
Click on the Save button and then restart Skype.
After you restart skype, skype wont use port 88 or 443 anymore.
Hope this might help someone.
This code work in my mysql db:
ALTER TABLE `goods`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
Other method by using pandas
import pandas as pd
LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])
You can then export results in any format you want
Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.
:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i
:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i
:: Show file name with the date.
echo Archive.%DTime%.zip
If you really want to micro optimise your code your best approach is always benchmarking.
The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch
One possibility, reducing the longer form before expanding all:
string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")
Another way, treating Vasic as optional:
string.replaceAll("Milan( Vasic)?", "Milan Vasic")
Others have described solutions based on lookahead or alternation.
Just from reading that i would have never understood that "$@"
expands into a list of separate parameters. Whereas, "$*"
is one parameter consisting of all the parameters added together.
If it still makes no sense do this.
http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/
Got it working. Here was my procedure:
Sources
tab in chrome inspectorElements
tab in inspectorTaken from: http://developer.android.com/guide/topics/ui/ui-events.html
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
Necroing this question because I recently ran into the problem myself, when trying to add a related property to an existing entity. I just ended up making a nice extension method:
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, TProperty value)
{
string expressionText = ExpressionHelper.GetExpressionText(expression);
string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);
return htmlHelper.Hidden(propertyName, value);
}
Use like so:
@Html.HiddenFor(m => m.RELATED_ID, Related.Id)
Note that this has a similar signature to the built-in HiddenFor, but uses generic typing, so if Value is of type System.Object, you'll actually be invoking the one built into the framework. Not sure why you'd be editing a property of type System.Object in your views though...
Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.
function truncateOnWord(str, limit) {
var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
var reg = new RegExp('(?=[' + trimmable + '])');
var words = str.split(reg);
var count = 0;
return words.filter(function(word) {
count += word.length;
return count <= limit;
}).join('');
}
If you want no index, read file using:
import pandas as pd
df = pd.read_csv('file.csv', index_col=0)
save it using
df.to_csv('file.csv', index=False)
Use Apache commons beanutils:
static void copyProperties(Object dest, Object orig)
-Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
Try RFS (for responsive font size) library by MartijnCuppens that maybe will be implemented in Bootstrap
Try this:
a[id*='Some:Same'][id$='name']
This will get you all a
elements with id containing
Some:Same
and have the id ending in
name
Command line usage:
for /f %f in ('dir /b c:\') do echo %f
Batch file usage:
for /f %%f in ('dir /b c:\') do echo %%f
Update: if the directory contains files with space in the names, you need to change the delimiter the for /f
command is using. for example, you can use the pipe char.
for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq
option on the for
:
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
And if you need to use output redirection or command piping, use the escape char (^
):
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
Use the method that accepts a Comparator
when you want to sort in something other than natural order.
It looks like overriding the Target
class or one of the implementations like BitmapImageViewTarget
and overriding the setResource
method to capture the bitmap might be the way to go...
This is untested. :-)
Glide.with(context)
.load("http://goo.gl/h8qOq7")
.asBitmap()
.into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
// Do bitmap magic here
super.setResource(resource);
}
});
Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.
Rather late I know, but you can use SELECT @@datadir
to get the information.
Happy file huntin' SO community :)
Yeah, Chrome searches instead of looking for scheme. If you want to launch your App through URI scheme, use this cool utility App on the Play store. It saved my day :) https://play.google.com/store/apps/details?id=com.naosim.urlschemesender
# clone special tag/branch without history
git clone --branch=<tag/branch> --depth=1 <repository>
# clone special revision with minimal histories
git clone --branch <branch> <repository> --shallow-since=yyyy-MM-ddTHH:mm:ss # get the commit time
cd <dir>
git reset --hard <revision>
you can't get a revision without histories if not set uploadpack.allowReachableSHA1InWant=true
on server side, while you can create a tag for it and clone the special tag instead.
You can use PyPdf2s PdfMerger
class.
File Concatenation
You can simply concatenate files by using the append
method.
from PyPDF2 import PdfFileMerger
pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(pdf)
merger.write("result.pdf")
merger.close()
You can pass file handles instead file paths if you want.
File Merging
If you want more fine grained control of merging there is a merge
method of the PdfMerger
, which allows you to specify an insertion point in the output file, meaning you can insert the pages anywhere in the file. The append
method can be thought of as a merge
where the insertion point is the end of the file.
e.g.
merger.merge(2, pdf)
Here we insert the whole pdf into the output but at page 2.
Page Ranges
If you wish to control which pages are appended from a particular file, you can use the pages
keyword argument of append
and merge
, passing a tuple in the form (start, stop[, step])
(like the regular range
function).
e.g.
merger.append(pdf, pages=(0, 3)) # first 3 pages
merger.append(pdf, pages=(0, 6, 2)) # pages 1,3, 5
If you specify an invalid range you will get an IndexError
.
Note: also that to avoid files being left open, the PdfFileMerger
s close method should be called when the merged file has been written. This ensures all files are closed (input and output) in a timely manner. It's a shame that PdfFileMerger
isn't implemented as a context manager, so we can use the with
keyword, avoid the explicit close call and get some easy exception safety.
You might also want to look at the pdfcat
script provided as part of pypdf2. You can potentially avoid the need to write code altogether.
The PyPdf2 github also includes some example code demonstrating merging.
The preferred way would be to create your own remote repository.
See here for details on how to do it. Have a look at the 'Uploading to a Remote Repository' section.
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
There are tons of responses. But none is talking about decorators. So here's mine.
Because it is a lot more simple.
There's no need to import anything, nor to write any subclass:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
NO_COLOR = "\33[m"
RED, GREEN, ORANGE, BLUE, PURPLE, LBLUE, GREY = \
map("\33[%dm".__mod__, range(31, 38))
logging.basicConfig(format="%(message)s", level=logging.DEBUG)
logger = logging.getLogger(__name__)
# the decorator to apply on the logger methods info, warn, ...
def add_color(logger_method, color):
def wrapper(message, *args, **kwargs):
return logger_method(
# the coloring is applied here.
color+message+NO_COLOR,
*args, **kwargs
)
return wrapper
for level, color in zip((
"info", "warn", "error", "debug"), (
GREEN, ORANGE, RED, BLUE
)):
setattr(logger, level, add_color(getattr(logger, level), color))
# this is displayed in red.
logger.error("Launching %s." % __file__)
This set the errors in red, debug messages in blue, and so on. Like asked in the question.
We could even adapt the wrapper to take a color
argument to dynamicaly set the message's color using logger.debug("message", color=GREY)
EDIT: So here's the adapted decorator to set colors at runtime:
def add_color(logger_method, _color):
def wrapper(message, *args, **kwargs):
color = kwargs.pop("color", _color)
if isinstance(color, int):
color = "\33[%dm" % color
return logger_method(
# the coloring is applied here.
color+message+NO_COLOR,
*args, **kwargs
)
return wrapper
# blah blah, apply the decorator...
# this is displayed in red.
logger.error("Launching %s." % __file__)
# this is displayed in blue
logger.error("Launching %s." % __file__, color=34)
# and this, in grey
logger.error("Launching %s." % __file__, color=GREY)
make sure you're using the newest jquery, and problem solved
I met this problem with this code:
<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
After change it to this:
<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
It works fine
Here's some ways to style <option>
along with the <select>
if you're using Bootstrap and/or jquery. I understand this isn't what the original poster is asking but I thought I could help others that stumble onto this question.
You can still achieve the goal of styling each <option>
separately, but may need to apply some style to the <select>
as well. My favorite is the "Bootstrap Select" library mentioned below.
If you're already using bootstrap, you can try the Bootstrap Select library or the library below (since it has a bootstrap theme).
Note that you are able to style the entire select
element, or the option
elements separately.
Examples:
Dependencies: requires jQuery v1.9.1+, Bootstrap, Bootstrap’s dropdown.js component, and Bootstrap's CSS
Compatibility: Unsure, but bootstrap says it "supports the latest, stable releases of all major browsers and platforms"
Demo: https://developer.snapappointments.com/bootstrap-select/examples/
.special {_x000D_
font-weight: bold !important;_x000D_
color: #fff !important;_x000D_
background: #bc0000 !important;_x000D_
text-transform: uppercase;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css" rel="stylesheet" />_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option>Mustard</option>_x000D_
<option class="special">Ketchup</option>_x000D_
<option style="background: #5cb85c; color: #fff;">Relish</option>_x000D_
</select>
_x000D_
There's a library you can use called Select2.
Dependencies: Library is JS + CSS + HTML only (does not require JQuery).
Compatibility: IE 8+, Chrome 8+, Firefox 10+, Safari 3+, Opera 10.6+
Demo: https://select2.org/getting-started/basic-usage
There's also a bootstrap theme available.
No Bootstrap example:
$(function() {_x000D_
var $select = $('.select2');_x000D_
_x000D_
$select.select2({_x000D_
theme: 'paper'_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<select class="select2 form-control" placeholder="Country">_x000D_
<optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
<option value="AK">Alaska</option>_x000D_
<option value="HI">Hawaii</option>_x000D_
</optgroup>_x000D_
<optgroup label="Pacific Time Zone">_x000D_
<option value="CA">California</option>_x000D_
<option value="NV">Nevada</option>_x000D_
<option value="OR">Oregon</option>_x000D_
<option value="WA">Washington</option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
Bootstrap example:
$(function() {_x000D_
var $select = $('.select2');_x000D_
_x000D_
$select.select2({_x000D_
theme: 'paper'_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/paper/bootstrap.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<select class="select2 form-control" placeholder="Country">_x000D_
<optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
<option value="AK">Alaska</option>_x000D_
<option value="HI">Hawaii</option>_x000D_
</optgroup>_x000D_
<optgroup label="Pacific Time Zone">_x000D_
<option value="CA">California</option>_x000D_
<option value="NV">Nevada</option>_x000D_
<option value="OR">Oregon</option>_x000D_
<option value="WA">Washington</option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
If you have extra money, you can use a premium library MDBootstrap. (This is an entire UI Kit, so it's not light)
This allows you to style your select and option elements using the Material design.
There is a free version, but it won't allow you to use the pretty Material design!
Dependencies: Bootstrap 4, JQuery,
Compatibility: "supports the latest, stable releases of all major browsers and platforms."
Demo: https://mdbootstrap.com/docs/jquery/forms/select/#color
Many thanks to everyone that has been working on code for this!
I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.
Anyway, I use it for something something like:
var myCache = {
cache: {},
order: [],
size: 0,
maxSize: 2 * 1024 * 1024, // 2mb
add: function(key, object) {
// Otherwise add new object
var size = this.getObjectSize(object);
if (size > this.maxSize) return; // Can't store this object
var total = this.size + size;
// Check for existing entry, as replacing it will free up space
if (typeof(this.cache[key]) !== 'undefined') {
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
total -= entry.size;
this.order.splice(i, 1);
break;
}
}
}
while (total > this.maxSize) {
var entry = this.order.shift();
delete this.cache[entry.key];
total -= entry.size;
}
this.cache[key] = object;
this.order.push({ size: size, key: key });
this.size = total;
},
get: function(key) {
var value = this.cache[key];
if (typeof(value) !== 'undefined') { // Return this key for longer
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
this.order.splice(i, 1);
this.order.push(entry);
break;
}
}
}
return value;
},
getObjectSize: function(object) {
// Code from above estimating functions
},
};
It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
Is there any truth to the claim that functional programming eliminates the need for OOP design patterns?
Functional programming is not the same as object-oriented programming. Object-oriented design patterns don't apply to functional programming. Instead, you have functional programming design patterns.
For functional programming, you won't read the OO design pattern books; you'll read other books on FP design patterns.
language agnostic
Not totally. Only language-agnostic with respect to OO languages. The design patterns don't apply to procedural languages at all. They barely make sense in a relational database design context. They don't apply when designing a spreadsheet.
a typical OOP design pattern and its functional equivalent?
The above shouldn't exist. That's like asking for a piece of procedural code rewritten as OO code. Ummm... If I translate the original Fortran (or C) into Java, I haven't done anything more than translate it. If I totally rewrite it into an OO paradigm, it will no longer look anything like the original Fortran or C -- it will be unrecognizable.
There's no simple mapping from OO design to functional design. They're very different ways of looking at the problem.
Functional programming (like all styles of programming) has design patterns. Relational databases have design patterns, OO has design patterns, and procedural programming has design patterns. Everything has design patterns, even the architecture of buildings.
Design patterns -- as a concept -- are a timeless way of building, irrespective of technology or problem domain. However, specific design patterns apply to specific problem domains and technologies.
Everyone who thinks about what they're doing will uncover design patterns.
However, it is important to note that the mysql connector driver version must be older than 5.1.47 and later.
The following can be used to retrieve JSESSIONID:
function getJSessionId(){
var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
if(jsId != null) {
if (jsId instanceof Array)
jsId = jsId[0].substring(11);
else
jsId = jsId.substring(11);
}
return jsId;
}
Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:
"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage
which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh
"thought" that it is run in the regular terminal and since it may be accomplished by simple posix
functions, it is beyond what simple bash
offers.
We were having similar issues with Font Awesome on a static "cookie-less" domain when reading fonts from the "cookie domain" (www.domain.tld) and this post was our hero. See here: How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?
For the copy/paste-r types (and to give some props) I pieced this together from all the contributions and added it to the top of the .htaccess file of the site root:
<IfModule mod_headers.c>
<IfModule mod_rewrite.c>
SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0
Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
Header merge Vary "Origin"
</IfModule>
</IfModule>
Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.
Props to:@Noyo @DaveRandom @pratap-koritala
(I tried to leave this as a comment to the accepted answer, but I can't do that yet)
Keep the jar files under web-inf lib incase you included jar and it is not able to identify .
It worked in my case where everything was ok but it was not able to load the driver class.
In certain cases, the use of :
for(var pair of formData.entries(){...
is impossible.
I've used this code in replacement :
var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
var item = iterator.next();
if(item.value!=undefined) {
outputLog[item.value[0]] = item.value[1];
} else if(item.done==true) {
end = true;
}
}
console.log(outputLog);
It's not a very smart code, but it works...
Hope it's help.
I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
I'm using the minimum image size (200 x 200) and getting good results. Take a look:
https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br
This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.
This size is on facebook documentation
Using setBackgroundResource()
method:
myImgView.setBackgroundResource(R.drawable.monkey);
you are putting that monkey in the background.
I suggest the use of setImageResource()
method:
myImgView.setImageResource(R.drawable.monkey);
or with setImageDrawable()
method:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
getResources().getDrawable()
is now deprecated. This is an example how to use now:myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
and how to validate for old API versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}
If you use MVC 3 and .NET 4, you can use the new Display
attribute in the System.ComponentModel.DataAnnotations
namespace. This attribute replaces the DisplayName
attribute and provides much more functionality, including localization support.
In your case, you would use it like this:
public class MyModel
{
[Required]
[Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
public string name{ get; set; }
}
As a side note, this attribute will not work with resources inside App_GlobalResources
or App_LocalResources
. This has to do with the custom tool (GlobalResourceProxyGenerator
) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.
(As a further side note, you shouldn't be using App_GlobalResources
or App_LocalResources
with MVC. You can read more about why this is the case here)
As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT
. I've commented most of it.
The Setup
class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
// EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
// the logging mechanism.
/// <summary>
///
/// </summary>
/// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
public GlobalKeyboardHook(Keys[] registeredKeys = null)
{
RegisteredKeys = registeredKeys;
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
// EDT: added a conversion from VirtualCode to Keys.
/// <summary>
/// The VirtualCode converted to typeof(Keys) for higher usability.
/// </summary>
public Keys Key { get { return (Keys)VirtualCode; } }
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
// EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
public static Keys[] RegisteredKeys;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
// EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
// Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
// has to be null for the event to get fired.
var key = (Keys)p.VirtualCode;
if (RegisteredKeys == null || RegisteredKeys.Contains(key))
{
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
The Usage differences can be seen here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private GlobalKeyboardHook _globalKeyboardHook;
private void buttonHook_Click(object sender, EventArgs e)
{
// Hooks only into specified Keys (here "A" and "B").
_globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });
// Hooks into all keys.
_globalKeyboardHook = new GlobalKeyboardHook();
_globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
// EDT: No need to filter for VkSnapshot anymore. This now gets handled
// through the constructor of GlobalKeyboardHook(...).
if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
{
// Now you can access both, the key and virtual code
Keys loggedKey = e.KeyboardData.Key;
int loggedVkCode = e.KeyboardData.VirtualCode;
}
}
}
Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.
To change the default character set and collation of a table including those of existing columns (note the convert to clause):
alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;
Edited the answer, thanks to the prompting of some comments:
Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41
and
That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46
Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:
# jinja2.__version__ == 2.8
from jinja2 import Template
def calcName(n, i):
return ' '.join([n] * i)
template = Template("Hello {{ calcName('Gandalf', 2) }}")
template.render(calcName=calcName)
# or
template.render({'calcName': calcName})
I have set up Volley as a separate Project. That way its not tied to any project and exist independently.
I also have a Nexus server (Internal repo) setup so I can access volley as
compile 'com.mycompany.volley:volley:1.0.4' in any project I need.
Any time I update Volley project, I just need to change the version number in other projects.
I feel very comfortable with this approach.
One more important difference: typedef
s cannot be forward declared. So for the typedef
option you must #include
the file containing the typedef
, meaning everything that #include
s your .h
also includes that file whether it directly needs it or not, and so on. It can definitely impact your build times on larger projects.
Without the typedef
, in some cases you can just add a forward declaration of struct Foo;
at the top of your .h
file, and only #include
the struct definition in your .cpp
file.
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
This will direct everything from the old host to the root of the new host:
RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]
If you have problems like that, first of all your TC
folder put in to the C:..drive.
after completing installation open turbo c blue screen.
there is a OPTIONS > Directories
..in that you can see for option to set up path..
C:\TC\INCUDE
C:\TC\LIB
C:\TC\BIN
..otherwise you can set another path where you want to store your output..Finally you can give OK and finished processes.. It will now work properly
An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.
This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:
---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---
::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}
1. any
2. normal markdown
3. can go in a cell
:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}
some text
:::
::::
:::: {.trow bypara=true}
If bypara=true
Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::
Looks like:
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.
From wiki.answers.com:
The term declaration means (in C) that you are telling the compiler about type, size and in case of function declaration, type and size of its parameters of any variable, or user defined type or function in your program. No space is reserved in memory for any variable in case of declaration. However compiler knows how much space to reserve in case a variable of this type is created.
for example, following are all declarations:
extern int a;
struct _tagExample { int a; int b; };
int myFunc (int a, int b);
Definition on the other hand means that in additions to all the things that declaration does, space is also reserved in memory. You can say "DEFINITION = DECLARATION + SPACE RESERVATION" following are examples of definition:
int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;
see Answers.
If this problem persists, you may want to check all path values in the PATH variable (under Control Panel\System and Security\System\Advanced System Settings
). It might be that some other path is invalid or contains an illegal character.
Today, I had the same problem and found a double quote in a different path value in the PATH variable. All paths after that (including a fresly installed conda) were not usable. Removing the double quote solved the problem.
It is possible by recreating table.Its work for me please follow following step:
do all above steps in worker thread to reduce load on uithread
I solved this problem by adding C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll in the reference
For a 2021 Solution in dotnet core, you can fix this error by right-clicking the project in Solution Explorer, and choosing 'Edit Project File'.
On the Debug Tab, at the bottom, you can directly configure the desired port and whether to use SSL or not.
Changes here need to be saved with Control+S. Once that's done, you can launch the project and confirm it fixed your issue, no having to delete IISFolders or anything else suggested here.
Perhaps not a major language (unfortunately), but in APL, theres the ?EA operation (stand for Execute Alternate).
Usage: 'Y' ?EA 'X' where X and Y are either code snippets supplied as strings or function names.
If X runs into an error, Y (usually error-handling) will be executed instead.
No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.
Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?
Use ToString("X4")
.
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
Once I also got that same type of error.
I.E:
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
Error 6 initializing SQL*Plus
Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
This error is occurring as the home path is not correctly set. To rectify this, if you are using Windows, run the below query:
C:\oracle\product\10.2.0\db_2>SET ORACLE_HOME=C:\oracle\product\10.2.0\db_2
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Or if you are using Linux, then replace set
with export
for the above command like so:
C:\oracle\product\10.2.0\db_2>EXPORT ORACLE_HOME='C:\oracle\product\10.2.0\db_2'
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
If you don't know the exact class of your number (Integer, Long, Double, whatever), you can cast to Number and get your long value from it:
Object num = new Integer(6);
Long longValue = ((Number) num).longValue();
As the internet updates I've come across a solution.
First some caveats.
First, mark your child component's encapsulation as shadow so it renders in the actual shadow dom. Second, add the part attribute to the element you wish to allow the parent to style. In your parent's component stylesheet you can use the ::part() method to access
Actually, I believe you want to use the __getattr__
special method instead.
Quote from the Python docs:
__getattr__( self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,__getattr__()
is not called. (This is an intentional asymmetry between__getattr__()
and__setattr__()
.) This is done both for efficiency reasons and because otherwise__setattr__()
would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()
method below for a way to actually get total control in new-style classes.
Note: for this to work, the instance should not have a test
attribute, so the line self.test=20
should be removed.
Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +
"SET SCHEMA TEST";
String url = "jdbc:h2:mem;" +
"INIT=RUNSCRIPT FROM '~/create.sql'\\;" +
"RUNSCRIPT FROM '~/populate.sql'";
Please note the double backslash (\\
) is only required within Java. The backslash(es) before ;
within the INIT
is required.
Use Platform.runLater(...)
for quick and simple operations and Task
for complex and big operations .
Example: Why Can't we use Platform.runLater(...)
for long calculations (Taken from below reference).
Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.
Code using Platform.runLater(...)
:
final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
@Override public void run() {
for (int i = 1; i <= 1000000; i++) {
final int counter = i;
Platform.runLater(new Runnable() {
@Override public void run() {
bar.setProgress(counter / 1000000.0);
}
});
}
}).start();
This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.
Code using Task :
Task task = new Task<Void>() {
@Override public Void call() {
static final int max = 1000000;
for (int i = 1; i <= max; i++) {
updateProgress(i, max);
}
return null;
}
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
it suffers from none of the flaws exhibited in the previous code
Reference : Worker Threading in JavaFX 2.0
This will bring back totals per property and type
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
GROUP BY PropertyID,
TYPE
This will bring back only active values
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID,
TYPE
and this will bring back totals for properties
SELECT PropertyID,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID
......
Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.
After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.
You can do it using jQuery. Example:
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
url : "next.php",
type: "POST",
data : "name=Denniss",
success: function(data)
{
//data - response from server
$('#response_div').html(data);
}
});
</script>
For XSL (on really lazy days) I use:
capture="&(?!amp;)" capturereplace="&amp;"
to translate all &-signs that aren't follwed på amp; to proper ones.
We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...
You can try these codes
claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd");
Or
claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd hh:mm:ss");
Try this:
update Projects
set KickOffStatus=2
where KickOffStatus is null
When the left part is an object instance, you use ->
. Otherwise, you use ::
.
This means that ->
is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while ::
is usually used to access static members (though in a few special cases, it's used to access instance members).
In general, ::
is used for scope resolution, and it may have either a class name, parent
, self
, or (in PHP 5.3) static
to its left. parent
refers to the scope of the superclass of the class where it's used; self
refers to the scope of the class where it's used; static
refers to the "called scope" (see late static bindings).
The rule is that a call with ::
is an instance call if and only if:
$this
exists and$this
is either the class of the method being called or a subclass of it.Example:
class A {
public function func_instance() {
echo "in ", __METHOD__, "\n";
}
public function callDynamic() {
echo "in ", __METHOD__, "\n";
B::dyn();
}
}
class B extends A {
public static $prop_static = 'B::$prop_static value';
public $prop_instance = 'B::$prop_instance value';
public function func_instance() {
echo "in ", __METHOD__, "\n";
/* this is one exception where :: is required to access an
* instance member.
* The super implementation of func_instance is being
* accessed here */
parent::func_instance();
A::func_instance(); //same as the statement above
}
public static function func_static() {
echo "in ", __METHOD__, "\n";
}
public function __call($name, $arguments) {
echo "in dynamic $name (__call)", "\n";
}
public static function __callStatic($name, $arguments) {
echo "in dynamic $name (__callStatic)", "\n";
}
}
echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";
echo '$b->func_instance():', "\n", $b->func_instance(), "\n";
/* This is more tricky
* in the first case, a static call is made because $this is an
* instance of A, so B::dyn() is a method of an incompatible class
*/
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
* instance of B (despite the fact we are in a method of A), so
* B::dyn() is a method of a compatible class (namely, it's the
* same class as the object's)
*/
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";
Output:
B::$prop_static: B::$prop_static value B::func_static(): in B::func_static $b->prop_instance: B::$prop_instance value $b->func_static(): in B::func_static $b->func_instance(): in B::func_instance in A::func_instance in A::func_instance $a->dyn(): in A::callDynamic in dynamic dyn (__callStatic) $b->dyn(): in A::callDynamic in dynamic dyn (__call)
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
In PHP there are a lot of variables that I should check. Is it the same on Go?
This has nothing to do with Go (or PHP for that matter). It just depends on what the client, proxy, load-balancer, or server is sending. Get the one you need depending on your environment.
http.Request.RemoteAddr
contains the remote IP address. It may or may not be your actual client.
And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))
No, why not try it yourself? http://play.golang.org/p/YMf_UBvDsH
Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:
DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);
DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.
git stash
[save]
takes your working directory state, and your index state, and stashes them away, setting index and working area to HEAD
version.
git stash apply
brings back those changes, so git reset --hard
would remove them again.
git stash pop
brings back those changes and removes top stashed change, so git stash [save]
would return to previous (pre-pop) state in this case.
An additional trick beside using =COUNTIF(...) and =COUNTA(...) is:
=COUNTBLANK(A2:C100)
That will count all the empty cells.
This is useful for:
Implementing an inset box shadow CSS works on Firefox:
select option:checked,
select option:hover {
box-shadow: 0 0 10px 100px #000 inset;
}
Checked option item works in Chrome:
select:focus > option:checked {
background: #000 !important;
}
There is test on https://codepen.io/egle/pen/zzOKLe
For me this is working on Google Chrome Version 76.0.3809.100 (Official Build) (64-bit)
Newest article I have found about this issue by Chris Coyier (Oct 28, 2019) https://css-tricks.com/the-current-state-of-styling-selects-in-2019/
The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration
to suit your needs.
.animated {_x000D_
-webkit-animation-duration: .5s;_x000D_
animation-duration: .5s;_x000D_
-webkit-animation-fill-mode: both;_x000D_
animation-fill-mode: both;_x000D_
-webkit-animation-timing-function: linear;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
0%, 100% {_x000D_
-webkit-transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
-webkit-transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
@keyframes bounce {_x000D_
0%, 100% {_x000D_
transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
.bounce {_x000D_
-webkit-animation-name: bounce;_x000D_
animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: red;_x000D_
position: relative;_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
position: relative;_x000D_
top: 92px;_x000D_
left: -300px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
Here is how your original keyframe
settings would be interpreted by the browser:
translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 0px in Y axis.translate
by 5px in Y axis. This results in a gradual upward movement.translate
by 0px in Y axis. This results in a gradual downward movement.translate
by 0px in Y axis.translate
by 0px in Y axis.Sounds like you need to create your own pair class (see discussion here). Then make a List of that pair class you created