cd "C:\Program Files\MongoDB\Server\4.4\bin"
mongoimport -d tymongo -c test --type json --file restaurants.json
mongoimport -d tymongo -c test --type csv --file database2.csv --headerline
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:
module.directive('myDirectiveContainer', function () {
return {
controller: function ($scope) {
this.scope = $scope;
}
};
});
module.directive('myDirective', function () {
return {
require: '^myDirectiveContainer',
link: function (scope, element, attrs, containerController) {
// use containerController.scope here...
}
};
});
and then
<div my-directive-container="">
<div my-directive="">
</div>
</div>
Maybe not the most graceful solution, but it got the job done.
Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc
executable inside the jdk's bin folder.
If you are using LoaderManager try with this statement:
getLoaderManager().restartLoader(0, null, this);
MSDN actually has a sample application for both C# and VB to do exactly this: http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx
The most common and reliable technique for developing single-instance detection is to use the Microsoft .NET Framework remoting infrastructure (System.Remoting). The Microsoft .NET Framework (version 2.0) includes a type, WindowsFormsApplicationBase, which encapsulates the required remoting functionality. To incorporate this type into a WPF application, a type needs to derive from it, and be used as a shim between the application static entry point method, Main, and the WPF application's Application type. The shim detects when an application is first launched, and when subsequent launches are attempted, and yields control the WPF Application type to determine how to process the launches.
'Another instance of the app is running. Bye'
then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.The framework already has support for this - its just that some idiot named the DLL Microsoft.VisualBasic
and it didn't get put into Microsoft.ApplicationUtils
or something like that. Get over it - or open up Reflector.
Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to take a look at this too.
SELECT * FROM user_cons_columns WHERE table_name = 'table_name';
List to Tuple and back can be done as below
import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)
l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)
# Make sure to name the final tuple 'tuple_2'
print(tuple_2)
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
Where it says "Accept requests from these HTTP referrers (websites) (Optional)" you don't need to have any referrer listed. So click the X beside localhost on this page but continue to use your key.
It should then work after a few minutes.
Changes made can sometimes take a few minutes to take effect so wait a few minutes before testing again.
(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:
int y = (c == 19) ? 7 : 11 ;
or
String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);
as You can see the type of the variable Y is the same as the return value ...
in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
try white-space:normal;
This will override inheriting white-space:nowrap;
You forgot to seek:
str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");
You should reference the textarea ID and include the runat="server"
attribute to the textarea
message.Body = TextArea1.Text;
What is test123
?
You can also try Notification API. Here's an example:
function message(msg){
if (window.webkitNotifications) {
if (window.webkitNotifications.checkPermission() == 0) {
notification = window.webkitNotifications.createNotification(
'picture.png', 'Title', msg);
notification.onshow = function() { // when message shows up
setTimeout(function() {
notification.close();
}, 1000); // close message after one second...
};
notification.show();
} else {
window.webkitNotifications.requestPermission(); // ask for permissions
}
}
else {
alert(msg);// fallback for people who does not have notification API; show alert box instead
}
}
To use this, simply write:
message("hello");
Instead of:
alert("hello");
Note: Keep in mind that it's only currently supported in Chrome, Safari, Firefox and some mobile web browsers (jan. 2014)
Find supported browsers here.
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
In my case I had in one report many different datasets to DB and Analysis Services Cube. Looks like that datasets blocked each other and generated such error. For me helped option "Use single transaction when processing the queries" in the CUBE datasource properties
You're confusing PATH and PYTHONPATH. You need to do this:
export PATH=$PATH:/home/randy/lib/python
PYTHONPATH is used by the python interpreter to determine which modules to load.
PATH is used by the shell to determine which executables to run.
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
It is better to use Bypass
...
you debug it on simulator only if you don't have iPhone Developer certificate. check on left corner in xcode you select simulator not device.
You can change your second condition to check only the span element:
...and contains(div/span, 'someText')]
If the span isn't always inside another div you can also use
...and contains(.//span, 'someText')]
This searches for the span anywhere inside the div.
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.
Perhaps you should consider using a HashSet.
From the MSDN link:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
for get all
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS
for get all table name.
Try it on sqlserver,
Take note that this solution using updateConfiguration
will not be working anymore with the Android M release coming in a few weeks. The new way to do this is now using the applyOverrideConfiguration
method from ContextThemeWrapper
see API doc
You can find my full solution here since I faced the problem myself: https://stackoverflow.com/a/31787201/2776572
Well, obviously you are trying to send something which is not a string or buffer. :) It works with console, because console accepts anything. Simple example:
var obj = { test : "test" };
console.log( obj ); // works
res.write( obj ); // fails
One way to convert anything to string is to do that:
res.write( "" + obj );
whenever you are trying to send something. The other way is to call .toString()
method:
res.write( obj.toString( ) );
Note that it still might not be what you are looking for. You should always pass strings/buffers to .write
without such tricks.
As a side note: I assume that request
is a asynchronous operation. If that's the case, then res.end();
will be called before any writing, i.e. any writing will fail anyway ( because the connection will be closed at that point ). Move that line into the handler:
request({
uri: 'http://www.google.com',
method: 'GET',
maxRedirects:3
}, function(error, response, body) {
if (!error) {
res.write(response.statusCode);
} else {
//response.end(error);
res.write(error);
}
res.end( );
});
One one line (semi-colons necessary):
for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done
Formatted for legibility (no semi-colons needed):
for i in 0 1 2 3 4 5 6 7 8 9
do
for j in 0 1 2 3 4 5 6 7 8 9
do
echo "$i$j"
done
done
There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do
(saving two lines here).
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}
Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.
var element = myList.Find(e => [some condition on e]);
In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.
In your case, that would be:
var reponse = list.Find(r => r.Statement == "statement1")
And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:
var response = list.Find(delegate (Response r) {
return r.Statement == "statement1";
});
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
You could also try setting style
inline without using a variable, like so:
style={{"height" : "100%"}}
or,
for multiple attributes: style={{"height" : "100%", "width" : "50%"}}
Return a relative filepath to path either from the current directory or from an optional start point.
>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'
So, if relative path starts with '..'
- it means that the second path is not descendant of the first path.
In Python3 you can use PurePath.relative_to
:
Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path
>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')
>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')
>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
.format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'
I think there are two ways to make a div center align through CSS.
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
This is the simple and best way. for the demo please visit below link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(includes = "settingNameId, value")
then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.
I wanted a solution for this similar to apt-get --print-uris
, but unfortunately apt-cyg doesn't do this. The following is a solution that allowed me to download only the packages I needed, with their dependencies, and copy them to the target for installation. Here is a bash script that parses the output of apt-cyg
into a list of URIs:
#!/usr/bin/bash
package=$1
depends=$( \
apt-cyg depends $package \
| perl -ne 'while ($x = /> ([^>\s]+)/g) { print "$1\n"; }' \
| sort \
| uniq)
depends=$(echo -e "$depends\n$package")
for curpkg in $depends; do
if ! grep -q "^$curpkg " /etc/setup/installed.db; then
apt-cyg show $curpkg \
| perl -ne '
if ($x = /install: ([^\s]+)/) {
print "$1\n";
}
if (/\[prev\]/) {
exit;
}'
fi
done
The above will print out the paths of the packages that need downloading, relative to the cygwin mirror root, omitting any packages that are already installed. To download them, I wrote the output to a file cygwin-packages-list
and then used wget:
mirror=http://cygwin.mirror.constant.com/
uris=$(for line in $(cat cygwin-packages-list); do echo "$mirror$line"; done)
wget -x $uris
The installer can then be used to install from a local cache directory. Note that for this to work I needed to copy setup.ini
from a previous cygwin package cache to the directory with the downloaded files (otherwise the installer doesn't know what's what).
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
I think that is controlled by the expose_php
setting in PHP.ini:
expose_php = off
Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.
There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();
Those curly things are sometimes hard to remember, that's why there's excellent documentation:
// Declare a single-dimensional array
int[] array1 = new int[5];
One way to do it without spilt the code into cases
with array:
def shift(arr, dx, default_value):
result = np.empty_like(arr)
get_neg_or_none = lambda s: s if s < 0 else None
get_pos_or_none = lambda s: s if s > 0 else None
result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]
return result
with matrix it can be done like this:
def shift(image, dx, dy, default_value):
res = np.full_like(image, default_value)
get_neg_or_none = lambda s: s if s < 0 else None
get_pos_or_none = lambda s : s if s > 0 else None
res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
return res
You can insert an image that looks like a button. Then attach a script to the image.
You can insert any image. The image can be edited in the spreadsheet
Image of a Button
Assign a function name to an image:
You could subscribe for the onchange event on the input field:
<input type="file" id="file" name="file" />
and then:
document.getElementById('file').onchange = function() {
// fire the upload here
};
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.
wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate
Else taskkill /im java.exe
will work to kill all java processes
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
<fieldset>_x000D_
<legend> YOUR TITLE </legend>_x000D_
_x000D_
_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, est et illum reformidans, at lorem propriae mei. Qui legere commodo mediocritatem no. Diam consetetur._x000D_
</p>_x000D_
</fieldset>
_x000D_
This should work for you:
Dim oShell
Dim iValue
Set oShell = CreateObject("WScript.Shell")
iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")
PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
I'd rather use more convenient itemSelect
event. With this event you can use org.primefaces.event.SelectEvent
objects in your listener.
<p:selectOneMenu ...>
<p:ajax event="itemSelect"
update="messages"
listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>
With such listener:
public void onItemSelectedListener(SelectEvent event){
MyItem selectedItem = (MyItem) event.getObject();
//do something with selected value
}
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And then use it with piping:
ls -1 | python parse.py
You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control.
If possible, I suggest using your own ClassLoader so you can unload.
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
This is how I currently store a reference to the previous path in the $rootScope
:
run(['$rootScope', function($rootScope) {
$rootScope.$on('$locationChangeStart', function() {
$rootScope.previousPage = location.pathname;
});
}]);
Simply use something like the following - the string should be there already:
<?php
if(isset($_SERVER['SERVER_SOFTWARE'])){
echo $_SERVER['SERVER_SOFTWARE'];
}
?>
I used to have the same problem.
Your config use security="none" so cannot generate _csrf:
<http pattern="/login.jsp" security="none"/>
you can set access="IS_AUTHENTICATED_ANONYMOUSLY" for page /login.jsp replace above config:
<http>
<intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?error=1"
default-target-url="/index.jsp"/>
<logout/>
<csrf />
</http>
Here's what i did:
SomeActivity.java
@Override
public void onBackPressed() {
Intent newIntent = new Intent(this,QuitAppActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
finish();
}
QuitAppActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
Basically what you did is cleared all activities from the stack and launch QuitAppActivity
, that will finish the task.
Try a query like
INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;
You can use DHP to do this. It is absolutely simple and it is fast than script.
Just write alert('something');
It is not programing language it is something like a lit bit jquery. You need require dhp.php in the top and in the bottom require dhpjs.php.
For now it is not open source but when it is you can use it. It is our programing language ;)
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']
The best way I have found is to use jQuery JSON
document.getElementById()
only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
document.querySelectorAll()
that allows you to specify multiple ids in a CSS selector string .document.getElementsByClassName()
with a single class name.Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :
<Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />
in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such
<Host name="domianname" appBase="webapps2" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false" >
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
</Host>
In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
CSS
#images{
text-align:center;
margin:50px auto;
}
#images a{
margin:0px 20px;
display:inline-block;
text-decoration:none;
color:black;
}
HTML
<div id="images">
<a href="http://xyz.com/hello">
<img src="hello.png" width="100px" height="100px">
<div class="caption">Caption 1</div>
</a>
<a href="http://xyz.com/hi">
<img src="hi.png" width="100px" height="100px">
<div class="caption">Caption 2</div>
</a>
</div>?
As Yaron mentioned, there isn't any difference between where
and filter
.
filter
is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.
We can use explain()
to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name
and person_country
columns. All of the following code snippets will return the same Physical Plan below:
df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()
These all return this Physical Plan:
== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
+- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>
The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.
From Java 8 onward you can try the following:
import java.time.*;
import java.time.temporal.ChronoUnit;
Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();
System.out.println(Duration.between(start_time, stop_time).toMillis());
//or
System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));
Here's my take on it:
//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
return $('tr', $(this).find('tbody')).length;
};
USAGE:
var rowCount = $('#productTypesTable').rowCount();
So, here is the deal:
When making
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
You are passing GsonConverterFactory.create() here. If you do it like this, Gson will automatically convert the json object you get in response to your object <ResponseBody>
. Here you can pass all other converters such as Jackson, etc...
This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.
Just a necrocomment for using string.Join and LINQ.
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*",
string.Join("|", codecs.Select(codec =>
string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));
This is the workaround that worked easily for me. It isn't direct answer to the question but still may help someone.
Rather than creating notransition
class which was supposed to cancel the transition
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
I created moveTransition
class
.moveTransition {
-webkit-transition: left 3s, top 3s;
-moz-transition: left 3s, top 3s;
-o-transition: left 3s, top 3s;
transition: left 3s, top 3s;
}
Then I added this class to element with js
element.classList.add("moveTransition")
And later in setTimeout, I removed it
element.classList.remove("moveTransition")
I wasn't able to test it in different browsers but in chrome it works perfectly
You're using integer division.
Try 7.0/10
instead.
pg_ctl
is a command line (Windows) program not a SQL statement. You need to do that from a cmd.exe
. Or use net start postgresql-9.5
If you have installed Postgres through the installer, you should start the Windows service instead of running pg_ctl
manually, e.g. using:
net start postgresql-9.5
Note that the name of the service might be different in your installation. Another option is to start the service through the Windows control panel
I have used the pgAdmin II tool to create a database called company
Which means that Postgres is already running, so I don't understand why you think you need to do that again. Especially because the installer typically sets the service to start automatically when Windows is started.
The reason you are not seeing any result is that psql
requires every SQL command to be terminated with ;
in your case it's simply waiting for you to finish the statement.
See here for more details: In psql, why do some commands have no effect?
For Mac Os, command + 1 , then press control + return
This is what I have after doing purge of all the python versions and reinstalling only 3.6.
root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
Also the pip and pip3 commands are totally f up:
root@esp32:/# pip
Traceback (most recent call last):
File "/usr/local/bin/pip", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
root@esp32:/# pip3
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.
there is a ngcontentloaded
event, I think you can use it
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
$$window = $ $window
init = function(){
contentHeight = elem.outerHeight()
//do the things
}
$$window.on('ngcontentloaded',init)
}
}
});
we can change angular CLI favicon icon. we have to put icon file in "assets" folder and give that path in index.html.
<link rel="icon" type="image/x-icon" href="./assets/images/favicon.png">
It's work for me.
It depends on what you want the behaviour to be. An int
cannot hold many of the values that an unsigned int
can.
You can cast as usual:
int signedInt = (int) myUnsigned;
but this will cause problems if the unsigned
value is past the max int
can hold. This means half of the possible unsigned
values will result in erroneous behaviour unless you specifically watch out for it.
You should probably reexamine how you store values in the first place if you're having to convert for no good reason.
EDIT: As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX
and UINT_MAX
.
For the usual 4-byte types:
4 bytes = (4*8) bits = 32 bits
If all 32 bits are used, as in unsigned
, the maximum value will be 2^32 - 1, or 4,294,967,295
.
A signed int
effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647
. Note that this is half of the other value.
phpmyadmin.conf opened with apacheconf.exe and contents chained so you must do the following:
Alias /phpsysinfo "c:/wamp/apps/phpsysinfo3.1.12/"
to Alias /phpmyadmin "c:/wamp/apps/phpmyadmin4.1.14/"
<Directory c:/wamp/apps/phpsysinfo3.1.12/ />
to <Directory c:/wamp/apps/phpmyadmin4.1.14/ />
its worked for me.
You can directly use the Dimensions
module and calc your views sizes.
Actually, Dimensions
give to you the main window sizes.
import { Dimensions } from 'Dimensions';
Dimensions.get('window').height;
Dimensions.get('window').width;
Hope to help you!
Update: Today using native StyleSheet
with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...
Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components
To summarize the other answers, in <jre-path>/lib/security/java.security
you can set the value of the property networkaddress.cache.ttl
to adjust how DNS lookups are cached. Note that this is not a system property but a security property. I was able to set this using:
java.security.Security.setProperty("networkaddress.cache.ttl", "<value>");
This can also be set by the system property -Dsun.net.inetaddr.ttl
though this will not override a security property if it is set elsewhere.
I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting networkaddress.cache.ttl
will not be enough. You need to set the system property disableWSAddressCaching
to true
. Unlike the time-to-live property, this can be set as a JVM argument or via System.setProperty
).
IBM has a pretty detailed post on how WebSphere handles DNS caching here. The relevant piece to the above is:
To disable address caching for Web services, you need to set an additional JVM custom property disableWSAddressCaching to true. Use this property to disable address caching for Web services. If your system typically runs with lots of client threads, and you encounter lock contention on the wsAddrCache cache, you can set this custom property to true, to prevent caching of the Web services data.
$scope.printDiv = function(divName) {
var printContents = document.getElementById(divName).innerHTML;
var popupWin = window.open('', '_blank', 'width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
popupWin.document.close();
}
This code works great for preparing the dynamic values Array for spinner in Android:
List<String> yearStringList = new ArrayList<>();
yearStringList.add("2017");
yearStringList.add("2018");
yearStringList.add("2019");
String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);
This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.
SELECT number, COUNT(*)
FROM YourTable
GROUP BY number
ORDER BY number
Dears,
Please try : npm install -g react-native-cli
If you get an error like Cannot find module ‘npmlog’ you can install npm directly using this command. If the above command run successfully then no need to run this command
curl -0 -L https://npmjs.org/install.sh | sudo sh
#For_Ubuntu.
Best regards.
Further hint: If you don't need those information you can change the Table Type to "Blackhole" (instead of InnoDB). This means, nothing will be stored in the future and the insert statements are still working fine.
You can also disable the logs by setting all events to disabled:
System.out.println
System
is a class in the java.lang
package.
out
is a static
data member of the System
class and references a variable of the PrintStream
class.
Using the int value 1002
seems to work for PHP 5.3.0:
public static function createDB() {
$dbHost="localhost";
$dbName="project";
$dbUser="admin";
$dbPassword="whatever";
$dbOptions=array(1002 => 'SET NAMES utf8',);
return new DB($dbHost, $dbName, $dbUser, $dbPassword,$dbOptions);
}
function createConnexion() {
return new PDO(
"mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser,
$this->dbPassword,
$this->dbOptions);
}
Starting from Oracle 12.2, you don't need the TABLE
function, you can directly select from the built-in collection.
SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);
COLUMN_VALUE
------------
5
2
6
3
78
SQL> select * FROM sys.odcivarchar2list('A','B','C','D');
COLUMN_VALUE
------------
A
B
C
D
You could use the pickle
module in the standard library.
Here's an elementary application of it to your example:
import pickle
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
with open('company_data.pkl', 'wb') as output:
company1 = Company('banana', 40)
pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)
company2 = Company('spam', 42)
pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)
del company1
del company2
with open('company_data.pkl', 'rb') as input:
company1 = pickle.load(input)
print(company1.name) # -> banana
print(company1.value) # -> 40
company2 = pickle.load(input)
print(company2.name) # -> spam
print(company2.value) # -> 42
You could also define your own simple utility like the following which opens a file and writes a single object to it:
def save_object(obj, filename):
with open(filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
# sample usage
save_object(company1, 'company1.pkl')
Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.
cPickle
(or _pickle
) vs pickle
It's almost always preferable to actually use the cPickle
module rather than pickle
because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import
statement to this:
import cPickle as pickle
In Python 3, cPickle
was renamed _pickle
, but doing this is no longer necessary since the pickle
module now does it automatically—see What difference between pickle and _pickle in python 3?.
The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:
try:
import cPickle as pickle
except ModuleNotFoundError:
import pickle
pickle
can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0
, but in Python 3.8.1, it's Protocol version 4
. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL
added to it, but that doesn't exist in Python 2.
Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL
in every call (assuming that's what you want, and you usually do), just use the literal number -1
— similar to referencing the last element of a sequence via a negative index.
So, instead of writing:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
You can just write:
pickle.dump(obj, output, -1)
Either way, you'd only have specify the protocol once if you created a Pickler
object for use in multiple pickle operations:
pickler = pickle.Pickler(output, -1)
pickler.dump(obj1)
pickler.dump(obj2)
etc...
Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).
While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list
, tuple
, or dict
and write them all to the file in a single call:
tech_companies = [
Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')
and restore the list and everything in it later with:
with open('tech_companies.pkl', 'rb') as input:
tech_companies = pickle.load(input)
The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:
class Company:
def __init__(self, name, value):
self.name = name
self.value = value
def pickled_items(filename):
""" Unpickle a file of pickled data. """
with open(filename, "rb") as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
print(' name: {}, value: {}'.format(company.name, company.value))
Try these functions,
var JsonToArray = function(json)
{
var str = JSON.stringify(json, null, 0);
var ret = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
ret[i] = str.charCodeAt(i);
}
return ret
};
var binArrayToJson = function(binArray)
{
var str = "";
for (var i = 0; i < binArray.length; i++) {
str += String.fromCharCode(parseInt(binArray[i]));
}
return JSON.parse(str)
}
source: https://gist.github.com/tomfa/706d10fed78c497731ac, kudos to Tomfa
If you are using WAMP then type the following in the browser
http://localhost/?phpinfo=-1,
you will get the phpinfo page.
You can also click the localhost icon in the wamp menu from the systray and then find the phpinfo page. WAMP localhost from WAMP Menu
From VS2019 Project Properties - Advanced - Advanced Properties - Character Set
Also if there is _UNICODE;UNICODE Preprocessors Definitions remove them. Project Properties - C/C++ - Preprocessor - Preprocessor Definition
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
Table setup:
CREATE TABLE dbo.tbl (
action VARCHAR(20) NOT NULL,
view_edit VARCHAR(20) NOT NULL
);
INSERT INTO dbo.tbl (action, view_edit)
VALUES ('Action1', 'VIEW'),
('Action1', 'EDIT'),
('Action2', 'VIEW'),
('Action3', 'VIEW'),
('Action3', 'EDIT');
Your table:
SELECT action, view_edit FROM dbo.tbl
Query without using PIVOT:
SELECT Action,
[View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'),
[Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT')
FROM tbl t
GROUP BY Action
Query using PIVOT:
SELECT [Action], [View], [Edit] FROM
(SELECT [Action], view_edit FROM tbl) AS t1
PIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2
Both queries result:
Try adding this to your where
clause:
dateadd(day, -30, getdate())
You should be able to do something like this:
http://maps.google.com/maps?q=24.197611,120.780512
Some more info on the query parameters available at this location
Here's another link to an SO thread
The android docs warn about things dissappearing due to round-off error... Perhaps try dp instead of px, and perhaps also try > 1 first to see if it is the round-off problem.
see http://developer.android.com/guide/practices/screens_support.html#testing
for the section "Images with 1 pixel height/width"
Unfortunately, as far as I know, the requests library is not equipped for performing asynchronous requests. You can wrap async/await
syntax around requests
, but that will make the underlying requests no less synchronous. If you want true async requests, you must use other tooling that provides it. One such solution is aiohttp
(Python 3.5.3+). It works well in my experience using it with the Python 3.7 async/await
syntax. Below I write three implementations of performing n web requests using
sync_requests_get_all
) using the Python requests
libraryasync_requests_get_all
) using the Python requests
library wrapped in Python 3.7 async/await
syntax and asyncio
async_aiohttp_get_all
) with the Python aiohttp
library wrapped in Python 3.7 async/await
syntax and asyncio
import time
import asyncio
import requests
import aiohttp
from types import SimpleNamespace
durations = []
def timed(func):
"""
records approximate durations of function calls
"""
def wrapper(*args, **kwargs):
start = time.time()
print(f'{func.__name__:<30} started')
result = func(*args, **kwargs)
duration = f'{func.__name__:<30} finished in {time.time() - start:.2f} seconds'
print(duration)
durations.append(duration)
return result
return wrapper
async def fetch(url, session):
"""
asynchronous get request
"""
async with session.get(url) as response:
response_json = await response.json()
return SimpleNamespace(**response_json)
async def fetch_many(loop, urls):
"""
many asynchronous get requests, gathered
"""
async with aiohttp.ClientSession() as session:
tasks = [loop.create_task(fetch(url, session)) for url in urls]
return await asyncio.gather(*tasks)
@timed
def sync_requests_get_all(urls):
"""
performs synchronous get requests
"""
# use session to reduce network overhead
session = requests.Session()
return [SimpleNamespace(**session.get(url).json()) for url in urls]
@timed
def async_requests_get_all(urls):
"""
asynchronous wrapper around synchronous requests
"""
loop = asyncio.get_event_loop()
# use session to reduce network overhead
session = requests.Session()
async def async_get(url):
return session.get(url)
async_tasks = [loop.create_task(async_get(url)) for url in urls]
return loop.run_until_complete(asyncio.gather(*async_tasks))
@timed
def asnyc_aiohttp_get_all(urls):
"""
performs asynchronous get requests
"""
loop = asyncio.get_event_loop()
return loop.run_until_complete(fetch_many(loop, urls))
if __name__ == '__main__':
# this endpoint takes ~3 seconds to respond,
# so a purely synchronous implementation should take
# little more than 30 seconds and a purely asynchronous
# implementation should take little more than 3 seconds.
urls = ['https://postman-echo.com/delay/3']*10
sync_requests_get_all(urls)
async_requests_get_all(urls)
asnyc_aiohttp_get_all(urls)
print('----------------------')
[print(duration) for duration in durations]
On my machine, this is the output:
sync_requests_get_all started
sync_requests_get_all finished in 30.92 seconds
async_requests_get_all started
async_requests_get_all finished in 30.87 seconds
asnyc_aiohttp_get_all started
asnyc_aiohttp_get_all finished in 3.22 seconds
----------------------
sync_requests_get_all finished in 30.92 seconds
async_requests_get_all finished in 30.87 seconds
asnyc_aiohttp_get_all finished in 3.22 seconds
I'll explain it in a simple way.
Generics defined at Class level are completely separate from the generics defined at the (static) method level.
class Greet<T> {
public static <T> void sayHello(T obj) {
System.out.println("Hello " + obj);
}
}
When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.
class Greet<T> {
public static <E> void sayHello(E obj) {
System.out.println("Hello " + obj);
}
}
Why the static method needs to have its own generics separate from those of the Class?
This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.
So, whenever you are calling the static method,
Greet.sayHello("Bob");
Greet.sayHello(123);
JVM interprets it as the following.
Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);
Both giving the same outputs.
Hello Bob
Hello 123
Use setText(str)
method of JLabel
to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);
open node.js command prompt
run this command
node -v
Make the class serializable by implementing the interface java.io.Serializable
.
java.io.Serializable
- Marker Interface which does not have any methods in it.ObjectOutputStream
that this object is a serializable object.In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
I went with the direct-approach and just implemented the thing:
public class CollectSingle<T> implements Collector<T, T, T>, BiConsumer<T, T>, Function<T, T>, Supplier<T> {
T value;
@Override
public Supplier<T> supplier() {
return this;
}
@Override
public BiConsumer<T, T> accumulator() {
return this;
}
@Override
public BinaryOperator<T> combiner() {
return null;
}
@Override
public Function<T, T> finisher() {
return this;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
@Override //accumulator
public void accept(T ignore, T nvalue) {
if (value != null) {
throw new UnsupportedOperationException("Collect single only supports single element, "
+ value + " and " + nvalue + " found.");
}
value = nvalue;
}
@Override //supplier
public T get() {
value = null; //reset for reuse
return value;
}
@Override //finisher
public T apply(T t) {
return value;
}
}
with the JUnit test:
public class CollectSingleTest {
@Test
public void collectOne( ) {
List<Integer> lst = new ArrayList<>();
lst.add(7);
Integer o = lst.stream().collect( new CollectSingle<>());
System.out.println(o);
}
@Test(expected = UnsupportedOperationException.class)
public void failOnTwo( ) {
List<Integer> lst = new ArrayList<>();
lst.add(7);
lst.add(8);
Integer o = lst.stream().collect( new CollectSingle<>());
}
}
This implementation not threadsafe.
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
Here is what I use
function windowSizes(){
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
};
}
$(window).on('resize', function () {
console.log( windowSizes().width,windowSizes().height );
});
Simply run a while loop that will continue to loop (and increase the number) until the number is divisible by 6.
while ($number % 6 != 0) {
$number++;
}
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
use this
if (userProfile.AccountType == AccountType.Retailer)
{
...
}
If you want to get int from your AccountType enum and compare it (don't know why) do this:
if((int)userProfile.AccountType == 1)
{
...
}
Objet reference not set to an instance of an object
exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.
EDIT (thanks to @Rik and @KonradMorawski) :
Maybe you can do some check before:
if(userProfile!=null)
{
}
or
if(userProfile==null)
{
throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
From the PHP documentation for htmlentities:
This function is identical to
htmlspecialchars()
in all ways, except withhtmlentities()
, all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for htmlspecialchars:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use
htmlentities()
instead.
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use htmlspecialchars
whenever possible.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
Just change the "application/json" to "text/plain" and do not forget the JSON.stringify(request):
var request = {Company: sapws.dbName, UserName: username, Password: userpass};
console.log(request);
$.ajax({
type: "POST",
url: this.wsUrl + "/Login",
contentType: "text/plain",
data: JSON.stringify(request),
crossDomain: true,
});
You can use like this too:
SELECT * FROM fiberbox WHERE fiber IN('140 ', '1938 ', '1940 ')
Working Cross-browser Solution
This problem has been plaguing us all for years.
To help in all cases, I have laid out the CSS only approach, and a jQuery approach in case the css caveats are a problem.
Here's a CSS only solution I came up with that works in all circumstances, with a few minor caveats.
The basics are simple, it hides the overflow of the span, and sets the max height based on the line height as suggested by Eugene Xa.
Then there is a pseudo class after the containing div that places the ellipsis nicely.
Caveats
This solution will always place the ellipsis, regardless if there is need for it.
If the last line ends with an ending sentence, you will end up with four dots....
You will need to be happy with justified text alignment.
The ellipsis will be to the right of the text, which can look sloppy.
Code + Snippet
.text {_x000D_
position: relative;_x000D_
font-size: 14px;_x000D_
color: black;_x000D_
width: 250px; /* Could be anything you like. */_x000D_
}_x000D_
_x000D_
.text-concat {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
word-wrap: break-word;_x000D_
overflow: hidden;_x000D_
max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */_x000D_
line-height: 1.2em;_x000D_
text-align:justify;_x000D_
}_x000D_
_x000D_
.text.ellipsis::after {_x000D_
content: "...";_x000D_
position: absolute;_x000D_
right: -12px; _x000D_
bottom: 4px;_x000D_
}_x000D_
_x000D_
/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
_x000D_
<div class="text ellipsis">_x000D_
<span class="text-concat">_x000D_
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in._x000D_
_x000D_
Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri._x000D_
</span>_x000D_
</div>
_x000D_
jQuery Approach
In my opinion this is the best solution, but not everyone can use JS. Basically, the jQuery will check any .text element, and if there are more chars than the preset max var, it will cut the rest off and add an ellipsis.
There are no caveats to this approach, however this code example is meant only to demonstrate the basic idea - I wouldn't use this in production without improving on it for a two reasons:
1) It will rewrite the inner html of .text elems. whether needed or not. 2) It does no test to check that the inner html has no nested elems - so you are relying a lot on the author to use the .text correctly.
Thanks for the catch @markzzz
Code & Snippet
setTimeout(function()_x000D_
{_x000D_
var max = 200;_x000D_
var tot, str;_x000D_
$('.text').each(function() {_x000D_
str = String($(this).html());_x000D_
tot = str.length;_x000D_
str = (tot <= max)_x000D_
? str_x000D_
: str.substring(0,(max + 1))+"...";_x000D_
$(this).html(str);_x000D_
});_x000D_
},500); // Delayed for example only.
_x000D_
.text {_x000D_
position: relative;_x000D_
font-size: 14px;_x000D_
color: black;_x000D_
font-family: sans-serif;_x000D_
width: 250px; /* Could be anything you like. */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young._x000D_
</p>_x000D_
_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth;_x000D_
</p>_x000D_
<!-- Working Cross-browser Solution_x000D_
_x000D_
This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->
_x000D_
UPDATE:
The original answer is now obsolete. Mongodb now supports advanced full text searching, with many features.
ORIGINAL ANSWER:
It should be noted that searching with regex's case insensitive /i means that mongodb cannot search by index, so queries against large datasets can take a long time.
Even with small datasets, it's not very efficient. You take a far bigger cpu hit than your query warrants, which could become an issue if you are trying to achieve scale.
As an alternative, you can store an uppercase copy and search against that. For instance, I have a User table that has a username which is mixed case, but the id is an uppercase copy of the username. This ensures case-sensitive duplication is impossible (having both "Foo" and "foo" will not be allowed), and I can search by id = username.toUpperCase() to get a case-insensitive search for username.
If your field is large, such as a message body, duplicating data is probably not a good option. I believe using an extraneous indexer like Apache Lucene is the best option in that case.
In my case I had virtual dir. When I accessed main WCF Service in main dir it was working fine but accessing WCF service in virtual dir was throwing an error. I had following code in web.config for both main and virtual dir.
<security>
<requestFiltering>
<denyQueryStringSequences>
<add sequence=".." />
</denyQueryStringSequences>
</requestFiltering>
</security>
by removing from web.config in virtual dir it fixed it.
By default ls -t
sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.
For the newest 5 files ordered from newest to oldest, use head
to take the first 5 lines of output:
ls -t | head -n 5
For the newest 5 files ordered from oldest to newest, use the -r
switch to reverse ls
's sort order, and use tail
to take the last 5 lines of output:
ls -tr | tail -n 5
You can't access your fieldname
as a global variable. Use document.getElementById:
function updateInput(ish){
document.getElementById("fieldname").value = ish;
}
and
onchange="updateInput(this.value)"
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();
The above snippet will have two strings separated by a new line irrespective of platforms.
for (Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}
Works like a charm.
I made this for another project using random and time. I used a general format from time you can view the documentation here for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.
import time
import random
def get_random_date():
return strftime("%Y-%m-%d %H:%M:%S",(random.randrange(2000,2016),random.randrange(1,12),
random.randrange(1,28),random.randrange(1,24),random.randrange(1,60),random.randrange(1,60),random.randrange(1,7),random.randrange(0,366),1))
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
The best way to convert it to HashMap<String, Object>
is this:
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));
For iPhone cocoa-touch projects:
I had this problem and thanks to Eric Farraro's comment, I was able to get it resolved. I was importing a class WSHelper.h in many of my other classes. But I also was importing some of those same classes in my WSHelper.h (circular like Eric said). So, to fix this I moved the imports from my WSHelper.h file to my WSHelper.m file as they weren't really needed in the .h file anyway.
Use the observer pattern. It works like this:
interface MyListener{
void somethingHappened();
}
public class MyForm implements MyListener{
MyClass myClass;
public MyForm(){
this.myClass = new MyClass();
myClass.addListener(this);
}
public void somethingHappened(){
System.out.println("Called me!");
}
}
public class MyClass{
private List<MyListener> listeners = new ArrayList<MyListener>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
void notifySomethingHappened(){
for(MyListener listener : listeners){
listener.somethingHappened();
}
}
}
You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.
This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.
In my example:
MyClass
is the producer here as its notifying a list of listeners.
MyListener
is the interface.
MyForm
is interested in when somethingHappened
, so it is implementing MyListener
and registering itself with MyClass
. Now MyClass
can inform MyForm
about events without directly referencing MyForm
. This is the strength of the observer pattern, it reduces dependency and increases reusability.
First I just find in npm module mongodb the file index.js ..node_modules\mongodb\node_modules\bson\ext\index.js
and change path to js version in catch block
bson = require('../build/Release/bson'); to bson = require('../browser_build/bson');
but then I just changed it like this, all the similar... previously installed the module... : bson = require('bson');
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)
and reading a bigint at
BigInteger n = new BigInteger(input.readLine());
so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);
Constructor used: BigInteger(String val)
Aslo change while((str=input.readLine())!=null && str.length()!=0)
to
while((str=input.readLine())!=null)
see related post string to bigint
readLine()
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
see javadocs
abs()
:
Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.
Also it works on complex variable also i.e. abs(a+bj)
also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)
math.fabs()
:
It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).
For CURLOPT_POSTFIELDS
, the parameters can either be passed as a urlencoded string like para1=val1¶2=val2&..
or as an array with the field name as key and field data as value
Try the following format :
$data = json_encode(array(
"first" => "John",
"last" => "Smith"
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
in your code, just after 'do while' statement, add this line..
`Wscript.sleep 10000`
This will let your script sleep for 10 secs and let your system take rest. Else your processor will be running this script million times a second and this will definitely load your processor.
To kill it, just goto taskmanager and kill wscript.exe or if it is not found, you will find cscript.exe, kill it pressing delete button. These would be present in process tab of your taskmanager.
Once you add that line in code, I dont think you need to kill this process. It will not load your CPU.
Have a great day.
If your system is using SELinux, make sure that you use the right context for the directory you created:
ls -dZ /data/db/
ls -dZ /var/lib/mongo/
and clone the context with:
chcon -R --reference=/var/lib/mongo /data/db
Use Open XML.
Here is some code to process a spreadsheet with a specific tab or sheet name and dump it to something like CSV. (I chose a pipe instead of comma).
I wish it was easier to get the value from a cell, but I think this is what we are stuck with. You can see that I reference the MSDN documents where I got most of this code. That is what Microsoft recommends.
/// <summary>
/// Got code from: https://msdn.microsoft.com/en-us/library/office/gg575571.aspx
/// </summary>
[Test]
public void WriteOutExcelFile()
{
var fileName = "ExcelFiles\\File_With_Many_Tabs.xlsx";
var sheetName = "Submission Form"; // Existing tab name.
using (var document = SpreadsheetDocument.Open(fileName, isEditable: false))
{
var workbookPart = document.WorkbookPart;
var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id));
var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
foreach (var row in sheetData.Elements<Row>())
{
foreach (var cell in row.Elements<Cell>())
{
Console.Write("|" + GetCellValue(cell, workbookPart));
}
Console.Write("\n");
}
}
}
/// <summary>
/// Got code from: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx
/// </summary>
/// <param name="cell"></param>
/// <param name="workbookPart"></param>
/// <returns></returns>
private string GetCellValue(Cell cell, WorkbookPart workbookPart)
{
if (cell == null)
{
return null;
}
var value = cell.CellFormula != null
? cell.CellValue.InnerText
: cell.InnerText.Trim();
// If the cell represents an integer number, you are done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and
// Booleans individually. For shared strings, the code
// looks up the corresponding value in the shared string
// table. For Booleans, the code converts the value into
// the words TRUE or FALSE.
if (cell.DataType == null)
{
return value;
}
switch (cell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the
// shared strings table.
var stringTable =
workbookPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
// If the shared string table is missing, something
// is wrong. Return the index that is in
// the cell. Otherwise, look up the correct text in
// the table.
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
default:
value = "TRUE";
break;
}
break;
}
return value;
}
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
If the reason for allowing if (aBooleanVariable) return; someMoreCode;
is to allow flags, then the fact that if (true) return; someMoreCode;
does not generate a compile time error seems like inconsistency in the policy of generating CodeNotReachable exception, since the compiler 'knows' that true
is not a flag (not a variable).
Two other ways which might be interesting, but don't apply to switching off part of a method's code as well as if (true) return
:
Now, instead of saying if (true) return;
you might want to say assert false
and add -ea OR -ea package OR -ea className
to the jvm arguments. The good point is that this allows for some granularity and requires adding an extra parameter to the jvm invocation so there is no need of setting a DEBUG flag in the code, but by added argument at runtime, which is useful when the target is not the developer machine and recompiling & transferring bytecode takes time.
There is also the System.exit(0)
way, but this might be an overkill, if you put it in Java in a JSP then it will terminate the server.
Apart from that Java is by-design a 'nanny' language, I would rather use something native like C/C++ for more control.
No, but you can detect what mouse button was used in the "onmousedown" event... and from there determine if it was a "right-click".
The general solution to interpreting a char as a string is string("HELLO"[1])
.
Rich's solution also works, of course.
XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Ps. You have to use .Root on any of these versions.
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
To put it all together, this is what it should look like:
In the controller:
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
Then in the view:
@foreach (var item in ViewBag.Funds)
{
<span> @item.FundName </span>
}
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
This was the first result on "longest string in postgres" google search so I'll put my answer here for those looking for a postgres solution.
SELECT max(char_length(column)) AS Max_Length_String FROM table
postgres docs: http://www.postgresql.org/docs/9.2/static/functions-string.html
In Swift 5, in order to sort Dictionary by KEYS
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })
In order to sort Dictionary by VALUES
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })
Here is some more cool knowledge to go with this:
I had a situation where I needed to be able to find folders based on a bit of criteria in the record and then open the folder(s) that were found. While doing work on finding a solution I created a small database that asks for a search starting folder gives a place for 4 pieces of criteria and then allows the user to do criteria matching that opens the 4 (or more) possible folders that match the entered criteria.
Here is the whole code on the form:
Option Compare Database
Option Explicit
Private Sub cmdChooseFolder_Click()
Dim inputFileDialog As FileDialog
Dim folderChosenPath As Variant
If MsgBox("Clear List?", vbYesNo, "Clear List") = vbYes Then DoCmd.RunSQL "DELETE * FROM tblFileList"
Me.sfrmFolderList.Requery
Set inputFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
With inputFileDialog
.Title = "Select Folder to Start with"
.AllowMultiSelect = False
If .Show = False Then Exit Sub
folderChosenPath = .SelectedItems(1)
End With
Me.txtStartPath = folderChosenPath
Call subListFolders(Me.txtStartPath, 1)
End Sub
Private Sub cmdFindFolderPiece_Click()
Dim strCriteria As String
Dim varCriteria As Variant
Dim varIndex As Variant
Dim intIndex As Integer
varCriteria = Array(Nz(Me.txtSerial, "Null"), Nz(Me.txtCustomerOrder, "Null"), Nz(Me.txtAXProject, "Null"), Nz(Me.txtWorkOrder, "Null"))
intIndex = 0
For Each varIndex In varCriteria
strCriteria = varCriteria(intIndex)
If strCriteria <> "Null" Then
Call fnFindFoldersWithCriteria(TrailingSlash(Me.txtStartPath), strCriteria, 1)
End If
intIndex = intIndex + 1
Next varIndex
Set varIndex = Nothing
Set varCriteria = Nothing
strCriteria = ""
End Sub
Private Function fnFindFoldersWithCriteria(ByVal strStartPath As String, ByVal strCriteria As String, intCounter As Integer)
Dim fso As New FileSystemObject
Dim fldrStartFolder As Folder
Dim subfldrInStart As Folder
Dim subfldrInSubFolder As Folder
Dim subfldrInSubSubFolder As String
Dim strActionLog As String
Set fldrStartFolder = fso.GetFolder(strStartPath)
' Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(fldrStartFolder.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
If fnCompareCriteriaWithFolderName(fldrStartFolder.Name, strCriteria) Then
' Debug.Print "Found and Opening: " & fldrStartFolder.Name & "Because of: " & strCriteria
Shell "EXPLORER.EXE" & " " & Chr(34) & fldrStartFolder.Path & Chr(34), vbNormalFocus
Else
For Each subfldrInStart In fldrStartFolder.SubFolders
intCounter = intCounter + 1
Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(subfldrInStart.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
If fnCompareCriteriaWithFolderName(subfldrInStart.Name, strCriteria) Then
' Debug.Print "Found and Opening: " & subfldrInStart.Name & "Because of: " & strCriteria
Shell "EXPLORER.EXE" & " " & Chr(34) & subfldrInStart.Path & Chr(34), vbNormalFocus
Else
Call fnFindFoldersWithCriteria(subfldrInStart, strCriteria, intCounter)
End If
Me.txtProcessed = intCounter
Me.txtProcessed.Requery
Next
End If
Set fldrStartFolder = Nothing
Set subfldrInStart = Nothing
Set subfldrInSubFolder = Nothing
Set fso = Nothing
End Function
Private Function fnCompareCriteriaWithFolderName(strFolderName As String, strCriteria As String) As Boolean
fnCompareCriteriaWithFolderName = False
fnCompareCriteriaWithFolderName = InStr(1, Replace(strFolderName, " ", "", 1, , vbTextCompare), Replace(strCriteria, " ", "", 1, , vbTextCompare), vbTextCompare) > 0
End Function
Private Sub subListFolders(ByVal strFolders As String, intCounter As Integer)
Dim dbs As Database
Dim fso As New FileSystemObject
Dim fldFolders As Folder
Dim fldr As Folder
Dim subfldr As Folder
Dim sfldFolders As String
Dim strSQL As String
Set fldFolders = fso.GetFolder(TrailingSlash(strFolders))
Set dbs = CurrentDb
strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldFolders.Path & Chr(34) & ", " & Chr(34) & fldFolders.Name & Chr(34) & ", '" & fldFolders.Size & "')"
dbs.Execute strSQL
For Each fldr In fldFolders.SubFolders
intCounter = intCounter + 1
strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldr.Path & Chr(34) & ", " & Chr(34) & fldr.Name & Chr(34) & ", '" & fldr.Size & "')"
dbs.Execute strSQL
For Each subfldr In fldr.SubFolders
intCounter = intCounter + 1
sfldFolders = subfldr.Path
Call subListFolders(sfldFolders, intCounter)
Me.sfrmFolderList.Requery
Next
Me.txtListed = intCounter
Me.txtListed.Requery
Next
Set fldFolders = Nothing
Set fldr = Nothing
Set subfldr = Nothing
Set dbs = Nothing
End Sub
Private Function TrailingSlash(varIn As Variant) As String
If Len(varIn) > 0& Then
If Right(varIn, 1&) = "\" Then
TrailingSlash = varIn
Else
TrailingSlash = varIn & "\"
End If
End If
End Function
The form has a subform based on the table, the form has 4 text boxes for the criteria, 2 buttons leading to the click procedures and 1 other text box to store the string for the start folder. There are 2 text boxes that are used to show the number of folders listed and the number processed when searching them for the criteria.
If I had the Rep I would post a picture... :/
I have some other things I wanted to add to this code but haven't had the chance yet. I want to have a way to store the ones that worked in another table or get the user to mark them as good to store.
I can not claim full credit for all the code, I cobbled some of it together from stuff I found all around, even in other posts on stackoverflow.
I really like the idea of posting questions here and then answering them yourself because as the linked article says, it makes it easy to find the answer for later reference.
When I finish the other parts I want to add I will post the code for that too. :)
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
Please check the below code, where I have used Tree data structures, without using Collection classes. The code may have bugs/improvements but please use this just for reference
package com.datastructure.tree;
public class BinaryTreeWithoutRecursion <T> {
private TreeNode<T> root;
public BinaryTreeWithoutRecursion (){
root = null;
}
public void insert(T data){
root =insert(root, data);
}
public TreeNode<T> insert(TreeNode<T> node, T data ){
TreeNode<T> newNode = new TreeNode<>();
newNode.data = data;
newNode.right = newNode.left = null;
if(node==null){
node = newNode;
return node;
}
Queue<TreeNode<T>> queue = new Queue<TreeNode<T>>();
queue.enque(node);
while(!queue.isEmpty()){
TreeNode<T> temp= queue.deque();
if(temp.left!=null){
queue.enque(temp.left);
}else
{
temp.left = newNode;
queue =null;
return node;
}
if(temp.right!=null){
queue.enque(temp.right);
}else
{
temp.right = newNode;
queue =null;
return node;
}
}
queue=null;
return node;
}
public void inOrderPrint(TreeNode<T> root){
if(root!=null){
inOrderPrint(root.left);
System.out.println(root.data);
inOrderPrint(root.right);
}
}
public void postOrderPrint(TreeNode<T> root){
if(root!=null){
postOrderPrint(root.left);
postOrderPrint(root.right);
System.out.println(root.data);
}
}
public void preOrderPrint(){
preOrderPrint(root);
}
public void inOrderPrint(){
inOrderPrint(root);
}
public void postOrderPrint(){
inOrderPrint(root);
}
public void preOrderPrint(TreeNode<T> root){
if(root!=null){
System.out.println(root.data);
preOrderPrint(root.left);
preOrderPrint(root.right);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTreeWithoutRecursion <Integer> ls= new BinaryTreeWithoutRecursion <>();
ls.insert(1);
ls.insert(2);
ls.insert(3);
ls.insert(4);
ls.insert(5);
ls.insert(6);
ls.insert(7);
//ls.preOrderPrint();
ls.inOrderPrint();
//ls.postOrderPrint();
}
}
As it turns out the answer is always simple.
Here is a small sample module with a simple way to show it in a main
definition:
def five(enterAnumber,sumation):
global helper
helper = enterAnumber + sumation
def isTheNumber():
return helper
Here is how to show it in a main
definition:
import TestPy
def main():
atest = TestPy
atest.five(5,8)
print(atest.isTheNumber())
if __name__ == '__main__':
main()
This simple code works just like that, and it will execute. I hope it helps.
When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.
How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.
You probably want git checkout master
, or git checkout [branchname]
.
This probably isn't the best way for your particular problem, but you can use the String.matches(String regex)
method or the matcher equivalent. We just need to construct a regular expression from your prospective title. Here it gets complex.
List<DVD> matchingDvds(String titleFragment) {
String escapedFragment = Pattern.quote(titleFragment);
// The pattern may have contained an asterisk, dollar sign, etc.
// For example, M*A*S*H, directed by Robert Altman.
Pattern pat = Pattern.compile(escapedFragment, Pattern.CASE_INSENSITIVE);
List<DVD> foundDvds = new ArrayList<>();
for (DVD dvd: catalog) {
Matcher m = pat.matcher(dvd.getTitle());
if (m.find()) {
foundDvds.add(dvd);
}
}
return foundDvds;
}
But this is inefficient, and it's being done purely in Java. You would do better to try one of these techniques:
Collator
and CollationKey
classes.boolean matches(String fragment)
. Have the DVD tell you what it matches.title
column of the DVD
table that way. Use JDBC or Hibernate or JPA or Spring Data, whichever you choose.Apache Lucene
and possibly Apache Solr
.If you can wait until Java 8, use lambda expressions. You can avoid the Pattern and Matcher class that I used above by building the regex this way:
String escapedFragment = Pattern.quote(titleFragment);
String fragmentAnywhereInString = ".*" + escapedFragment + ".*";
String caseInsensitiveFragment = "(?i)" + fragmentAnywhereInString;
// and in the loop, use:
if(dvd.getTitle().matches(caseInsensitiveFragment)) {
foundDvds.add(dvd);
}
But this compiles the pattern too many times. What about lower-casing everything?
if (dvd.getTitle().toLowerCase().contains(titleFragment.toLowerCase()))
Congratulations; you've just discovered the Turkish problem. Unless you state the locale in toLowerCase
, Java finds the current locale. And the lower-casing is slow because it has to take into account the Turkish dotless i and dotted I. At least you have no patterns and no matchers.
Pass -noverify
JVM argument to your test task. If you are using gradle, in the build.gradle
you can have something like:
test {
jvmArgs "-noverify"
}
try ToString method for your desirer format use
DateTime.Now.ToString("yyyy-MM-dd");
OR you can use it with your variable of DateTime type
dt.ToString("yyyy-MM-dd");
where dt is a DateTime variable
You can use getenv
function and don't have to work with a $_SERVER
variable:
getenv('REQUEST_METHOD');
More info:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/
If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.
In Bundle ID Suffix you should write full name of bundle ID.
Example:
Bundle ID suffix = thebestapp (NOT CORRECT!!!!)
Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)
The reason for this is explained in the Developer Portal:
The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g.
ABCDE12345
), and an App ID Suffix (a Bundle ID search string, e.g.com.mycompany.appname
). [emphasis added]
So in this case the suffix is the full string com.awesomeapps.thebestapp
.
as an alternative way you can also try this that may be usefull in some situations
display:table;
I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists).
Let say I have:
List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");
And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)
Using org.apache.commons.collections.CollectionUtils
List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));
Result
["key1", "key6"]
Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.
isFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// do the heavy process
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
Hope this will help you. Correct me If have missed anything.
In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.
As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.
var player = makeGamePlayer("John Smith", 15, 3);
The code above calls function makeGamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function makeGamePlayer(name, totalScore, gamesPlayed) {
// Define desired object
var obj = {
name: name,
totalScore: totalScore,
gamesPlayed: gamesPlayed
};
// Return it
return obj;
}
Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this
inside the function. In the case above, since makeGamePlayer
is not called as a method, the this
value will be the global object in sloppy mode, or undefined in strict mode.
As constructors, you can use the new
operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:
.prototype
of the constructorthis
valuevar player = new GamePlayer("John Smith", 15, 3);
The code above creates an instance of GamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function GamePlayer(name,totalScore,gamesPlayed) {
// `this` is the instance which is currently being created
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
// No need to return, but you can use `return this;` if you want
}
By convention, constructor names begin with an uppercase letter.
The advantage of using constructors is that the instances inherit from GamePlayer.prototype
. Then, you can define properties there and make them available in all instances
My approach. Tricky, but works well for me
<p> </p>
Just for completion: All the answers above are going for a shallow copy - keeping the reference of the original objects. I you want a deep copy, your (reference-) class in the list have to implement a clone / copy method, which provides a deep copy of a single object. Then you can use:
newList.addAll(oldList.stream().map(s->s.clone()).collect(Collectors.toList()));
This code will work properly:
/* ??? ????*/
.div-live {
text-align: center;
}
.span-live {
display: inline-block;
color: #b5b5b5;
}
.span-live:before,
.span-live:after {
border-top: 1px solid #b5b5b5;
display: block;
height: 1px;
content: " ";
width: 30%;
position: absolute;
left: 0;
top: 3rem;
}
.span-live:after {
right: 0;
left: auto;
}
_x000D_
<div class="div-live">
<span class="span-live">??? ????</span>
</div>
_x000D_
Not a C# specific thing, but I am a ternary operations junkie.
Instead of
if (boolean Condition)
{
//Do Function
}
else
{
//Do something else
}
you can use a succinct
booleanCondtion ? true operation : false operation;
e.g.
Instead of
int value = param;
if (doubleValue)
{
value *= 2;
}
else
{
value *= 3;
}
you can type
int value = param * (tripleValue ? 3 : 2);
It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless
Use the facebook lintter available here. http://developers.facebook.com/tools/lint/
This will check your link and re fetch any images. this also clears any old cache.
Or try this - https://developers.facebook.com/tools/debug
The default parser can parse your input. So you don't need a custom formatter and
String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);
works as expected.
Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:
// Can pass browser type
if brower.lower() == 'chrome':
driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
ch_Options = Options()
ch_Options.add_argument('--headless')
ch_Options.add_argument("--disable-gpu")
driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
ff_option = FFOption()
ff_option.add_argument('--headless')
ff_option.add_argument("--disable-gpu")
driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
raise Exception('Invalid Browser Type')
The reason not to use ICloneable is not because it doesn't have a generic interface. The reason not to use it is because it's vague. It doesn't make clear whether you're getting a shallow or a deep copy; that's up to the implementer.
Yes, MemberwiseClone
makes a shallow copy, but the opposite of MemberwiseClone
isn't Clone
; it would be, perhaps, DeepClone
, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.)
What I usually do is simply make a Copy
method that does exactly what I want.
You can subtract the time zone difference from now.
final Calendar calendar = Calendar.getInstance();
final int utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long tempDate = new Date().getTime();
return new Date(tempDate - utcOffset);
I've found one more solution to follow the map render:
<tbody>{this.getcontent()}</tbody>
And a separate function:
getcontent() {
const bodyarea = this.state.movies.map(movies => (
<tr key={movies._id}>
<td>{movies.title}</td>
<td>{movies.genre.name}</td>
<td>{movies.numberInStock}</td>
<td>{movies.publishDate}</td>
<td>
<button
onClick={this.deletMovie.bind(this, movies._id)}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
));
return bodyarea;
}
This example solves many problems easily.
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :
var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects); //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
list_Objects.sort(function(a,b){
return a["name"].localeCompare(b["name"]);
});
Console.log(list_Objects); //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words
\bmyWord\b
\<myWord\>
Hear me now and believe me later, this ugly syntax is what you need to use:
/[[:<:]]myWord[[:>:]]/
So, for example, to replace mint with minty for whole words only:
sed "s/[[:<:]]mint[[:>:]]/minty/g"
Source: re_format man page
Android actually has an API for this! The method is setMediaPlaybackRequiresUserGesture(). I found it after a lot of digging into video autoplay and a lot of attempted hacks from SO. Here's an example from blair vanderhoof:
package com.example.myProject;
import android.os.Bundle;
import org.apache.cordova.*;
import android.webkit.WebSettings;
public class myProject extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
WebSettings ws = super.appView.getSettings();
ws.setMediaPlaybackRequiresUserGesture(false);
}
}
This may seem like a shot in the dark but make sure PHP has been complied with OpenSSL if SMTP requires SSL.
To check use phpinfo()
Hope it helps!
You can do it, but not at the point you've specified. Within the context of B
, you may invoke A.X()
by calling base.X()
.
Coordinate[] coordinates = new Coordinate[3];
coordinates[0] = new Coordinate(102, 26);
coordinates[1] = new Coordinate(103, 25.12);
coordinates[2] = new Coordinate(104, 16.11);
CoordinateSequence coordinateSequence = new CoordinateArraySequence(coordinates);
Geometry geo = new LineString(coordinateSequence, geometryFactory);
CoordinateReferenceSystem wgs84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem cartesinaCrs = DefaultGeocentricCRS.CARTESIAN;
MathTransform mathTransform = CRS.findMathTransform(wgs84, cartesinaCrs, true);
Geometry geo1 = JTS.transform(geo, mathTransform);
You have to install the full JDK, not only the JRE.
I had the same issue and solved by installing JDK.
Please use this link to download the latest JDK version 15.0.2.
When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block. Example:
...
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN
BEGIN
SELECT final_grade
INTO v_final_grade
FROM enrollment
WHERE student_id = v_student_id
AND section_id = v_section_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_final_grade := NULL;
END;
CASE -- outer CASE
WHEN v_final_grade IS NULL THEN
...
There might be a better way, but this here's one approach:
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
df = pd.DataFrame(df.row.str.split(' ',1).tolist(),
columns = ['flips','row'])
flips row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
It is better to use C++ string class instead of old style C string, life would be much easier.
if you have existing old style string, you can covert to string class
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
string trueString = string (greeting);
cout << trueString + "and there \n"; // compiles fine
cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too
Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.
Though I do like this one:
for (float f = 16777216f; f < 16777217f; f++) { }
I had the same problem, and my solution is changing the support version '27.+'(27.1.0) to '27.0.1'
I have found the simplest (cheap and cheerful) solution is simply add an empty span with ng-show = "someFunctionThatAlwaysReturnsZeroOrNothing()" to the end of the last element rendered. This function will be run when to check if the span element should be displayed. Execute any other code in this function.
I realize this is not the most elegant way to do things, however, it works for me...
I had a similar situation, though slightly reversed where I needed to remove a loading indicator when an animation began, on mobile devices angular was initializing much faster than the animation to be displayed, and using an ng-cloak was insufficient as the loading indicator was removed well before any real data was displayed. In this case I just added the my return 0 function to the first rendered element, and in that function flipped the var that hides the loading indicator. (of course I added an ng-hide to the loading indicator triggered by this function.
select datediff(day,
dateadd(day, 0, dateadd(month, ((2013 - 1900) * 12) + 3 - 1, 0)),
dateadd(day, 0, dateadd(month, ((2013 - 1900) * 12) + 3, 0))
)
Nice Simple and does not require creating any functions Work Fine
If you have a lateinit
property in one class and need to check if it is initialized from another class
if(foo::file.isInitialized) // this wouldn't work
The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.
Example:
class Foo() {
private lateinit var myFile: File
fun isFileInitialised() = ::file.isInitialized
}
// in another class
class Bar() {
val foo = Foo()
if(foo.isFileInitialised()) // this should work
}
Swift 3 syntax:
tableView.tableFooterView = UIView(frame: .zero)
Swift syntax: < 2.0
tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
Swift 2.0 syntax:
tableView.tableFooterView = UIView(frame: CGRect.zero)
Always preferred using a connection service file (lookup/google 'psql connection service file')
Then simply:
psql service={yourservicename} < {myfile.sql}
Where yourservicename
is a section name from the service file.
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Just updated from angular 1.2 to 1.3, have found a problem in the code. Transforming a resource will lead to an endless-loop because (I think) of the $promise holding again the same object. Maybe it will help someone...
I could fix that by:
[...]
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
angular.forEach(obj, function(value, name) {
+ if(name.indexOf("$promise") != -1) {
+ return;
+ }
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
[...]
I had to restart the rails application on the production so I looked for an another answer. I have found it below:
http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger
In Laravel 5.x you can use laravelcollective/html and the syntax:
{!! Html::image('img/logo.png') !!}
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"