I'm going to test adding the no-store tag to our site to see if this makes a difference to browser caching (Chrome has sometimes been caching the pages). I also found this article very useful on documentation on how and why caching works and will look at ETag's next if the no-store is not reliable:
git fetch origin
git reset --hard origin/master
git pull
Explanation:
See documentation at http://git-scm.com/docs.
Just use:
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
The success
property requires only a reference to a function, and passes the data as parameter to this function.
You can access your handleData
function like this because of the way handleData
is declared. JavaScript will parse your code for function declarations before running it, so you'll be able to use the function in code that's before the actual declaration. This is known as hoisting.
This doesn't count for functions declared like this, though:
var myfunction = function(){}
Those are only available when the interpreter passed them.
See this question for more information about the 2 ways of declaring functions
As an aside to the solutions here, there are cleaner alternatives if you're using certain development servers.
With Heroku's Foreman, you can create per-project environment variables in a .env
file:
ADMIN_PASSOWRD="secret"
With Pow, you can use a .powenv
file:
export ADMIN_PASSOWRD="secret"
In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%'
there
are position
(reversed order of args) and strpos
.
SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0
Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain %
and especially _
(single char wildcard), to give no false positives.
You Can Follow These Steps.
pip install jupyterthemes
or pip install --upgrade jupyterthemes
to upgrade to latest version of theme.jt -l
jt-t <themename>
for example jt -t solarizedl
In case you want to check if multiple env variables are not set, you can do the following:
import os
MANDATORY_ENV_VARS = ["FOO", "BAR"]
for var in MANDATORY_ENV_VARS:
if var not in os.environ:
raise EnvironmentError("Failed because {} is not set.".format(var))
Per the official guide, use of
pylab
is no longer recommended.matplotlib.pyplot
should be used directly instead.
Globally setting font sizes via rcParams
should be done with
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
The defaults can be restored using
plt.rcParams.update(plt.rcParamsDefault)
You can also do this by creating a style sheet in the stylelib
directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()
). The style sheet format is
axes.labelsize: 16
axes.titlesize: 16
If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle
then you can use it via
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
You can also create (or modify) a matplotlibrc file which shares the format
axes.labelsize = 16
axes.titlesize = 16
Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.
A complete list of the rcParams
keys can be retrieved via plt.rcParams.keys()
, but for adjusting font sizes you have (italics quoted from here)
axes.labelsize
- Fontsize of the x and y labelsaxes.titlesize
- Fontsize of the axes titlefigure.titlesize
- Size of the figure title (Figure.suptitle()
)xtick.labelsize
- Fontsize of the tick labelsytick.labelsize
- Fontsize of the tick labelslegend.fontsize
- Fontsize for legends (plt.legend()
, fig.legend()
)legend.title_fontsize
- Fontsize for legend titles, None
sets to the same as the default axes. See this answer for usage example.all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}
or a float
in pt
. The string sizes are defined relative to the default font size which is specified by
font.size
- the default font size for text, given in pts. 10 pt is the standard valueAdditionally, the weight can be specified (though only for the default it appears) by
font.weight
- The default weight of the font used by text.Text
. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900}
or 'normal'
(400), 'bold'
(700), 'lighter'
, and 'bolder'
(relative with respect to current weight).More clear example with es6 destructing
class Form extends Component {
constructor(props) {
super(props);
this.state = {
login: null,
password: null,
email: null
}
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
let login = this.state.login;
let password = this.state.password;
// etc
}
render() {
return (
<form onSubmit={this.onSubmit.bind(this)}>
<input type="text" name="login" onChange={this.onChange.bind(this)} />
<input type="password" name="password" onChange={this.onChange.bind(this)} />
<input type="email" name="email" onChange={this.onChange.bind(this)} />
<button type="submit">Sign Up</button>
</form>
);
}
}
BCrypt is a very good library, and there is a Java port of it.
In your view:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
@endif
@endforeach
</div>
Then set a flash message in the controller:
Session::flash('alert-danger', 'danger');
Session::flash('alert-warning', 'warning');
Session::flash('alert-success', 'success');
Session::flash('alert-info', 'info');
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
Without changing the position to absolute, see below. This supports all recent browsers as well.
.vranger {_x000D_
margin-top: 50px;_x000D_
transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
for very old browsers, you can use -sand-transform: rotate(10deg);
from CSS sandpaper
or use
prefix selector such as -ms-transform: rotate(270deg);
for IE9
I would do something like this but i bet there is a simpler way. i think the sql from linqtosql would use a select from person Where NOT EXIST(select from your exclusion list)
static class Program
{
public class Person
{
public string Key { get; set; }
public Person(string key)
{
Key = key;
}
}
public class NotPerson
{
public string Key { get; set; }
public NotPerson(string key)
{
Key = key;
}
}
static void Main()
{
List<Person> persons = new List<Person>()
{
new Person ("1"),
new Person ("2"),
new Person ("3"),
new Person ("4")
};
List<NotPerson> notpersons = new List<NotPerson>()
{
new NotPerson ("3"),
new NotPerson ("4")
};
var filteredResults = from n in persons
where !notpersons.Any(y => n.Key == y.Key)
select n;
foreach (var item in filteredResults)
{
Console.WriteLine(item.Key);
}
}
}
Pure bash solution for comparing floats without exponential notation, leading or trailing zeros:
if [ ${FOO%.*} -eq ${BAR%.*} ] && [ ${FOO#*.} \> ${BAR#*.} ] || [ ${FOO%.*} -gt ${BAR%.*} ]; then
echo "${FOO} > ${BAR}";
else
echo "${FOO} <= ${BAR}";
fi
Order of logical operators matters. Integer parts are compared as numbers and fractional parts are intentionally compared as strings. Variables are split into integer and fractional parts using this method.
Won't compare floats with integers (without dot).
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
You can use switch-case fall through by omitting the break;
statement.
char c = /* whatever */;
switch(c) {
case 'a':
case 'A':
//get the 'A' image;
break;
case 'b':
case 'B':
//get the 'B' image;
break;
// (...)
case 'z':
case 'Z':
//get the 'Z' image;
break;
}
...or you could just normalize to lower case or upper case before switch
ing.
char c = Character.toUpperCase(/* whatever */);
switch(c) {
case 'A':
//get the 'A' image;
break;
case 'B':
//get the 'B' image;
break;
// (...)
case 'Z':
//get the 'Z' image;
break;
}
This was the solution for me. Connect as you would to debug via wifi:
Make sure your phone is connected by usb. Then open your command prompt as admin and navigate to YourAndroidSdkLocation\platform-tools
, and do:
adb tcpip 5555
adb connect YOUR_DEVICE_IP
At this point my device successfully came online, giving me the option to debug via both usb or wifi.
Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:
var temp1;
if ( temp1 )... // false
var temp2 = true;
if ( temp2 )... // true
var temp3 = "";
if ( temp3 ).... // false
var temp4 = "hello world";
if ( temp4 )... // true
Hopefully that helps?
Also, its worth checking out these videos from Douglas Crockford
update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now
Besides the other answers. You should notice these args can give you the file path that was dragged and dropped on the .exe
file.
i.e if you drag and drop any file on your .exe
file then the application will be launched and the arg[0]
will contain the file path that was dropped onto it.
static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
this will print the path of the file dropped on the .exe
file. e.g
C:\Users\ABCXYZ\source\repos\ConsoleTest\ConsoleTest\bin\Debug\ConsoleTest.pdb
Hence, looping through the args
array will give you the path of all the files that were selected and dragged and dropped onto the .exe
file of your console app. See:
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadLine();
}
The code sample above will print all the file names that were dragged and dropped onto it, See I am dragging 5 files onto my ConsoleTest.exe
app.
You can try this one-liner which preserves soft-deletes also:
Model::whereRaw('1=1')->delete();
I think sometimes stupid mistakes can give us this error.
<div id="#main"> <--- id with hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
To
<div id="main"> <--- id without hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
works for me from Pardeep Jain
I hope you are trying to run the main class in this way, see screenshot:
If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:
public static void main(String[] args) {
// some code here
}
I hope this will help you.
You can provide a tag inside your activity layout xml file.
Supply the android:tag attribute
with a unique string.
Just as you would assign an id in a layout xml.
android:tag="unique_tag"
var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
});
console.log(isValid);
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
The sequence is CR (Carriage Return) - LF (Line Feed). Remember dot matrix printers? Exactly. So - the correct order is \r \n
As the error says, you should specify the datatypes when using the read_csv()
method.
So, you should write
file = pd.read_csv('example.csv', dtype='unicode')
Make sure, that all of your class methods (updateVelocity
, updatePosition
, ...) take at least one positional argument, which is canonically named self
and refers to the current instance of the class.
When you call particle.updateVelocity()
, the called method implicitly gets an argument: the instance, here particle
as first parameter.
You can use selectedOptions
var selectedValues = Array.from(document.getElementById('select-meal-type').selectedOptions).map(el=>el.value);
console.log(selectedValues);
_x000D_
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2" selected>Lunch</option>
<option value="3">Dinner</option>
<option value="4" selected>Snacks</option>
<option value="5">Dessert</option>
</select>
_x000D_
It's optional.
The port may be specified so cookies can be port specific. It's not necessary, the web server / application must care of this.
Source: German Wikipedia article, RFC2109, Chapter 4.3.1
inside your project directory, run:
./gradlew clean build
or from Android Studio select:
Build > Clean Project
Updated: As @VinceFior pointed out in a comment below
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
In Python 3.5 and newer use the new recursive **/
functionality:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)
When recursive
is set, **
followed by a path separator matches 0 or more subdirectories.
In earlier Python versions, glob.glob()
cannot list files in subdirectories recursively.
In that case I'd use os.walk()
combined with fnmatch.filter()
instead:
import os
import fnmatch
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in fnmatch.filter(files, '*.txt')]
This'll walk your directories recursively and return all absolute pathnames to matching .txt
files. In this specific case the fnmatch.filter()
may be overkill, you could also use a .endswith()
test:
import os
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in files if f.endswith('.txt')]
I know it is an old question but I have found this possibility if you plan to call it often.
create procedure Table_Exists
@tbl varchar(50)
as
return (select count(*) from sysobjects where type = 'U' and name = @tbl)
go
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
Recently I am working with the 1.8.0_25 JDK version on Windows 8.1 and I had the same problem with this. But as PankaJ Jakhar said
The real solution for me was pretty simple:
The path I introduced for this variable was:
C:\Program Files\Java\jdk1.8.0_25\
And it works for me!
From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.
The file opened by codecs.open
is a file that takes unicode
data, encodes it in iso-8859-1
and writes it to the file. However, what you try to write isn't unicode
; you take unicode
and encode it in iso-8859-1
yourself. That's what the unicode.encode
method does, and the result of encoding a unicode string is a bytestring (a str
type.)
You should either use normal open()
and encode the unicode yourself, or (usually a better idea) use codecs.open()
and not encode the data yourself.
I have experimented many of the backslash escape characters. \n
which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
For people (like me) who really want PathLocationStrategy
(i.e. html5Mode) instead of HashLocationStrategy
, see How to: Configure your server to work with html5Mode from a third-party wiki:
When you have html5Mode enabled, the
#
character will no longer be used in your URLs. The#
symbol is useful because it requires no server side configuration. Without#
, the URL looks much nicer, but it also requires server side rewrites.
Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow HTML5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Documentation for rewrite module
server {
server_name my-app;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
So you're trying to get the search term and category into the URL?
I would advise against this as you'll have to deal with multi-word search terms etc, and could end up with all manner of unpleasantness with disallowed characters.
I would suggest POSTing the data, sanitising it and then returning a results page.
Laravel routing is not designed to accept GET requests from forms, it is designed to use URL segments as get parameters, and built around that idea.
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label
See this link for more on the differences between a TextBlock and other Controls
Several ways to do so, here are some possible one-line approaches:
Use getch()
(need #include <conio.h>
).
Use getchar()
(expected for Enter, need #include <iostream>
).
Use cin.get()
(expected for Enter, need #include <iostream>
).
Use system("pause")
(need #include <iostream>
).
PS: This method will also print Press any key to continue . . .
on the screen. (seems perfect choice for you :))
Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.
If the goal is to style the img after browser has rendered image, you should:
const img = new Image();
img.src = 'path/to/img.jpg';
img.decode().then(() => {
/* set styles */
/* add img to DOM */
});
because the browser first loads the compressed version of image
, then decodes it
, finally paints
it. since there is no event for paint
you should run your logic after browser has decoded
the img tag.
Try,
var newList =
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();
This is an adding to @Sam answer that though is correct is missing the fact that anytime you open a folder in visual studio code, it create a .vscode folder, but those can be multiple, created any time you eventually open a directory. The .vscode folder has JSON objects that content properties such "setting.json", in which one declare the Interpreter to use at that ".vscode" level( refer to this for more clarifications What is a 'workspace' in VS Code?).
{
{
"python.pythonPath": "VirtualEnPath/bin/python3.6"
}
}
So potentially you could open VS code at another level in the virtual Env, it create another .vscode folder that assume as Python directory those of the global machine and so having such error, and has I experienced has nothing to do if the Virtual Env is activated or not.
This indeed what happened to me, I have indeed a DjangoRESTAPI_GEN folder in which I initially opened the IDE and it did recognize the Virtual Env Python path, the a few days after I opened it at the level where git is, so it did created another .vscode, that picked the global Python Interpreter, causing my lint in the Virtual Environment not been used, and the virtual env interpreter not even showed in "select python interpreter". But as wrote opening the IDE at the level where the .vscode that has the settings.json with correct path, it does.
Once you set the correct path in the setting.json and select the virtual env interpreter, then VS Code will automatically activate the VE in its terminal
Try to use this:
position: relative;
clear: both;
I use it when I can't use absolute position, for example in printing when you use page-break-after: always;
works fine only with position:relative
.
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
I'd use a set myself, but here's yet another way:
uniquewords = []
while True:
ipta = raw_input("Word: ")
if ipta == "":
break
if not ipta in uniquewords:
uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"
I encounter this problem when creating workspace/project in eclipse 3.7.2. Then I open it using Kepler (4.3). So simply open the project by the eclipse version you created it (3.7.2 in my case) solves the problem. Hope it helps.
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
For lists, use enumerate
for field, possible_values in enumerate(fields):
print(field, possible_values)
iteritems
will not work for list objects
If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.
In your code you simply use
x1.index
and the returned array is the indexes relating to the original positions in x.
For me what works when I change the PATH is: exec "$BASH" --login
It's not implemented in C++. (also, char*
strings? I hope not).
Usually if you have so many parameters it is a fairly serious code smell. But instead, why not simply value-initialize the struct and then assign each member?
I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :(
Eventually, I decided to rebuild my Docker images, so that I change the root password by something I will know.
RUN echo 'root:Docker!' | chpasswd
or
RUN echo 'Docker!' | passwd --stdin root
I believe I found the solution in the jQuery documentation:
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it outside the queue, meaning it will automatically start without waiting for its turn.
$( "p" ).animate({ left: "50px", opacity: 1 }, { duration: 500, queue: false });
simply add: queue: false
.
Practically speaking, if the keys were of type NaN, the browser will not change the order.
The following script will output "One", "Two", "Three":
var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Whereas the following script will output "Three", "One", "Two":
var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
You need to iterate over the array
for ($i = 0, $c = count($array); $i < $c; ++$i) {
$array[$i] = (array) $array[$i];
}
ans use (array)
conversion because you have array of objects of Std class and not object itself
Example:
$users = DB::table('users')->get();
var_dump($users);
echo "<br /><br />";
for ($i = 0, $c = count($users); $i < $c; ++$i) {
$users[$i] = (array) $users[$i];
}
var_dump($users);
exit;
Output for this is:
array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }
array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }
as expected. Object of stdClass
has been converted to array.
just this as img tag is a content element
img {
content:url(http://example.com/image.png);
}
I don't like using wait
because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0
and sleep
to this.
Given an array of pids
to wait on, I use the below waitPids()
function to get a continuous feedback on what pids are still pending to finish.
declare -a pids
waitPids() {
while [ ${#pids[@]} -ne 0 ]; do
echo "Waiting for pids: ${pids[@]}"
local range=$(eval echo {0..$((${#pids[@]}-1))})
local i
for i in $range; do
if ! kill -0 ${pids[$i]} 2> /dev/null; then
echo "Done -- ${pids[$i]}"
unset pids[$i]
fi
done
pids=("${pids[@]}") # Expunge nulls created by unset.
sleep 1
done
echo "Done!"
}
When I start a process in the background, I add its pid immediately to the pids
array by using this below utility function:
addPid() {
local desc=$1
local pid=$2
echo "$desc -- $pid"
pids=(${pids[@]} $pid)
}
Here is a sample that shows how to use:
for i in {2..5}; do
sleep $i &
addPid "Sleep for $i" $!
done
waitPids
And here is how the feedback looks:
Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274
Done!
A quick reset of the form fields is possible with this jQuery reset function.
$(selector)[0].reset();
I'm pretty sure you can completely delete the <stuff> , which will generate a warning and you can use an, @ suppress warnings. If you really want it to be generic, but to use any of its elements you will have to do type casting. For instance, I made a simple bubble sort function and it uses a generic type when sorting the list, which is actually an array of Comparable in this case. If you wish to use an item, do something like: System.out.println((Double)arrayOfDoubles[0] + (Double)arrayOfDoubles[1]); because I stuffed Double(s) into Comparable(s) which is polymorphism since all Double(s) inherit from Comparable to allow easy sorting through Collections.sort()
//INDENT TO DISPLAY CODE ON STACK-OVERFLOW
@SuppressWarnings("unchecked")
public static void simpleBubbleSort_ascending(@SuppressWarnings("rawtypes") Comparable[] arrayOfDoubles)
{
//VARS
//looping
int end = arrayOfDoubles.length - 1;//the last index in our loops
int iterationsMax = arrayOfDoubles.length - 1;
//swapping
@SuppressWarnings("rawtypes")
Comparable tempSwap = 0.0;//a temporary double used in the swap process
int elementP1 = 1;//element + 1, an index for comparing and swapping
//CODE
//do up to 'iterationsMax' many iterations
for (int iteration = 0; iteration < iterationsMax; iteration++)
{
//go through each element and compare it to the next element
for (int element = 0; element < end; element++)
{
elementP1 = element + 1;
//if the elements need to be swapped, swap them
if (arrayOfDoubles[element].compareTo(arrayOfDoubles[elementP1])==1)
{
//swap
tempSwap = arrayOfDoubles[element];
arrayOfDoubles[element] = arrayOfDoubles[elementP1];
arrayOfDoubles[elementP1] = tempSwap;
}
}
}
}//END public static void simpleBubbleSort_ascending(double[] arrayOfDoubles)
check /Library/PostgreSQL/9.3/bin and you should find pg_config
I.E. /Library/PostgreSQL/<version_num>/
ps: you can do the following if you deem it necessary for your pg needs -
create a .profile in your ~ directory
export PG_HOME=/Library/PostgreSQL/9.3
export PATH=$PATH:$PG_HOME/bin
You can now use psql
or postgres
commands from the terminal, and install psycopg2 or any other dependency without issues, plus you can always just ls $PG_HOME/bin
when you feel like peeking at your pg_dir.
You can transform logical implication A => B
to NOT A or B
. This is one of the most basic laws of logic. In your case it is something like this:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic.
You CAN get version from command line.
hive> select version();
OK
1.1.0-cdh5.12.0 rUnknown
Time taken: 2.815 seconds, Fetched: 1 row(s)
hive>
Try this:
(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-3)
}).Count
Please use sorted() function in Python3
items = ["love", "like", "play", "cool", "my"]
sorted(items2)
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
I found a slight variation on #6 package is out of date from the excellent solution by @Richie Cotton.
Sometimes the package maintainer may show R version gaps that it does not support. In that case, you have at least two options: 1) upgrade your R version to the next one the target package already supports, 2) install the most recent version from the older ones available that would work with your R version.
A concrete example: the latest CRAN version of package rattle
for data mining, 5.3.0, does not support R version 3.4 because it had a big update between package versions 5.2.0 (R >= 2.13.0) and 5.3.0 (R >=3.5).
In a case like this, the alternative to upgrading the R installation is the solution already mentioned. Install the package devtools
if you don't have it (it includes package remotes
) and then install the specific version that will work in your current R. You can look up that information on the CRAN page for the specific package archives.
library("devtools")
install_version("rattle", version = "5.2.0", repos = "http://cran.us.r-project.org")
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
I know this is an old question but I fought with this same issue all day and my solution was a simple one.
I had my directory structure something along the lines of...
apps/
app/
__init__.py
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
And since all the other models up until the one I had a problem with were being imported somewhere else that ended up importing from main_app
which was registered in the INSTALLED_APPS
, I just got lucky that they all worked.
But since I only added each app
to INSTALLED_APPS
and not the app_sub*
when I finally added a new models file that wasn't imported ANYWHERE else, Django totally ignored it.
My fix was adding a models.py
file to the base directory of each app
like this...
apps/
app/
__init__.py
models.py <<<<<<<<<<--------------------------
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
models.py <<<<<<<<<<--------------------------
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
and then add from apps.app.app_sub1 import *
and so on to each of the app
level models.py
files.
Bleh... this took me SO long to figure out and I couldn't find the solution anywhere... I even went to page 2 of the google results.
Hope this helps someone!
I have found that in some cases too much memory can slow the program down.
For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.
The solution was to evict the old objects from the session.
Stuart
Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Here,
this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field
oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.
font-weight: bold
Important Note: Alert of Future Deprecation.
As of iOS 9.0, the API functions description for:
AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)
includes the following note:
This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or
AudioServicesPlaySystemSoundWithCompletion instead.
The right way to go will be using any of these two:
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)
or
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
//your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}
remember to
import AVFoundation
For org.json I've rolled out my own solution, a method that compares to JSONObject instances. I didn't work with complex JSON objects in that project, so I don't know whether this works in all scenarios. Also, given that I use this in unit tests, I didn't put effort into optimizations. Here it is:
public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException {
if (js1 == null || js2 == null) {
return (js1 == js2);
}
List<String> l1 = Arrays.asList(JSONObject.getNames(js1));
Collections.sort(l1);
List<String> l2 = Arrays.asList(JSONObject.getNames(js2));
Collections.sort(l2);
if (!l1.equals(l2)) {
return false;
}
for (String key : l1) {
Object val1 = js1.get(key);
Object val2 = js2.get(key);
if (val1 instanceof JSONObject) {
if (!(val2 instanceof JSONObject)) {
return false;
}
if (!jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) {
return false;
}
}
if (val1 == null) {
if (val2 != null) {
return false;
}
} else if (!val1.equals(val2)) {
return false;
}
}
return true;
}
inplace=True
is used depending if you want to make changes to the original df or not.
df.drop_duplicates()
will only make a view of dropped values but not make any changes to df
df.drop_duplicates(inplace = True)
will drop values and make changes to df.
Hope this helps.:)
you can use enum constructor for enum to have primitive data type..
public enum DaysOfWeek {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);
private int value;
private DaysOfWeek(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
private static final SparseArray<DaysOfWeek> map = new SparseArray<DaysOfWeek>();
static
{
for (DaysOfWeek daysOfWeek : DaysOfWeek.values())
map.put(daysOfWeek.value, daysOfWeek);
}
public static DaysOfWeek from(int value) {
return map.get(value);
}
}
you can use to pass int as extras then pull it from enum using its value.
If you are using kotlin you can try the following code,
In the sending activity,
val intent = Intent(context, RecorderService::class.java);
intent.putExtra("filename", filename);
context.startService(intent)
In the service,
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
if (intent != null && intent.extras != null)
val filename = intent.getStringExtra("filename")
}
The latest PowerShell version as of Sept 2015 is PowerShell 4.0. It's bundled with Windows Management Framework 4.0.
Here's the download page for PowerShelll 4.0 for all versions of Windows. For Windows 7, there are 2 links on that page, 1 for x64 and 1 for x86.
In my case the issue was the Google services gradle plugin with the following line in the gradle file:
apply plugin: 'com.google.gms.google-services'
Removing this resolved the issue
Entity-Framework Select Distinct Name:
Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....
public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo)
{
var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
return Result.Distinct().ToList();
}
Or you can try this Simple Example
Public Function GetUniqueLocation() As List(Of Integer)
Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function
group by fV.tier_id, f.form_template_id
You can use it to raise errors as part of error-checking:
if (a < b):
raise ValueError()
Or handle some errors, and then pass them on as part of error-handling:
try:
f = open('file.txt', 'r')
except IOError:
# do some processing here
# and then pass the error on
raise
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
This problem is probably from your /etc/apt/sources.list as others mentioned but there is chance that the problem is with your hard disk. I solved the same issue by cleaning up some space.
When you don't have enough space on your hard disk, updating your machine won't occur until you delete some files.
Developing on Windows, I ran into this problem when using git tfs
. I solved it this way:
git config --global core.whitespace cr-at-eol
This basically tells Git that an end-of-line CR is not an error. As a result, those annoying ^M
characters no longer appear at the end of lines in git diff
, git show
, etc.
It appears to leave other settings as-is; for instance, extra spaces at the end of a line still show as errors (highlighted in red) in the diff.
(Other answers have alluded to this, but the above is exactly how to set the setting. To set the setting for only one project, omit the --global
.)
EDIT:
After many line-ending travails, I've had the best luck, when working on a .NET team, with these settings:
If you need to use the whitespace setting, you should probably enable it only on a per-project basis if you need to interact with TFS. Just omit the --global
:
git config core.whitespace cr-at-eol
If you need to remove some core.* settings, the easiest way is to run this command:
git config --global -e
This opens your global .gitconfig file in a text editor, and you can easily delete the lines you want to remove. (Or you can put '#' in front of them to comment them out.)
There are different ways to do so. You can use DateTime.Now.ToLongTimeString()
which
returns only the time in string format.
Search in your web.config
or App.Config
if you have some tags that are not used in your project or you don't have in your references.
Listing all foreign keys in a db including description
SELECT
i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
i2.UPDATE_RULE, i2.DELETE_RULE
FROM
information_schema.KEY_COLUMN_USAGE AS i1
INNER JOIN
information_schema.REFERENTIAL_CONSTRAINTS AS i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL
AND i1.TABLE_SCHEMA ='db_name';
restricting to a specific column in a table table
AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'
{{-- Google Language Translator START --}}
<style>
.google-translate {
display: inline-block;
vertical-align: top;
padding-top: 15px;
}
.goog-logo-link {
display: none !important;
}
.goog-te-gadget {
color: transparent !important;
}
#google_translate_element {
display: none;
}
.goog-te-banner-frame.skiptranslate {
display: none !important;
}
body {
top: 0px !important;
}
</style>
<script src="{{asset('js/translate-google.js')}}"></script>
<script type="text/javascript">
function googleTranslateElementInit2(){
new google.translate.TranslateElement({
pageLanguage:'en',
includedLanguages: 'en,es',
// https://ctrlq.org/code/19899-google-translate-languages
// includedLanguages: 'en,it,la,fr',
// layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
autoDisplay:true
},'google_translate_element2');
var a = document.querySelector("#google_translate_element select");
// console.log(a);
if(a){
a.selectedIndex=1;
a.dispatchEvent(new Event('change'));
}
}
</script>
<ul class="navbar-nav my-lg-0 m-r-10">
<li>
<div class="google-translate">
<div id="google_translate_element2"></div>
</div>
</li>
{{-- Google Language Translator ENDS --}}
// translate-google.js
(function () {
var gtConstEvalStartTime = new Date();
function d(b) {
var a = document.getElementsByTagName("head")[0];
a || (a = document.body.parentNode.appendChild(document.createElement("head")));
a.appendChild(b)
}
function _loadJs(b) {
// console.log(b);
var a = document.createElement("script");
a.type = "text/javascript";
a.charset = "UTF-8";
a.src = b;
d(a)
}
function _loadCss(b) {
var a = document.createElement("link");
a.type = "text/css";
a.rel = "stylesheet";
a.charset = "UTF-8";
a.href = b;
d(a)
}
function _isNS(b) {
b = b.split(".");
for (var a = window, c = 0; c < b.length; ++c)
if (!(a = a[b[c]])) return !1;
return !0
}
function _setupNS(b) {
b = b.split(".");
for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
return a
}
window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () {
document.readyState = "complete"
}, !1);
if (_isNS('google.translate.Element')) {
return
}(function () {
var c = _setupNS('google.translate._const');
c._cest = gtConstEvalStartTime;
gtConstEvalStartTime = undefined;
c._cl = 'en';
c._cuc = 'googleTranslateElementInit2';
c._cac = '';
c._cam = '';
c._ctkk = eval('((function(){var a\x3d3002255536;var b\x3d-2533142796;return 425386+\x27.\x27+(a+b)})())');
var h = 'translate.googleapis.com';
var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
var b = s + h;
c._pah = h;
c._pas = s;
c._pbi = b + '/translate_static/img/te_bk.gif';
c._pci = b + '/translate_static/img/te_ctrl3.gif';
c._pli = b + '/translate_static/img/loading.gif';
c._plla = h + '/translate_a/l';
c._pmi = b + '/translate_static/img/mini_google.png';
c._ps = b + '/translate_static/css/translateelement.css';
c._puh = 'translate.google.com';
_loadCss(c._ps);
_loadJs(b + '/translate_static/js/element/main.js');
})();
})();
NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
[persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array
also you can reach this without using NSMutableArray:
NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
persons = [persons arrayByAddingObject:[[Person alloc] init]];
}
One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!
[persons addObject:[[[Person alloc] init] autorelease];
I had this issue and I solved it by creating a directory in mysite folder to hold my db.sqlite3 file. so I did /home/user/src/mysite/database/db.sqlite3
. In my django setting file I change my
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': "/home/user/src/mysite/database/db.sqlite3" ,
}}
I did this to make Django aware that I am storing my database in a sub directory of the base directory, which mysite in my case. Now you need to grant the permission to apache to be able read write the database.
chown user:www-data database/db.sqlite3
chown user:www-data database
chmod 755 database
chmod 755 database/db.sqlite3
This solved my problem. Here is a list of the different permissions. You can use choose the one that fits you but avoid 777 and 666
-rw------- (600) -- Only the user has read and write permissions.
-rw-r--r-- (644) -- Only user has read and write permissions; the group and others can read only.
-rwx------ (700) -- Only the user has read, write and execute permissions.
-rwxr-xr-x (755) -- The user has read, write and execute permissions; the group and others can only read and execute.
-rwx--x--x (711) -- The user has read, write and execute permissions; the group and others can only execute.
-rw-rw-rw- (666) -- Everyone can read and write to the file. Bad idea.
-rwxrwxrwx (777) -- Everyone can read, write and execute. Another bad idea.
Here are a couple common settings for directories:
drwx------ (700) -- Only the user can read, write in this directory.
drwxr-xr-x (755) -- Everyone can read the directory, but its contents can only be changed by the user.
here is a link to an article to [learn more][1]
[1]: http://ftp.kh.edu.tw/Linux/Redhat/en_6.2/doc/gsg/s1-navigating-chmodnum.htm#:~:text=%2Drwxr%2Dxr%2Dx%20(,and%20others%20can%20only%20execute.
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
Please try jQuery UI dialog
Here is the forms demo
For mobile use, have a look at jQuery Mobile - Creating dialogs
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
A very old question I know but...
A pandas DataFrame seems to be the ideal option here.
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html
From the blurb
Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure
I'm the OP. After some research and testing, the answer is:
No, there is no way to do exactly that.
tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.
The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.
As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.
LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.
In Android Manifest File, put attribute for your <activity>
that android:screenOrientation="portrait"
If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b
From the first search result on google:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
JavaScriptSerializer Class
Provides serialization and deserialization functionality for AJAX-enabled applications.
Inheritance Hierarchy
System.Object
System.Web.Script.Serialization.JavaScriptSerializer
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
So, include System.Web.Extensions.dll
as a reference.
In my case, the folder was _Manager. After I renamed it to Manager it worked.
Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.
The error is because difference in datatypes of y_pred and y_true. y_true might be dataframe and y_pred is arraylist. If you convert both to arrays, then issue will get resolved.
To add to already great and easy solution provided by Przemek315, the same config if you use Kotlin DSL:
tasks.test {
useJUnitPlatform()
}
The Bootstrap Glyphicons are fonts. This means it can be changed like any other text through CSS styling.
CSS:
<style>
.glyphicon-plus {
color: #F00;
}
</style>
HTML:
<span class="glyphicon glyphicon-plus"></span>
Example:
<!doctype html>
<html>
<head>
<title>Glyphicon Colors</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.glyphicon-plus {
color: #F00;
}
</style>
</head>
<body>
<span class="glyphicon glyphicon-plus"></span>
</body>
</html>
Watch the course Up and Running with Bootstrap 3 by Jen Kramer, or watch the individual lesson on Overriding core CSS with custom styles.
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
Objective-C doesn't have named parameters, so everything on the left side of a colon is part of the method name. For example,
getBusStops: forTime:
is the name of the method. The name is broken up so it can be more descriptive. You could simply name your method
getBusStops: :
but that doesn't tell you much about the second parameter.
I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.
Here is how I call the method:
var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();
Here is the class that does the work:
Note: Since these are extension methods they need to be in a static class.
using System.IO;
using System.Xml.Serialization;
public static class XmlTools
{
public static string ToXmlString<T>(this T input)
{
using (var writer = new StringWriter())
{
input.ToXml(writer);
return writer.ToString();
}
}
private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
{
new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
}
}
On Python 3 numpy.genfromtxt
expects a bytes stream. Use the following:
numpy.genfromtxt(io.BytesIO(x.encode()))
How about this:
git log -1 $TAGNAME
OR
git log -1 origin/$TAGNAME
Let's say you work on a project and after a day or so. You notice one feature is still giving you errors. But you do not know what change you made that caused the error. So you have to fish previous working commits. To revert to a specific commit:
git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 .
Ok, so that commit works for you. No more error. You pinpointed the issue. Now you can go back to latest commit:
git checkout 792d9294f652d753514dc2033a04d742decb82a5 .
And checkout a specific file before it caused the error (in my case I use example Gemfile.lock):
git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 -- /projects/myproject/Gemfile.lock
And this is one way to handle errors you created in commits without realizing the errors until later.
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
If you've just got the iterator then that's what you'll have to do - it doesn't know how many items it's got left to iterate over, so you can't query it for that result. There are utility methods that will seem to do this efficiently (such as Iterators.size()
in Guava), but underneath they're just consuming the iterator and counting as they go, the same as in your example.
However, many iterators come from collections, which you can often query for their size. And if it's a user made class you're getting the iterator for, you could look to provide a size() method on that class.
In short, in the situation where you only have the iterator then there's no better way, but much more often than not you have access to the underlying collection or object from which you may be able to get the size directly.
pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
If you want to list all the files currently being tracked under the branch master
, you could use this command:
git ls-tree -r master --name-only
If you want a list of files that ever existed (i.e. including deleted files):
git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'
You can implement a custom serializer as follows:
public class Person {
public String name;
public int age;
@JsonSerialize(using = IntToStringSerializer.class, as=String.class)
public int favoriteNumber:
}
public class IntToStringSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer tmpInt,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeObject(tmpInt.toString());
}
}
Java should handle the autoboxing from int
to Integer
for you.
The following code will load an image from a file image.png
and will display it as grayscale.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()
If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'
.
If you're looking for a good alias to do this plus not blow up cd
if you aren't in a git dir:
alias ..g='git rev-parse && cd "$(git rev-parse --show-cdup)"'
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)
Javascripts:
var x = new XMLHttpRequest();
if(x) x.onreadystatechange=function(){
if (x.readyState === 4 && x.status===200){
console.log(x.responseText); //Success
}else{
console.log(x); //Failed
}
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();
My Chrome's request header Origin: null
My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.
header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);
I was able to successfully connect to my server.
You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic
enabled
I tested compatibility with FF and Opera, It works in many cases such as:
From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.
Put in other words, this error is telling you that SQL Server does not know which B
to select from the group.
Either you want to select one specific value (e.g. the MIN
, SUM
, or AVG
) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B
in the GROUP BY
field list).
Consider the following data:
ID A B 1 1 13 1 1 79 1 2 13 1 2 13 1 2 42
The query
SELECT A, COUNT(B) AS T1
FROM T2
GROUP BY A
would return:
A T1 1 2 2 3
which is all well and good.
However consider the following (illegal) query, which would produce this error:
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A
And its returned data set illustrating the problem:
A T1 B 1 2 13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...? 2 3 13? 42? ...?
However, the following two queries make this clear, and will not cause the error:
Using an aggregate
SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A
would return:
A T1 B 1 2 92 2 3 68
Adding the column to the GROUP BY
list
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B
would return:
A T1 B 1 1 13 1 1 79 2 2 13 2 1 42
On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:
Location of my virtual environment (named ml_venv):
/Users/auser/.pyvenv/ml_venv
auser@HOST:~/.pyvenv$ tree -d -L 2
.
+-- ml_venv
+-- bin
+-- include
+-- lib
I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"
I restarted the IDE, and now I could see the interpreter from my virtual environment:
Implementing multiple interfaces is very useful and doesn't cause much problems to language implementers nor programmers. So it is allowed. Multiple inheritance while also useful, can cause serious problems to users (dreaded diamond of death). And most things you do with multiple inheritance can be also done by composition or using inner classes. So multiple inheritance is forbidden as bringing more problems than gains.
Your if
statement is always false and T
gets initialized only if a condition is met, so the code doesn't reach the point where T
gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.
Try:
def temp_sky(lreq, breq):
T = <some_default_value> # None is often a good pick
for line in tfile:
data = line.split()
if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:
T = data[2]
return T
I know this is very old, but none of these answers helped me, so I'm adding my answer. This, like @yichengliu's answer, uses the Pseudo ::after
element.
#div {
position: relative;
}
#div::after {
content: '';
position: absolute;
right: 0;
width: 1px;
height: 100%;
z-index: -1;
-webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
-moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
}
/*or*/
.filter.right::after {
content: '';
position: absolute;
right: 0;
top: 0;
width: 1px;
height: 100%;
background: white;
z-index: -1;
-webkit-filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
}
If you decide to change the X of the drop shadow (first pixel measurement of the drop-shadow
or box-shadow
), changing the width will help so it doesn't look like there is a white gap between the div and the shadow.
If you decide to change the Y of the drop shadow (second pixel measurement of the drop-shadow
or box-shadow
), changing the height will help for the same reason as above.
You can either use
break;
or
foreach() if ($tmp++ < 2) {
}
(the second solution is even worse)
C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.
When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.
Object initializer
If your constructor with the parameter isn't doing anything besides setting a property, you can do this in C# 3 or better using an object initializer rather than calling a constructor (which is impossible, as has been mentioned):
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { YourPropertyName = listItem } ); // Now using object initializer
}
...
}
Using this, you can always put any constructor logic in the default (empty) constructor, too.
Activator.CreateInstance()
Alternatively, you could call Activator.CreateInstance() like so:
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
object[] args = new object[] { listItem };
tabListItems.Add((T)Activator.CreateInstance(typeof(T), args)); // Now using Activator.CreateInstance
}
...
}
Note that Activator.CreateInstance can have some performance overhead that you may want to avoid if execution speed is a top priority and another option is maintainable to you.
If using Vagrant try reloading your box. This solved my issue.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
From my limited experience, this happens for two main reasons:
The simple solution here is to use an error handler ending with Resume Next
If your lookup_value
is a variable you can enclose it with TRIM()
cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)
protected void Page_Load(object sender, EventArgs e)
{
DropDownTitle();
}
protected void DropDownTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
A pure CSS solution:
.frame {_x000D_
margin: 1em 0;_x000D_
height: 35px;_x000D_
width: 160px;_x000D_
border: 1px solid red;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-height: 25px;_x000D_
max-width: 160px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: auto;_x000D_
background: #3A6F9A;_x000D_
}
_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=250 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=25 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=23 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=21 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=19 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=17 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=15 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=13 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=11 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=9 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=7 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=5 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
<img src="http://jsfiddle.net/img/logo.png" height=3 />_x000D_
</div>
_x000D_
Key stuff
// position: relative; - in .frame holds the absolute element within the frame
// top: 0; bottom: 0; left: 0; right: 0; - this is key for centering a component
// margin: auto; - centers the image horizontally & vertically
With openssl
:
openssl x509 -enddate -noout -in file.pem
The output is on the form:
notAfter=Nov 3 22:23:50 2014 GMT
Also see MikeW's answer for how to easily check whether the certificate has expired or not, or whether it will within a certain time period, without having to parse the date above.
First. Assign an id to your div. Like this:
<div id="uniqueid">This text will be replaced</div>
After that, add inside your <script>
tag following code:
Document.getElementById("uniqueid").id = randomString(8);
If you are a intellij IDE user, you can use shortcut key Alt+Enter
and then choose Wrap with Center
and then add textAlign: TextAlign.center
(function ($) {
$(document).ready(function(){
$("#myspan").text("This is span");
});
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>
_x000D_
user text()
to change span text.
If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName")
- or to elaborate:
user = User()
property = "fullName"
name = getattr(user, property)
Otherwise just use user.fullName
.
if(doc.SelectSingleNode("//mynode")==null)....
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that
Give correct maven setting.xml path in eclipse.
Enter correct setting.xml path in user settings text box
Download all files from bootstrap and then include this css
<style type="text/css">
@font-face {
font-family: 'Glyphicons Halflings';
src: url('/fonts/glyphicons-halflings-regular.eot');
}
</style>
IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value
(percentage) and parameter
(parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return 0.7 * value.ToDouble();
string[] split = parameter.ToString().Split('.');
double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
return value.ToDouble() * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
}
XAML:
<UserControl.Resources>
<m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>
Try:
=ArrayFormula(QUERY(A:A&{"",""};"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'";1))
22/07/2014 Some time in the last month, Sheets has started supporting more flexible concatenation of arrays, using an embedded array. So the solution may be shortened slightly to:
=QUERY({A:A,A:A},"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'",1)
I stumbled across this page with the same issue, but the following problems:
With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:
element
.css('color','#FF0000')
;
$('<div />')
.css('width',0)
.animate(
{'width':100},
{
duration: 3000,
step:function(now){
var v = (255 - 255/100 * now).toString(16);
v = (v.length < 2 ? '0' : '') + v.substr(0,2);
element.css('color','#'+v+'0000');
}
}
)
;
The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width
- which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.
The same could have been achieved with setInterval
, but by using this method you can benefit from jQuery's animation methods - like .stop()
- and you can use easing
and duration
.
Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)
Both .done()
and .success()
are callback functions and they essentially function the same way.
Here's the documentation. The difference is that .success()
is deprecated as of jQuery 1.8. You should use .done()
instead.
In case you don't want to click the link:
Deprecation Notice
The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
Formatting your console's output as FFmpeg brings out these details.
Input #0, flv, from 'video.flv':
Duration: 00:05:01.20, start: 0.000000, bitrate: 66 kb/s
Stream #0.0: Video: h264, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 66 kb/s, 29.92 tbr, 1k tbn, 2k tbc
Stream #0.1: Audio: aac, 22050 Hz, stereo, s16
The original flv is converted to an .mp4 file with H.264 video and AAC audio (just like the original .flv):
Output #0, mp4, to 'video.mp4':
Stream #0.0: Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], q=2-31, 200 kb/s, 90k tbn, 29.92 tbc
Stream #0.1: Audio: 0x0000, 22050 Hz, stereo, s16, 64 kb/s
Because the audio and video data in the .flv are already in the format/codecs you need for the .mp4, you can just copy everything to the new .mp4 container. This process will be massively faster than decoding and reencoding everything:
ffmpeg -i video.flv -vcodec copy -acodec copy video.mp4
or more simply:
ffmpeg -i video.flv -codec copy video.mp4
Unsupported codec for output stream #0.1
Which means FFmpeg can't convert audio (stream #0.1) to AAC.
You can skip the error by:
or you can solve the error by:
For more details you should also read Converting FLV to MP4 With FFmpeg The Ultimate Guide
The node-mysql
library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values
Use GregorianCalendar
. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH)
.
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)
You can also use head
and tail
:
In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
a b
0 1 a
3 4 d
This example is from http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3
Works for me in Bootstrap v3.1.1.
<div class="container">
<div class="row">
<h2>Multi level dropdown menu in Bootstrap 3</h2>
<hr>
<div class="dropdown">
<a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
<li><a href="#">Some action</a></li>
<li><a href="#">Some other action</a></li>
<li class="divider"></li>
<li class="dropdown-submenu">
<a tabindex="-1" href="#">Hover me for more options</a>
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#">Second level</a></li>
<li class="dropdown-submenu">
<a href="#">Even More..</a>
<ul class="dropdown-menu">
<li><a href="#">3rd level</a></li>
<li><a href="#">3rd level</a></li>
</ul>
</li>
<li><a href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
</ul>
</li>
</ul>
</div>
</div>
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #fff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}
I've seen the same recommendation in Sublime Text 2.
Like it was already said, the main improvement is not evaluating the array's length at each iteration in the for loop. This a well-known optimization technique and particularly efficient in JavaScript when the array is part of the HTML document (doing a for
for the all the li
elements).
For example,
for (var i = 0; i < document.getElementsByTagName('li').length; i++)
is much slower than
for (var i = 0, len = document.getElementsByTagName('li').length; i < len; i++)
From where I'm standing, the main improvement in the form in your question is the fact that it doesn't declare an extra variable (len
in my example)
But if you ask me, the whole point is not about the i++
vs i--
optimization, but about not having to evaluate the length of the array at each iteration (you can see a benchmark test on jsperf).
Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().
var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();
This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.
ECMAScript 2016 incorporates an includes()
method for arrays that specifically solves the problem, and so is now the preferred method.
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array at which to begin searching)
As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.
Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.
Under Linux and other Unix-related systems, there are only two characters that cannot appear in the name of a file or directory, and those are NUL '\0'
and slash '/'
. The slash, of course, can appear in a path name, separating directory components.
Rumour1 has it that Steven Bourne (of 'shell' fame) had a directory containing 254 files, one for every single letter (character code) that can appear in a file name (excluding /
, '\0'
; the name .
was the current directory, of course). It was used to test the Bourne shell and routinely wrought havoc on unwary programs such as backup programs.
Other people have covered the Windows rules.
Note that MacOS X has a case-insensitive file system.
When Steve Bourne was writing his Unix shell (which came to be known as the Bourne shell), he made a directory of 254 files with one-character names, one for each byte value except
'\0'
and slash, the two characters that cannot appear in Unix file names. He used that directory for all manner of tests of pattern-matching and tokenization. (The test directory was of course created by a program.) For years afterwards, that directory was the bane of file-tree-walking programs; it tested them to destruction.
Note that the directory must have contained entries .
and ..
, so it was arguably 253 files (and 2 directories), or 255 name entries, rather than 254 files. This doesn't affect the effectiveness of the anecdote, or the careful testing it describes.
Though the question has a decent answer already, I just want to stress that the :first-child
tag goes on the item type that represents the children.
For example, in the code:
<div id"someDiv">
<input id="someInput1" />
<input id="someInput2" />
<input id="someInput2" />
</div
If you want to affect only the second two elements with a margin, but not the first, you would do:
#someDiv > input {
margin-top: 20px;
}
#someDiv > input:first-child{
margin-top: 0px;
}
that is, since the input
s are the children, you would place first-child
on the input portion of the selector.
In mysql the SET
clause needs to come after the JOIN
. Example:
UPDATE e
LEFT JOIN a ON a.id = e.aid
SET e.id = 2
WHERE
e.type = 'user' AND
a.country = 'US';
You don't need to set the value at all. ng-model takes care of it all:
Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/
(only usable if you don't need recursive deptch)
Use bookmarklet. Drag this link in bookmarks, then edit and paste this code:
(function(){ var arr=[], l=document.links; var ext=prompt("select extension for download (all links containing that, will be downloaded.", ".mp3"); for(var i=0; i<l.length; i++) { if(l[i].href.indexOf(ext) !== false){ l[i].setAttribute("download",l[i].text); l[i].click(); } } })();
and go on page (from where you want to download files), and click that bookmarklet.
IF EXISTS(SELECT * FROM MY_TABLE WHERE
(MY_FIELD1 = @IN_MY_FIELD1
or (MY_FIELD1 IS NULL and @IN_MY_FIELD1 is NULL)) AND
(MY_FIELD2 = @IN_MY_FIELD2
or (MY_FIELD2 IS NULL and @IN_MY_FIELD2 is NULL)) AND
(MY_FIELD3 = @IN_MY_FIELD3
or (MY_FIELD3 IS NULL and @IN_MY_FIELD3 is NULL)) AND
(MY_FIELD4 = @IN_MY_FIELD4
or (MY_FIELD4 IS NULL and @IN_MY_FIELD4 is NULL)) AND
(MY_FIELD5 = @IN_MY_FIELD5
or (MY_FIELD5 IS NULL and @IN_MY_FIELD5 is NULL)) AND
(MY_FIELD6 = @IN_MY_FIELD6
or (MY_FIELD6 IS NULL and @IN_MY_FIELD6 is NULL)))
BEGIN
goto on_duplicate
END
Wordy As compared to the IFNULL/COALESCE solution. But will work without having to think about what value will not appear in the data that can be used as the stand in for NULL.
I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:
plot(Time,Intensity,axes=F)
Then I rebuild the plot's elements with:
box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.
So, at = c(...)
specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...)
gives me the choice of limits and the increments.
as i also wanted that same thing in a project u can do something like
HTML
<div class="col-md-6"></div>
<div class="divider-vertical"></div>
<div class="col-md-5"></div>
CSS
.divider-vertical {
height: 100px; /* any height */
border-left: 1px solid gray; /* right or left is the same */
float: left; /* so BS grid doesn't break */
opacity: 0.5; /* optional */
margin: 0 15px; /* optional */
}
LESS
.divider-vertical(@h:100, @opa:1, @mar:15) {
height: unit(@h,px); /* change it to rem,em,etc.. */
border-left: 1px solid gray;
float: left;
opacity: @opa;
margin: 0 unit(@mar,px); /* change it to rem,em,etc.. */
}
As @Kanmani hinted, an easier to interpret implementation may use numpy.flip
, as in the following:
import numpy as np
avgDists = np.array([1, 8, 6, 9, 4])
ids = np.flip(np.argsort(avgDists))
print(ids)
By using the visitor pattern rather than member functions, it is easier to read the order of operations.
If you are like me, and manually installed your webserver without using Xampp or some other installer,
Your data is probably stored at C:\ProgramData\MySQL\MySQL Server 5.6\data
$formattedPrice = Mage::helper('core')->currency($_finalPrice,true,false);
$('#navigation ul li').css({'display' : 'inline-block'});
It seems a typo there ...syntax mistake :))
var arrays = [_x000D_
[1, 2, 3],_x000D_
[2, 3, 4, 5]_x000D_
]_x000D_
function commonValue (...arr) {_x000D_
let res = arr[0].filter(function (x) {_x000D_
return arr.every((y) => y.includes(x))_x000D_
})_x000D_
return res;_x000D_
}_x000D_
commonValue(...arrays);
_x000D_
echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only
Remove the semicolon ( ; ).
In oracle, you can use semicolon or not when u ran query directly on DB. But when u using java to ran a oracle query, u have to remove semicolon at the end.
When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi
str.split()
without any arguments splits on runs of whitespace characters:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
From the linked documentation:
If sep is not specified or is
None
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Here is a better script:
$('#mainimage').click(function(e)
{
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
alert("Left: " + left + " Top: " + top);
});
There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO
However it does not work quite the same as 'ON DUPLICATE UPDATE'
It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key
You can't reference the values in the old rows so you can't do an equivalent of
INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4)
ON DUPLICATE KEY UPDATE
id=1, a=2, b=3, c=c + 1;
I'd like to use the work around to get the ID to!
That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.
However as I said, if you actually use that primary key in other tables, REPLACE INTO
probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.
Someone else suggested before you can reduce some typing by doing:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
The path with reference to root directory is called absolute. The path with reference to current directory is called relative.
Try this function in Excel:
Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
Dim s() As String = Split(Text, SplitAt)
If ReturnZeroBasedIndex <= s.Count - 1 Then
Return s(ReturnZeroBasedIndex)
Else
Return ""
End If
End Function
You use it like this:
First Name (A1) | Last Name (A2)
Value in cell A1 = Michael Zomparelli
I want the last name in column A2.
=SPLITTEXT(A1, " ", 1)
The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli
The above function is a .Net function, but can easily be converted to VBA.
Visual Studio Code: Version: 1.53.2
If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.
Go to Edit > Replace in Files
From there it is similar to the search funtionality for a single file.
I changed the name of a class I was using across files and this worked perfectly.
Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.
For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci.certificateStatus = "TRUE";
break;
default:
dataToSend.naci.certificateStatus = "";
}
}
And because dataToSend.naci
cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci!.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci!.certificateStatus = "TRUE";
break;
default:
dataToSend.naci!.certificateStatus = "";
}
}
If you are on Azure you need you can now, you need to have Manag. Studio 2014 and update hotfix: http://blogs.msdn.com/b/sqlreleaseservices/archive/2014/12/18/sql-server-2014-management-studio-updated-support-for-the-latest-azure-sql-database-update-v12-preview.aspx
//Just use a List
//create the list
public final List<Object> myObjects;
//instantiate the list
myObjects = new ArrayList<Object>();
//add objects to the list
Object object = myObject;
myObjects.add(object);
//remove the object calling this method if you have more than 1 objects still works with 1
//object too.
private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}
Depending on how well the makefile/configure script/autofoo magic of the program in question is the following might solve your problem:
make uninstall
The problem is that you should execute this on the source tree of the version you've got installed and with exactly the same configuration that you used for installing.
It's little too late but this really works for me.
react-native run-android
.react-native start
.First command will build apk
for android and deploy it on your device if its connected. When you open the App it will show red screen with error. Then run second command which will run packager and build app bundle for you.
Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.
cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
You can do a div over the padding as follows:
<div id= "paddingOne">
</div>
<div id= "paddingTwo">
</div>
#paddingOne {
width: 100;
length: 100;
background-color: #000000;
margin: 0;
z-index: 2;
}
#paddingTwo {
width: 200;
length: 200;
background-color: #ffffff;
margin: 0;
z-index: 3;
the width, length, background color, margins, and z-index can vary of course, but in order to cover the padding, the z-index must be higher than 0 so that it will lay over the padding. You can fiddle with positioning and such to change its orientation. Hope that helps!
P.S. the divs are html and the #paddingOne and #paddingTwo are css (in case anyone didn't get that:)
In situations where the class under test can be modified and when it's desirable to avoid byte code manipulation, to keep things fast or to minimise third party dependencies, here is my take on the use of a factory to extract the new
operation.
public class TestedClass {
interface PojoFactory { Pojo getNewPojo(); }
private final PojoFactory factory;
/** For use in production - nothing needs to change. */
public TestedClass() {
this.factory = new PojoFactory() {
@Override
public Pojo getNewPojo() {
return new Pojo();
}
};
}
/** For use in testing - provide a pojo factory. */
public TestedClass(PojoFactory factory) {
this.factory = factory;
}
public void doSomething() {
Pojo pojo = this.factory.getNewPojo();
anythingCouldHappen(pojo);
}
}
With this in place, your testing, asserts and verify calls on the Pojo object are easy:
public void testSomething() {
Pojo testPojo = new Pojo();
TestedClass target = new TestedClass(new TestedClass.PojoFactory() {
@Override
public Pojo getNewPojo() {
return testPojo;
}
});
target.doSomething();
assertThat(testPojo.isLifeStillBeautiful(), is(true));
}
The only downside to this approach potentially arises if TestClass
has multiple constructors which you'd have to duplicate with the extra parameter.
For SOLID reasons you'd probably want to put the PojoFactory interface onto the Pojo class instead, and the production factory as well.
public class Pojo {
interface PojoFactory { Pojo getNewPojo(); }
public static final PojoFactory productionFactory =
new PojoFactory() {
@Override
public Pojo getNewPojo() {
return new Pojo();
}
};