Java 8
NOTE: All, but one, Date
's constructors are deprecated. Most of the Date
's methods are deprecated. REF: Date: Deprecated Methods. All, but Date::from(Instant)
, static methods are deprecated.
So, since java 8 consider using Instant
(immutable, thread-safe, leap-seconds aware) type rather than Date
. REF: Instant
static final LocalTime MARKETS_OPEN = LocalTime.of(07, 00);
static final LocalTime MARKETS_CLOSE = LocalTime.of(20, 00);
// Instant utcTime = testDate.toInstant();
var bigAppleTime = ZonedDateTime.ofInstant(utcTime, ZoneId.of("America/New_York"));
return !bigAppleTime.toLocalTime().isBefore(MARKETS_OPEN)
&& !bigAppleTime.toLocalTime().isAfter(MARKETS_CLOSE);
return bigAppleTime.toLocalTime().isAfter(MARKETS_OPEN)
&& bigAppleTime.toLocalTime().isBefore(MARKETS_CLOSE);
I'm a devops engineer and this happens with private repositories. Since I manage multiple Github organizations, I have a few different SSH keys. To overcome this ERROR: Repository not found. fatal: Could not read from remote repository.
error, you can use
export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no -o User=git -i ~/.ssh/ssh_key_for_repo"
git clone [email protected]:user/repo.git
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using only tabs or only spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
As an aside, your code is more verbose than it needs to be. Instead of this:
if str_p == str_q:
result = True
else:
result = False
return result
Just do this:
return str_p == str_q
You also appear to have a bug on this line:
str_q = p[b+1:]
I'll leave you to figure out what the error is.
You could import the 'os' module and use it like this :
import os
os.system('#DesiredAction')
If you want to do it with phpmyadmin interface:
Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key
Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.
Data comes from a txt file with the following rows:
1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200
think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.
Here is the Octave implementation:
%
% Linear Regression with multiple variables
%
% Alpha for learning curve
alphaNum = 0.0005;
% Number of features
n = 2;
% Number of iterations for Gradient Descent algorithm
iterations = 10000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DATA = load('CHANGE_WITH_DATA_FILE_PATH');
% Initial theta values
theta = ones(n + 1, 1);
% Number of training samples
m = length(DATA(:, 1));
% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
X = [X, DATA(:,i)];
endfor
% Expected data must go always in the last column
y = DATA(:, n + 1)
function gradientDescent(x, y, theta, alphaNum, iterations)
iterations = [];
costs = [];
m = length(y);
for iteration = 1:10000
hypothesis = x * theta;
loss = hypothesis - y;
% J(theta)
cost = sum(loss.^2) / (2 * m);
% Save for the graphic to see if the algorithm did work
iterations = [iterations, iteration];
costs = [costs, cost];
gradient = (x' * loss) / m; % /m is for the average
theta = theta - (alphaNum * gradient);
endfor
% Show final theta values
display(theta)
% Show J(theta) graphic evolution to check it worked, tendency must be zero
plot(iterations, costs);
endfunction
% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);
The solution for this problem is just to add overflow: auto;
to the .content for making the content wrapper scrollable.
Furthermore, there are circumstances occurring along with Flexbox wrapper and overflowed
scrollable content like this codepen.
The solution is to add overflow: hidden (or auto);
to the parent of the wrapper (set with overflow: auto;) around large contents.
@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls
:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit
:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
String str_date = "11-June-07";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = formatter.parse(str_date);
I'm sure you can use RAISERROR ... WITH NOWAIT
If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.
With jQuery, it'd be something like
if ($('input[name=gender]:checked').length > 0) {
// do something here
}
Let me break that down into pieces to cover it more clearly. jQuery processes things from left to right.
input[name=gender]:checked
input
limits it to input tags.[name=gender]
limits it to tags with the name gender within the previous group.:checked
limits it to checkboxes/radio buttons that are selected within the previous group.If you want to avoid this altogether, mark one of the radio buttons as checked (checked="checked"
) in the HTML code, which would guarantee that one radio button is always selected.
If you used the auth scaffolding in 5.5 simply direct your href
to:
{{ route('logout') }}
There is no need to alter any routes or controllers.
Use a generic Last<T>
. That will work with ANY IEnumerable
, including string.
public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
int count = Math.Min(enumerable.Count(), nLastElements);
for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
{
yield return enumerable.ElementAt(i);
}
}
And a specific one for string:
public static string Right(this string str, int nLastElements)
{
return new string(str.Last(nLastElements).ToArray());
}
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
In case it's useful to really see there is no difference between string
and System.String
:
var method1 = typeof(MyClass).GetMethod("TestString1").GetMethodBody().GetILAsByteArray();
var method2 = typeof(MyClass).GetMethod("TestString2").GetMethodBody().GetILAsByteArray();
//...
public string TestString1()
{
string str = "Hello World!";
return str;
}
public string TestString2()
{
String str = "Hello World!";
return str;
}
Both produce exactly the same IL byte array:
[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]
This is the easiest way i have found to do it.
List<List<String>> matrix= new List<List<String>>(); //Creates new nested List
matrix.Add(new List<String>()); //Adds new sub List
matrix[0].Add("2349"); //Add values to the sub List at index 0
matrix[0].Add("The Prime of Your Life");
matrix[0].Add("Daft Punk");
matrix[0].Add("Human After All");
matrix[0].Add("3");
matrix[0].Add("2");
To retrieve values is even easier
string title = matrix[0][1]; //Retrieve value at index 1 from sub List at index 0
I think this will help
<directoryBrowse enabled="false" />
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
<add value="index.php" />
</files>
</defaultDocument>
</system.webServer>
Try something like:
B = np.reshape(A,(-1,ncols))
You'll need to make sure that you can divide the number of elements in your array by ncols
though. You can also play with the order in which the numbers are pulled into B
using the order
keyword.
I run into that problem too! npm install is somewhat confusing and web posts keep bringing in the -d/--dev flags as if there is an explicit 'development' install mode.
npm install
will install both "dependencies" and "devDependencies"
npm install --production
will only install "dependencies"
npm install --dev
will only install "devDependencies"
Swift version:
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.5
You actually have one capture group that will match multiple times. Not multiple capture groups.
javascript (js) solution:
let string = "HI,THERE,TOM";
let myRegexp = /([A-Z]+),?/g; //modify as you like
let match = myRegexp.exec(string); //js function, output described below
while(match!=null){ //loops through matches
console.log(match[1]); //do whatever you want with each match
match = myRegexp.exec(bob); //find next match
}
Output:
HI
THERE
TOM
Syntax:
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
As you can see, this will work for any number of matches.
both %d
and %i
can be used to print an integer
%d stands for "decimal", and %i for "integer." You can use %x to print in hexadecimal, and %o to print in octal.
You can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal."
On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.
check here for more explanation
With Java 8 there is this API method to accomplish your requirement.
map.putIfAbsent(key, value)
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);
actually you want to get the object from the Spring engine, where the engine already maintaining the object of your required class at that starting of the spring application(Initialization of the Spring engine).Now the thing is you just have to get that object to a reference.
in a service class
@Autowired
private ApplicationContext context;
SomeClass sc = (SomeClass)context.getBean(SomeClass.class);
now in the reference of the sc you are having the object. Hope explained well. If any doubt please let me know.
Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery
$("#<%= txt_iplength.ClientID %>").val();
You need to use an ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);
Further documentation about creating parsers can be found here.
If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__,
you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__,
no need to call it. Example:
>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
__del__
is the same way, (but be wary of relying on __del__
for finalization - consider doing it via the with statement instead).
I rarely use __new__.
I do all the initialization in __init__.
Another option is to add another tag with flex: auto
style in between your tags that you want to fill in the remaining space.
https://jsfiddle.net/tsey5qu4/
The HTML:
<div class="parent">
<div class="left">Left</div>
<div class="fill-remaining-space"></div>
<div class="right">Right</div>
</div>
The CSS:
.fill-remaining-space {
flex: auto;
}
This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.
Just add 'change' listener on your input whose type is file. i.e
<input type="file" id="file_to_upload" name="file_to_upload" />
I have done using jQuery and obviously anyone can use valina JS (as per the requirement).
$("#file_to_upload").change(function() {
if (this.files.length) {
alert('file choosen');
} else {
alert('file NOT choosen');
}
});
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
If you need to know the default collation for a newly created database use:
SELECT SERVERPROPERTY('Collation')
This is the server collation for the SQL Server instance that you are running.
Also, if you don't have the gradlew file in your current directory:
You can install gradle with homebrew with the following command:
$ brew install gradle
As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):
$ gradle test
Just to provide some variation here: You could check for
if ($_SERVER["QUERY_STRING"] == null)
it is completely identical to testing $_GET
.
You can use this ShellScript to install (most) of it's dependencies, clone, build, compile and get all the necessary files into ../src/includes
folder:
https://github.com/node-tensorflow/node-tensorflow/blob/master/tools/install.sh
UPDATE 17/03/2017
Original solution won't work anymore. The spinners are part of shadow dom. For now just to hide in chrome use:
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
}
_x000D_
<input type="number" />
_x000D_
or to always show:
input[type=number]::-webkit-inner-spin-button {_x000D_
opacity: 1;_x000D_
}
_x000D_
<input type="number" />
_x000D_
You can try the following but keep in mind that works only for Chrome:
input[type=number]::-webkit-inner-spin-button { _x000D_
-webkit-appearance: none;_x000D_
cursor:pointer;_x000D_
display:block;_x000D_
width:8px;_x000D_
color: #333;_x000D_
text-align:center;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before,_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
content: "^";_x000D_
position:absolute;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before {_x000D_
top:0px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
bottom:0px;_x000D_
-webkit-transform: rotate(180deg);_x000D_
}
_x000D_
<input type="number" />
_x000D_
Usually when you want to check if a file exists, it's because you want to create that file if it doesn't. Graeme Perrow's answer is good if you don't want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have bad security implications if the file created was a symlink!)
If you want to check for existence and create the file if it doesn't exist, atomically so that there are no race conditions, then use this:
#include <fcntl.h>
#include <errno.h>
fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}
} else {
/* now you can use the file */
}
array_splice($array, 0, 1);
Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).
Also you can manually add your current directory (src in your case) to pythonpath:
import os
import sys
sys.path.insert(0, os.getcwd())
Flutter is usually installed(per illustrations) in.
C:\src\Flutter
You can try running flutter doctor
for installation issues.
Also run flutter upgrade
to get the latest version of Flutter and Dart SDKs.
DART SDK can be found at
/flutter/bin/cache/dart-sdk
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.
Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy()
method on the array!
import numpy as np
def img_as_array(im):
"""OpenCV's native format to a numpy array view"""
w, h, n = im.width, im.height, im.channels
modes = {1: "L", 3: "RGB", 4: "RGBA"}
if n not in modes:
raise Exception('unsupported number of channels: {0}'.format(n))
out = np.asarray(im)
if n != 1:
out = out[:, :, ::-1] # BGR -> RGB conversion
return out
# : . * !
symbols<base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
gradleVersion = '2.2'
}
// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Then at the command-line run
gradle wrapper
If you're missing gradle on your system install it or the above won't work. On a Mac it is best to install via Homebrew.
brew install gradle
After you have successfully run the wrapper task and generated gradlew
, don't use your system gradle. It will save you a lot of headaches.
./gradlew assemble
com.android.tools.build:gradle:1.0.1
You should set the version to be the latest and you can check the tools page and edit the version accordingly.
The addition of gradle and the newest Android Studio have changed project layout dramatically. If you have an older project I highly recommend creating a clean one with the latest Android Studio and see what Google considers the standard project.
Android Studio has facilities for importing older projects which can also help.
I am posting this because this took me hours to find so i hope it may help someone.
I had a problem that the shadow/elevation was not showing though i created a simple activity and placed the toolbar as follows:
<androidx.appcompat.widget.Toolbar
android:id="@+id/mt_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:background="@color/colorPrimaryDark"
android:elevation="12dp"/>
It turns out that in the manifest
setting android:hardwareAccelerated="false"
was causing it! once i removed it, the shadow appeared
I don't know if that answers your question, but yes, you can use angularjs links, such as:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
There is a good example on the AngularJS website:
http://docs.angularjs.org/api/ng.directive:ngHref
UPDATE: The AngularJS documentation was a bit obscure and it didn't provide a good solution for it. Sorry!
You can find a better solution here: How to handle anchor hash linking in AngularJS
2 things to mention if focus()
not working:
This way works in both Firefox and Chrome without any setTimeOut()
.
Regarding Phil Street's post:
It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip
is installed, and if it is in Program Files (x86)
then try using this instead:
PATH=%PATH%;C:\Program Files (x86)\7-Zip
This is probably not the main reason why the create_all()
method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
I also have a separate cli command that also does the create_all:
# tasks/db.py
from lib.db import get_db
@current_app.cli.command('init-db')
def init_db():
db = get_db()
db.create_all()
I also am using a application factory.
When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).
The fix that I came around to was to make sure that the db was a single global reference:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
db = None
def get_db():
global db
if not db:
db = SQLAlchemy(current_app)
return db
I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.
Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.
function delay(t){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);
//This will call the page named delay.php and the response will be sent to a division with ID as "response"
xmlhttp.send();
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
Type
netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789
perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.
http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/
Iterate string:
for ($i = 0; $i < strlen($str); $i++){
echo $str[$i];
}
Don't use @@ERROR
, use BEGIN TRY/BEGIN CATCH
instead. See this article: Exception handling and nested transactions for a sample procedure:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
end catch
end
Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str)
call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'
plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4
note that the command above assumes that you have a file named ls.dat
with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.
I agree with pm100 (and should have explicitly said this in my earlier post).
You should never implement IDisposable in a class unless you need it. To be very specific, there are about 5 times when you would ever need/should implement IDisposable:
Your class explicitly contains (i.e. not via inheritance) any managed resources which implement IDisposable and should be cleaned up once your class is no longer used. For example, if your class contains an instance of a Stream, DbCommand, DataTable, etc.
Your class explicitly contains any managed resources which implement a Close() method - e.g. IDataReader, IDbConnection, etc. Note that some of these classes do implement IDisposable by having Dispose() as well as a Close() method.
Your class explicitly contains an unmanaged resource - e.g. a COM object, pointers (yes, you can use pointers in managed C# but they must be declared in 'unsafe' blocks, etc. In the case of unmanaged resources, you should also make sure to call System.Runtime.InteropServices.Marshal.ReleaseComObject() on the RCW. Even though the RCW is, in theory, a managed wrapper, there is still reference counting going on under the covers.
If your class subscribes to events using strong references. You need to unregister/detach yourself from the events. Always to make sure these are not null first before trying to unregister/detach them!.
Your class contains any combination of the above...
A recommended alternative to working with COM objects and having to use Marshal.ReleaseComObject() is to use the System.Runtime.InteropServices.SafeHandle class.
The BCL (Base Class Library Team) has a good blog post about it here http://blogs.msdn.com/bclteam/archive/2005/03/16/396900.aspx
One very important note to make is that if you are working with WCF and cleaning up resources, you should ALMOST ALWAYS avoid the 'using' block. There are plenty of blog posts out there and some on MSDN about why this is a bad idea. I have also posted about it here - Don't use 'using()' with a WCF proxy
How about this?
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
IF (LEFT((SELECT Attribute FROM INSERTED), 7) <> 'NoHist_')
BEGIN
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
END
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
Dynamic adding jQuery, CSS from js file. When we added onload function to body we can use jQuery to create page from js file.
init();_x000D_
_x000D_
function init()_x000D_
{_x000D_
addJQuery();_x000D_
addBodyAndOnLoadScript();_x000D_
addCSS();_x000D_
}_x000D_
_x000D_
function addJQuery()_x000D_
{_x000D_
var head = document.getElementsByTagName( 'head' )[0];_x000D_
var scriptjQuery = document.createElement( 'script' );_x000D_
scriptjQuery.type = 'text/javascript';_x000D_
scriptjQuery.id = 'jQuery'_x000D_
scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';_x000D_
var script = document.getElementsByTagName( 'script' )[0];_x000D_
head.insertBefore(scriptjQuery, script);_x000D_
}_x000D_
_x000D_
function addBodyAndOnLoadScript()_x000D_
{_x000D_
var body = document.createElement('body')_x000D_
body.onload = _x000D_
function()_x000D_
{_x000D_
onloadFunction();_x000D_
};_x000D_
}_x000D_
_x000D_
function addCSS()_x000D_
{_x000D_
var head = document.getElementsByTagName( 'head' )[0];_x000D_
var linkCss = document.createElement( 'link' );_x000D_
linkCss.rel = 'stylesheet';_x000D_
linkCss.href = 'E:/Temporary_files/temp_css.css';_x000D_
head.appendChild( linkCss );_x000D_
}_x000D_
_x000D_
function onloadFunction()_x000D_
{_x000D_
var body = $( 'body' );_x000D_
body.append('<strong>Hello world</strong>');_x000D_
}
_x000D_
html _x000D_
{_x000D_
background-color: #f5f5dc;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Temp Study HTML Page</title>_x000D_
<script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>_x000D_
</head>_x000D_
<body></body>_x000D_
</html>
_x000D_
I tried almost anything but no help...
Everytime was just this
? ~ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e unauthorized
However I've managed to connect device!
There is tutor, step by step.
$ rm -v .android/adbkey*
.android/adbkey
.android/adbkey.pub
Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys
Now create new adb keypair
? ~ adb keygen .android/adbkey
adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey'
adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'
Manually copy from PC .android/adbkey.pub
(pubkic key) to Device on path /data/misc/adb/adb_keys
Reboot device and check adb devices
:
? ~ adb devices
List of devices attached
aeef5e4e device
Permissions of /data/misc/adb/adb_keys
are (766/-rwxrw-rw-)
on my device
I know this question was already answered, but this is what I use:
using (FileStream fStream = File.OpenRead(filename)) {
return GetHash<MD5>(fStream)
}
Where GetHash:
public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
StringBuilder sb = new StringBuilder();
MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
using (T crypt = (T) create.Invoke(null, null)) {
byte[] hashBytes = crypt.ComputeHash(stream);
foreach (byte bt in hashBytes) {
sb.Append(bt.ToString("x2"));
}
}
return sb.ToString();
}
Probably not the best way, but it can be handy.
In Visual Studio 2017, I went to Project Properties -> Configuration Properties -> General, Selected All Platforms (1), then chose the dropdown (2) under Windows SDK Version and updated from 10.0.14393.0 to one that was installed (3). For me, that was 10.0.15063.0.
Additional details: This corrected the error in my case because Windows SDK Version helps VS select the correct paths. VC++ Directories -> Library Directories -> Edit -> Macros -> shows that macro $(WindowsSDK_LibraryPath_x86) has a path with the version number selected above.
If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:
npm install node-sass --save-dev
So that you can keep using /deep/ for development.
The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.
You can access web references via the advanced options in add service reference (if I recall correctly).
I'd use service reference because as I understand it, it's the newer mechanism of the two.
NullPointerException
in some cases!
Without criteria.setProjection(Projections.distinct(Projections.property("id")))
all query goes well!
This solution is bad!
Another way is use SQLQuery. In my case following code works fine:
List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();
Distinction is done in data base! In opposite to:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
where distinction is done in memory, after load entities!
This is how I come up with the IP
func ReadUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)
X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For
Using the map()
and reduce()
built-in functions
def file_to_list(file):
#stuff to parse file to a list
return list
files = [...list of files...]
L = map(file_to_list, files)
flat_L = reduce(lambda x,y:x+y, L)
Minimal "for looping" and elegant coding pattern :)
_msize(array)
in Windows or malloc_usable_size(array)
in Linux should work for the dynamic array
Both are located within malloc.h and both return a size_t
At last I fixed it simply using:
display: table;
Simple and elegant solution
Just follow these steps. It worked perfectly with npm install running multiple times or installing any other modules or even publishing project to artifactory.
In the same directory where you have package.json create a npm-shrinkwrap.json file with the following contents:
{
"dependencies": {
"graceful-fs": {
"version": "4.2.2"
}
}
}
Run npm install, and don't worry, it'll update npm-shrinkwrap.json with a bunch of content. Let's get rid of this updates by updating package.json scripts options.
"scripts": {
"preshrinkwrap": "git checkout -- npm-shrinkwrap.json",
"postshrinkwrap": "git checkout -- npm-shrinkwrap.json"
}
Now you can run npm install and your npm-shrinkwrap.json will be intact and will work forever.
a minimal bash loop you can build off of (based off ghostdog74 answer)
for dir in directory/*
do
echo ${dir}
done
to zip a whole bunch of files by directory
for dir in directory/*
do
zip -r ${dir##*/} ${dir}
done
Instead of giving margin, you should give padding:
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:divider="@android:color/green"
android:dividerHeight="4dp"
android:layout_alignParentTop="true"
android:padding="5dp" >
</ListView>
OR
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingTop="2dp"
android:divider="@android:color/green"
android:dividerHeight="4dp"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:paddingBottom="2dp"
android:paddingStart="0dp"
android:paddingEnd="0dp" >
</ListView>
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
Bytes are transparently converted to ints.
Just say
int i= rno[0];
The fix posted on above link did not work for me. This did:
function isLocalStorageNameSupported() {
var testKey = 'test', storage = window.localStorage;
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
return true;
} catch (error) {
return false;
}
}
Derived from http://m.cg/post/13095478393/detect-private-browsing-mode-in-mobile-safari-on-ios5
I find the best way to handle long dropdown boxes is to put it inside a fixed width div container and use width:auto on the select tag. Most browsers will contain the dropdown within the div, but when you click on it, it will expand to display the full option value. It does not work with IE explorer, but there is a fix (like is always needed with IE). Your code would look something like this.
HTML
<div class="dropdown_container">
<select class="my_dropdown" id="my_dropdown">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>
</div>
CSS
div.dropdown_container {
width:10px;
}
select.my_dropdown {
width:auto;
}
/*IE FIX */
select#my_dropdown {
width:100%;
}
select:focus#my_dropdown {
width:auto\9;
}
Have you tried the jtds
driver for SQLServer?
USING FLEX
display: flex;
height: 100%;
align-items: center;
justify-content: center;
gci "C:\WINDOWS\System32" -r -include .txt | select fullname
integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.
Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:
Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):
openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A
crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.
crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.
Here is a case when requesting “use-credentials” from CDN:
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
crossorigin="use-credentials"></script>
A browser can cancel the request if crossorigin incorrectly set.
Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link
Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity
How about using the replaceAll() method?
I completed similar task in my project with section with keys without values:
import configparser
# allow_no_value param says that no value keys are ok
config = configparser.ConfigParser(allow_no_value=True)
# overwrite optionxform method for overriding default behaviour (I didn't want lowercased keys)
config.optionxform = lambda optionstr: optionstr
config.read('./app.config')
features = list(config['FEATURES'].keys())
print(features)
Output:
['BIOtag', 'TextPosition', 'IsNoun', 'IsNomn']
app.config:
[FEATURES]
BIOtag
TextPosition
IsNoun
IsNomn
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
In-line them if you really need one or two lines.
I've already had the proxies set as described above and it was working until today. Then it turned out that now I need "http://" in front of my proxy address: "http://{proxyURL}:{proxyPort}". Then it finally worked.
I think this will helpful to you...
DECLARE @ConstraintName nvarchar(200)
SELECT
@ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'TABLE_NAME' AND
KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName)
It will delete foreign Key Constraint based on specific table and column.
unique_ptr
's like that.I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.
unique_ptr
constructor parameters if you have publicly-exposed unique_ptr
members.unique_ptr
s wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*>
as suggested in the Core Guidelines.
Only if the purpose of your class is to hold unique_ptr
's, and have others use those unique_ptr
's as such - only then is it reasonable for your constructor or methods to take them.
unique_ptr
s internallyUsing unique_ptr
for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
You say:
To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.
And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".
It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:
$ git clone git://github.com/SpringSource/spring-data-graph-examples.git
The git:
-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.
I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.
You could also achieve that by renaming the columns:
df.columns = ['a', 'b']
This involves a manual step but could be an option especially if you would eventually rename your data frame.
When using moment.js, use:
var tz = moment.tz.guess();
It will return an IANA time zone identifier, such as America/Los_Angeles
for the US Pacific time zone.
It is documented here.
Internally, it first tries to get the time zone from the browser using the following call:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.
If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date
object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a UTC datetime object.
If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z
:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400
or 2008-09-03T20:56:35.450686+05:00
use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500
making it more consistent/easier to parse.
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
If your system does not support the %z
strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
) then you need to manually offset the time from Z
(UTC). Note %z
may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
Here is a function that will do it without jQuery:
function getElementOffset(element)
{
var de = document.documentElement;
var box = element.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
}
You can do it with pythagoras theorem
If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.
var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt( a*a + b*b );
// c is the distance
TL;DR: Set CURLOPT_PROXYTYPE
to use CURLPROXY_SOCKS5_HOSTNAME
if you have a modern PHP, the value 7
otherwise, and/or correct the CURLOPT_PROXY
value.
As you correctly deduced, you cannot resolve .onion
domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.
Using CURLPROXY_SOCKS5
will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion
address unless it, too, is specifically forwarding such queries to Tor.
Instead of CURLPROXY_SOCKS5
, you must use CURLPROXY_SOCKS5_HOSTNAME
. Alternatively, you can also use CURLPROXY_SOCKS4A
, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion
domain.
There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:
Here is the correct code in full, with comments to indicate the changes.
<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($curl_error);
You can also omit setting CURLOPT_PROXYTYPE
entirely by changing the CURLOPT_PROXY
value to include the socks5h://
prefix:
// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');
I used quite @Eyuel method:
node cli.js install npm -gf
Now you should have node + npm working, use theses commands to check: node --version
and npm --version
Update 27/07/2017 : I noticed that the latest version of node 8.2.1 with the latest version of npm are quite different from the one I was using at the time of this answer. The install with theses versions won't work. It is working with node 6.11.1 and npm 5.2.3. Also if you are running with a proxy don't forget this to connect on internet :
You have to specify that test1 is global:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
I got the same problem after creating a new TestCase: Eclipse -> New -> JUnit Test Case. It creates a class without access level modifier. I could solve the problem by just putting a public before the class keyword.
You need to drop the table and then recreate it and then load it again
After some research I finally got a VBA code to show the filter value in another cell:
Dim bRepresentAsRange As Boolean, bRangeBroken As Boolean
Dim sSelection As String
Dim tbl As Variant
bRepresentAsRange = False
bRangeBroker = False
With Worksheets("Forecast").PivotTables("ForecastbyDivision")
ReDim tbl(.PageFields("Probability").PivotItems.Count)
For Each fld In .PivotFields("Probability").PivotItems
If fld.Visible Then
tbl(n) = fld.Name
sSelection = sSelection & fld.Name & ","
n = n + 1
bRepresentAsRange = True
Else
If bRepresentAsRange Then
bRepresentAsRange = False
bRangeBroken = True
End If
End If
Next fld
If Not bRangeBroken Then
Worksheets("Forecast").Range("ProbSelection") = " >= " & tbl(0)
Else
Worksheets("Forecast").Range("ProbSelection") = Left(sSelection, Len(sSelection) - 1)
End If
End With
I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:
public static void showVirtualKeyboard(Context context, final View view) {
if (context != null) {
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
if(view.isShown()) {
imm.showSoftInput(view, 0);
view.requestFocus();
} else {
view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
view.post(new Runnable() {
@Override
public void run() {
view.requestFocus();
imm.showSoftInput(view, 0);
}
});
view.removeOnAttachStateChangeListener(this);
}
@Override
public void onViewDetachedFromWindow(View v) {
view.removeOnAttachStateChangeListener(this);
}
});
}
}
}
Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";
int main()
{
size_t wcsChars = wcslen( wcsString);
size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Wide chars in wcsString: %u\n", wcsChars);
printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
}
And the output:
Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18
I have created a small lib that does this a year ago:
https://github.com/shawnmclean/Idle.js
Description:
Tiny javascript library to report activity of user in the browser (away, idle, not looking at webpage, in a different tab, etc). that is independent of any other javascript libraries such as jquery.
Visual Studio users can get it from NuGet by: PM> Install-Package Idle.js
$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];
but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.
I guess you're missing the ENCLOSED BY clause
LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';
And specify the csv file full path
Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.
OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.
There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.
@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.
That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.
The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.
Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:
It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)
It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)
The result using initialized data:
The result using uninitialized data (this is what Mysticial tested):
And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:
Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.
You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.
I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.
The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.
and note that:
please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
Don't do relative import.
From PEP8:
Relative imports for intra-package imports are highly discouraged.
Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.
Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.
Ok so I just found a really decent work around to this issue. CMDKEY works on windows 7+ and allows you to enter details into the windows cred manager from the cmd prompt, and if you use the /pass switch it provides its own password entry without exposing the password. It does not present ***** as you type but the password is hidden.
The script below requests the username as normal and creates a var called "%username%" it then checks to see if the cred manager already has an entry for the target server. If it does it just maps the drive to the usename and does not request a password. If there is no entry it then uses the CMDKEY to prompt for password and stores it in cred manager.
set /p username="Enter School Username: "
CMDKEY /list:SERVERNAME | FIND "NONE" > nul 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO MAPDRIVES
CMDKEY /ADD:SERVERNAME /username:%username% /pass
:MAPDRIVES
NET USE Y: \\SERVERNAME\SHARE\%username%
I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372
I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NANO 1000000000L
// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
int ret;
struct tm t;
tzset();
if (localtime_r(&(ts->tv_sec), &t) == NULL)
return 1;
ret = strftime(buf, len, "%F %T", &t);
if (ret == 0)
return 2;
len -= ret - 1;
ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
if (ret >= len)
return 3;
return 0;
}
int main(int argc, char **argv) {
clockid_t clk_id = CLOCK_REALTIME;
const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
char timestr[TIME_FMT];
struct timespec ts, res;
clock_getres(clk_id, &res);
clock_gettime(clk_id, &ts);
if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
printf("timespec2str failed!\n");
return EXIT_FAILURE;
} else {
unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
return EXIT_SUCCESS;
}
}
output:
gcc mwe.c -lrt
$ ./a.out
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501
Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table. column take unique values (not same) when we applied primary & unique key.
<title>Index.html</title>
<script>
var varDeclaration = true;
noVarDeclaration = true;
window.hungOnWindow = true;
document.hungOnDocument = true;
</script>
<script src="external.js"></script>
/* external.js */
console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8
console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!) *I personally find this more clugy than hanging off window obj
Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'
Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.
Hash can create a new hash from an existing hash:
irb(main):009:0> h1 = {1 => 2}
=> {1=>2}
irb(main):010:0> h2 = Hash[h1]
=> {1=>2}
irb(main):011:0> h1.object_id
=> 2150233660
irb(main):012:0> h2.object_id
=> 2150205060
Here's my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define pii pair<int, int>
#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032
unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];
#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
unsigned i, j, k;
for (i = 3; i<LMT; i += 2)
if (!chkC(base, i))
for (j = i*i, k = i << 1; j<MAX; j += k)
setC(base, j);
primes[0] = 2;
for (i = 3, j = 1; i<MAX; i += 2)
if (!chkC(base, i))
primes[j++] = i;
}
//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
int expo = 0;
for (int i = 0; primes[i] <= sqrt(num); i++)
{
expo = 0;
int prime = primes[i];
while (num % prime == 0){
expo++;
num = num / prime;
}
if (expo>0)
factors.push_back(make_pair(prime, expo));
}
if ( num >= 2)
factors.push_back(make_pair(num, 1));
}
vector <int> divisors;
void setDivisors(int n, int i) {
int j, x, k;
for (j = i; j<factors.size(); j++) {
x = factors[j].first * n;
for (k = 0; k<factors[j].second; k++) {
divisors.push_back(x);
setDivisors(x, j + 1);
x *= factors[j].first;
}
}
}
int main() {
sieve();
int n, x, i;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
primeFactors(x);
setDivisors(1, 0);
divisors.push_back(1);
sort(divisors.begin(), divisors.end());
cout << divisors.size() << "\n";
for (int j = 0; j < divisors.size(); j++) {
cout << divisors[j] << " ";
}
cout << "\n";
divisors.clear();
factors.clear();
}
}
The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).
The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:
factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1
as 12 = 2^2 * 3^1
The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].
It can calculate divisors of any number which fits in int. Also it is quite fast.
Using WifiManager
you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
I'm new to flutter. I found that one can also achieve it this way.
tabs: [
for (var title in movieTitles) Tab(text: title)
]
Note: It requires dart sdk version to be >= 2.3.0, see here
If you use CDATA, you could embed the line breaks directly into the XML I think. Example:
<song>
<title>Song Title</title>
<lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>
decimal d = 3.00 is still 3. I guess you want to show it some where on screen or print it on log file as 3.00. You can do following
string str = d.ToString("F2");
or if you are using database to store the decimal then you can set pricision value in database.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"
clang++ 3.5 even warns on it:
/tmp/a.C:3:7: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to
always evaluate to false [-Wtautological-undefined-compare]
if( & nullReference == 0 ) // null reference
^~~~~~~~~~~~~ ~
1 warning generated.
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.
You can do it by subfolders (example /css/v1/style.css)
or by filename (example: css/style_v1.css)
or even by setting different folders for your website, example:
www.mywebsite.com/site1
www.mywebsite.com/site2
www.mywebsite.com/site3
And use a .htaccess or even change httpd.conf to redirect to your current application.
If's about one image or page:
<?$time = date("H:i:s");?>
<img src="myfile.jpg?time=<?$time;?>">
You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.
After installing OpenSSL, you need to restart your computer and use Run As Administrator
. Then its works.
What about this.
var p = document.getElementById("p")_x000D_
p.innerText = p.innerText+" And this is addon."
_x000D_
<p id ="p">This is some text</p>
_x000D_
Go to c:\Documents and Settings[username]\Application Data\subversion\auth\svn.simple
and delete the hexadecimal file. Normally each file is associated with one repository
I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.
Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.
in visual studio 2012 you can simply select the browser you want to debug with from the dropdown box placed just over the code editor
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
I would say using tryParse, it'll return 'false' if the uint is to big for an int.
Don't forget that a uint can go much bigger than a int, as long as you going > 0
The Natural Language Toolkit (nltk.org) has what you need. This group posting indicates this does it:
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
fp = open("test.txt")
data = fp.read()
print '\n-----\n'.join(tokenizer.tokenize(data))
(I haven't tried it!)
The --force
option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.
If you tell rpm
to install all RPMs from some directory, then it does exactly this. rpm
will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.
You can remove the old RPM and rpm
will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.
If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm
to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i
(zypper in
can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.
I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles
. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify
command. It will complain for the new package if the old one has overwritten some files.
Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
for my case Footer method was having malformed html code (missing td) causing error on osx.
public function Footer() {
$this->SetY(-40);
$html = <<<EOD
<table>
<tr>
Test Data
</tr>
</table>
EOD;
$this->writeHTML($html);
}
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
var token = string.Empty;
if (Request.Headers.TryGetValue("MyKey", out headerValues))
{
token = headerValues.FirstOrDefault();
}
If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.
NOTE: ngx-bootstrap is used.
import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';
@Directive({
selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
@Input() swipeThreshold = 50;
private start: number;
private stillMoving: boolean;
private moveListener: Function;
constructor(
@Host() @Self() @Optional() private carousel: CarouselComponent,
private renderer: Renderer2,
private element: ElementRef
) {
}
ngOnInit(): void {
if ('ontouchstart' in document.documentElement) {
this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
}
}
private onTouchStart(e: TouchEvent): void {
if (e.touches.length === 1) {
this.start = e.touches[0].pageX;
this.stillMoving = true;
this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
}
}
private onTouchMove(e: TouchEvent): void {
if (this.stillMoving) {
const x = e.touches[0].pageX;
const difference = this.start - x;
if (Math.abs(difference) >= this.swipeThreshold) {
this.cancelTouch();
if (difference > 0) {
if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
this.carousel.activeSlide = this.carousel.activeSlide + 1;
}
} else {
if (this.carousel.activeSlide > 0) {
this.carousel.activeSlide = this.carousel.activeSlide - 1;
}
}
}
}
}
private onTouchEnd(e: TouchEvent): void {
this.cancelTouch();
}
private cancelTouch() {
if (this.moveListener) {
this.moveListener();
this.moveListener = undefined;
}
this.start = null;
this.stillMoving = false;
}
}
in html:
<carousel appCarouselSwipe>
...
</carousel>
find . -type f -empty -exec rm -f {} \;
You can reference Microsoft.VisualBasic.dll
.
Then using the code below.
Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");
Alternatively, by adding a using
directive allowing for a shorter syntax in your code (which I'd personally prefer).
using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");
Or you can do what Pranay Rana suggests, that's what I would've done too...
I've just set up a quick benchmarking exercise:
Function time to run 1 million iterations
--------------------------------------------
(int) "123": 0.55029
intval("123"): 1.0115 (183%)
(int) "0": 0.42461
intval("0"): 0.95683 (225%)
(int) int: 0.1502
intval(int): 0.65716 (438%)
(int) array("a", "b"): 0.91264
intval(array("a", "b")): 1.47681 (162%)
(int) "hello": 0.42208
intval("hello"): 0.93678 (222%)
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know why though.
Update: I've run the tests again, this time with coercion (0 + $var)
| INPUT ($x) | (int) $x |intval($x) | 0 + $x |
|-----------------|------------|-----------|-----------|
| "123" | 0.51541 | 0.96924 | 0.33828 |
| "0" | 0.42723 | 0.97418 | 0.31353 |
| 123 | 0.15011 | 0.61690 | 0.15452 |
| array("a", "b") | 0.8893 | 1.45109 | err! |
| "hello" | 0.42618 | 0.88803 | 0.1691 |
|-----------------|------------|-----------|-----------|
Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
$x = "11";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11)
$x = "0x11";
(int) $x; // int(0)
intval($x); // int(0)
$x + 0; // int(17) !
$x = "011";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11) (not 9)
Tested using PHP 5.3.1
Mine was different again. I was setting the user-agent like so:
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.
#
indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.
So, #include
is a preprocessor directive that tells the preprocessor to include header files in the program.
< >
indicate the start and end of the file name to be included.
iostream
is a header file that contains functions for input/output operations (cin
and cout
).
Now to sum it up C++ to English translation of the command, #include <iostream>
is:
Dear preprocessor, please include all the contents of the header file iostream
at the very beginning of this program before compiler starts the actual compilation of the code.
The number of column parameters in your insert query is 9, but you've only provided 8 values.
INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
The query should omit the "id" parameter, because it is auto-generated (or should be anyway):
INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
You might find ODA useful. It's a web-based disassembler that supports tons of architectures.
Creating a tableview using tableViewController .
import UIKit
class TableViewController: UITableViewController
{
let tableViewModel = TableViewModel()
var product: [String] = []
var price: [String] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
let priceProductDetails = tableViewModel.dataProvider()
for (key, value) in priceProductDetails
{
product.append(key)
price.append(value)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return product.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
cell.textLabel?.text = product[indexPath.row]
cell.detailTextLabel?.text = price[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.
Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.
The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse
method for more info. But then, again, note that an IP might have multiple names associated with it.
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
This question is pretty old, but I just ran into a similar problem and my particular solution wasn't listed here:
Make sure you don't have a folder in your PATH that doesn't exist.
In my case, I had a bunch of default folders (Windows, Powershell, Sql Server, etc) and then a custom C:\bin
that I typically use, and then various other tweaks like c:\python17
, etc. It turns out that the cmd processor was finding that c:\bin
didn't exist and then stopped processing the rest of the variable.
Also, I don't know that I ever would have noticed this without PATH manager. It nicely highlighted the fact that that item was invalid.
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
Use the following query in sql tab:
SHOW CREATE TABLE your_table_name
Press GO button
After show table, above the table ( +options ) Hyperlink.
Press +options Hyperlink then appear some options select (Full texts) press GO button.
Show sql quaery.
I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:
$('a[href*=\\#]').on('click',function(e) {
var target = this.hash;
var $target = $(target);
console.log(targetname);
var targetname = target.slice(1, target.length);
if(document.getElementById(targetname) != null) {
e.preventDefault();
}
$('html, body').stop().animate({
'scrollTop': $target.offset().top-120 //or the height of your fixed navigation
}, 900, 'swing', function () {
window.location.hash = target;
});
});
I'm sure you'll get a ton of "don't do this" answers, and I must say, there is good reason. This isn't an ideal solution....
That being said, I've gone down this road (and similar ones) before, mostly because the job specified it as a hard requirement and I couldn't talk around it.
Here are a few things to consider with this:
How easy is it to link to Access from Excel using ADO / DAO? Is it quite limited in terms of functionality or can I get creative?
It's fairly straitforward. You're more limited than you would be doing things using other tools, since VBA and Excel forms is a bit more limiting than most full programming languages, but there isn't anything that will be a show stopper. It works - sometimes its a bit ugly, but it does work. In my last company, I often had to do this - and occasionally was pulling data from Access and Oracle via VBA in Excel.
Do I pay a performance penalty (vs.using forms in Access as the UI)?
My experience is that there is definitely a perf. penalty in doing this. I never cared (in my use case, things were small enough that it was reasonable), but going Excel<->Access is a lot slower than just working in Access directly. Part of it depends on what you want to do....
In my case, the thing that seemed to be the absolute slowest (and most painful) was trying to fill in Excel spreadsheets based on Access data. This wasn't fun, and was often very slow. If you have to go down this road, make sure to do everything with Excel hidden/invisible, or the redrawing will absolutely kill you.
Assuming that the database will always be updated using ADO / DAO commands from within Excel VBA, does that mean I can have multiple Excel users using that one single Access database and not run into any concurrency issues etc.?
You're pretty much using Excel as a client - the same way you would use a WinForms application or any other tool. The ADO/DAO clients for Access are pretty good, so you probably won't run into any concurrency issues.
That being said, Access does NOT scale well. This works great if you have 2 or 3 (or even 10) users. If you are going to have 100, you'll probably run into problems. Also, I tended to find that Access needed regular maintenance in order to not have corruption issues. Regular backups of the Access DB are a must. Compacting the access database on a regular basis will help prevent database corruption, in my experience.
Any other things I should be aware of?
You're doing this the hard way. Using Excel to hit Access is going to be a lot more work than just using Access directly.
I'd recommend looking into the Access VBA API - most of it is the same as Excel, so you'll have a small learning curve. The parts that are different just make this easier. You'll also have all of the advantages of Access reporting and Forms, which are much more data-oriented than the ones in Excel. The reporting can be great for things like this, and having the Macros and Reports will make life easier in the long run. If the user's going to be using forms to manage everything, doing the forms in Access will be very, very similar to doing them in Excel, and will look nearly identical, but will make everything faster and smoother.
All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico
unless you've specified a shortcut icon via <link>
. So if you don't explicitly specify one, it's best to always have a favicon.ico
file, to avoid a 404. Yahoo! suggests you make it small and cacheable.
And you don't have to go for a PNG just for the alpha transparency either. ICO files support alpha transparency just fine (i.e. 32-bit color), though hardly any tools allow you to create them. I regularly use Dynamic Drive's FavIcon Generator to create favicon.ico
files with alpha transparency. It's the only online tool I know of that can do it.
There's also a free Photoshop plug-in that can create them.
Scikit-learn is a machine learning library for Python which can do this job for you. Just import sklearn.linear_model module into your script.
Find the code template for Multiple Linear Regression using sklearn in Python:
import numpy as np
import matplotlib.pyplot as plt #to plot visualizations
import pandas as pd
# Importing the dataset
df = pd.read_csv(<Your-dataset-path>)
# Assigning feature and target variables
X = df.iloc[:,:-1]
y = df.iloc[:,-1]
# Use label encoders, if you have any categorical variable
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
X['<column-name>'] = labelencoder.fit_transform(X['<column-name>'])
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder(categorical_features = ['<index-value>'])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the dummy variable trap
X = X[:,1:] # Usually done by the algorithm itself
#Spliting the data into test and train set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, random_state = 0, test_size = 0.2)
# Fitting the model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the test set results
y_pred = regressor.predict(X_test)
That's it. You can use this code as a template for implementing Multiple Linear Regression in any dataset. For a better understanding with an example, Visit: Linear Regression with an example
app.use(bodyParser.urlencoded({extended: true}));
I have the same problem but this work for me. You can try this extended part.
Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.
To complement Michael's answer, and according to this answer, a safe way to deal with the problem is to use the following arguments:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -XX:+UseConcMarkSweepGC
When you write your script on windows environment and you want to run it on unix environnement you need to be careful about the encodage :
dos2unix $filePath
To still be able to scroll this worked for me
if (e.changedTouches.length > 1) e.preventDefault();
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open.
Therefore, to the answer of @hkBattousai I will add the exit
command:
"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"
There are three ways to fetch multiple rows returned by PDO statement.
The simplest one is just to iterate over PDOStatement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
another one is to fetch rows using fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
or, if you need to preprocess some data first, use the while loop and collect the data into array manually
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
and then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:
/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload
If you need to do this often, you may want to use an alias. I use the following:
alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'
The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.
You can use "restart" instead of "reload" if you really want to restart the server.
This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.
With this code you will be also able to get MacAddress in Android 6.0 also
public static String getMacAddr() {
try {
List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif: all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b: macBytes) {
//res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {}
return "02:00:00:00:00:00";
}
EDIT 1. This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.
For Java code, Create a POJO class for your object instead of a JSONObject. and use JSONEncapsulator for your POJO class. that way order of elements depends on the order of getter setters in your POJO class. for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.
Use $http Interceptor
By using an $http interceptor you can send headers to Back-end or the other way around and do your checks that way.
Great article on $http interceptors
Example:
$httpProvider.interceptors.push(function ($q) {
return {
'response': function (response) {
// TODO Create check for user authentication. With every request send "headers" or do some other check
return response;
},
'responseError': function (reject) {
// Forbidden
if(reject.status == 403) {
console.log('This page is forbidden.');
window.location = '/';
// Unauthorized
} else if(reject.status == 401) {
console.log("You're not authorized to view this page.");
window.location = '/';
}
return $q.reject(reject);
}
};
});
Put this in your .config or .run function.
It's by value according to the PHP Documentation.
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
You can use lookups in Ansible in order to get the contents of a file, e.g.
user_data: "{{ lookup('file', user_data_file) }}"
Caveat: This lookup will work with local files, not remote files.
Here's a complete example from the docs:
- hosts: all
vars:
contents: "{{ lookup('file', '/etc/foo.txt') }}"
tasks:
- debug: msg="the value of foo.txt is {{ contents }}"
The event has a property called event.path of the element which is a "static ordered list of all its ancestors in tree order". To check if an event originated from a specific DOM element or one of its children, just check the path for that specific DOM element. It can also be used to check multiple elements by logically OR
ing the element check in the some
function.
$("body").click(function() {_x000D_
target = document.getElementById("main");_x000D_
flag = event.path.some(function(el, i, arr) {_x000D_
return (el == target)_x000D_
})_x000D_
if (flag) {_x000D_
console.log("Inside")_x000D_
} else {_x000D_
console.log("Outside")_x000D_
}_x000D_
});
_x000D_
#main {_x000D_
display: inline-block;_x000D_
background:yellow;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">_x000D_
<ul>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div id="main2">_x000D_
Outside Main_x000D_
</div>
_x000D_
So for your case It should be
$("body").click(function() {
target = $("#menuscontainer")[0];
flag = event.path.some(function(el, i, arr) {
return (el == target)
});
if (!flag) {
// Hide the menus
}
});
You are correct that your cTag class must implement IComparable<T>
interface. Then you can just call Sort()
on your list.
To implement IComparable<T>
interface, you must implement CompareTo(T other)
method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public string date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public DateTime date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String)
method.
If you are using NGINX over linux and want a pure bash/html, you can add a mask on your template and pipe the requests to use the sed command to do a replace by using a regullar expression.
Anyway I would rather have a bash script that takes from a templates folder and generate the final HTML.
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
Updated 2020
Here's an updated answer for the latest Bootstrap 4.0.0. This version has classes that will help you create a sticky or fixed sidebar without the extra CSS....
Use sticky-top
:
<div class="container">
<div class="row py-3">
<div class="col-3 order-2" id="sticky-sidebar">
<div class="sticky-top">
...
</div>
</div>
<div class="col" id="main">
<h1>Main Area</h1>
...
</div>
</div>
</div>
Demo: https://codeply.com/go/O9GMYBer4l
or, use position-fixed
:
<div class="container-fluid">
<div class="row">
<div class="col-3 px-1 bg-dark position-fixed" id="sticky-sidebar">
...
</div>
<div class="col offset-3" id="main">
<h1>Main Area</h1>
...
</div>
</div>
</div>
Demo: https://codeply.com/p/0Co95QlZsH
Also see:
Fixed and scrollable column in Bootstrap 4 flexbox
Bootstrap col fixed position
How to use CSS position sticky to keep a sidebar visible with Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Using a table would be one (and easy) option.
Other options are all about setting fixed width on the and making it text-aligned to the right:
label {
width: 200px;
display: inline-block;
text-align: right;
}
or, as was pointed out, make them all float instead of inline.
I found a great code for you:
HTML
<form class="form-wrapper cf">
<input type="text" placeholder="Search here..." required>
<button type="submit">Search</button>
</form>
CSS
/*Clearing Floats*/
.cf:before, .cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
.cf {
zoom:1;
}
/* Form wrapper styling */
.form-wrapper {
width: 450px;
padding: 15px;
margin: 150px auto 50px auto;
background: #444;
background: rgba(0,0,0,.2);
border-radius: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}
/* Form text input */
.form-wrapper input {
width: 330px;
height: 20px;
padding: 10px 5px;
float: left;
font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
border: 0;
background: #eee;
border-radius: 3px 0 0 3px;
}
.form-wrapper input:focus {
outline: 0;
background: #fff;
box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}
.form-wrapper input::-webkit-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-moz-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-ms-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
/* Form submit button */
.form-wrapper button {
overflow: visible;
position: relative;
float: right;
border: 0;
padding: 0;
cursor: pointer;
height: 40px;
width: 110px;
font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
color: #fff;
text-transform: uppercase;
background: #d83c3c;
border-radius: 0 3px 3px 0;
text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}
.form-wrapper button:hover {
background: #e54040;
}
.form-wrapper button:active,
.form-wrapper button:focus {
background: #c42f2f;
outline: 0;
}
.form-wrapper button:before { /* left arrow */
content: '';
position: absolute;
border-width: 8px 8px 8px 0;
border-style: solid solid solid none;
border-color: transparent #d83c3c transparent;
top: 12px;
left: -6px;
}
.form-wrapper button:hover:before {
border-right-color: #e54040;
}
.form-wrapper button:focus:before,
.form-wrapper button:active:before {
border-right-color: #c42f2f;
}
.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
border: 0;
padding: 0;
}
I'm not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It's really quite simple:
The function takes two arguments, a div containing only the words "show more" [or whatever] and a div containing the originally hidden text and the words "show less." The function displays the one div and hides the other.
NOTE: If more than one show/hide on page, assign different ids to divs Colors can be changed
<p>Here is text that is originally displayed</p>
<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">
<p>Put expanded text here</p>
<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>
<p>more text</p>
Here is the Script:
<script>
function showFunction(diva, divb) {
var x = document.getElementById(diva);
var y = document.getElementById(divb);
x.style.display = 'block';
y.style.display = 'none';
}
</script>
I'd recommend serialization,
public class Person
{
public string FirstName;
public string MI;
public string LastName;
}
static void Serialize()
{
clsPerson p = new Person();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(System.Console.Out, p);
System.Console.WriteLine();
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
}
You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:
using System;
using System.Xml;
public class GenerateXml {
private static void Main() {
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "01";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
// Create and add another product node.
productNode = doc.CreateElement("product");
productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "02";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("C#"));
productNode.AppendChild(nameNode);
priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
doc.Save(Console.Out);
}
}
And if it needs to be fast, use XmlWriter:
public static void WriteXML()
{
// Create an XmlWriterSettings object with the correct options.
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " "; // "\t";
settings.OmitXmlDeclaration = false;
settings.Encoding = System.Text.Encoding.UTF8;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("books");
for (int i = 0; i < 100; ++i)
{
writer.WriteStartElement("book");
writer.WriteElementString("item", "Book "+ (i+1).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
writer.Close();
} // End Using writer
}
And btw, the fastest way to read XML is XmlReader:
public static void ReadXML()
{
using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
{
while (xmlReader.Read())
{
if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
{
if (xmlReader.HasAttributes)
System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
}
} // Whend
} // End Using xmlReader
System.Console.ReadKey();
}
And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/
I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load")
instead of .load()
.
This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:
.load();
to
.trigger("load");
I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
mode con:cols=[whatever you want] lines=[whatever you want].
The unit is the number of characters that fit in the command prompt, eg.
mode con:cols=80 lines=100
will make the command prompt 80 ASCII chars of width and 100 of height
You would find the array keys with "${!foo[@]}"
(reference), so:
for i in "${!foo[@]}"; do
printf "%s\t%s\n" "$i" "${foo[$i]}"
done
Which means that indices will be in $i
while the elements themselves have to be accessed via ${foo[$i]}
if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
//do stuff if yess
}
else
{
//do stuff if No
}
QUESTION:
What does =>
mean?
ANSWER:
=>
Is the symbol we humans decided to use to separate "Key" => "Value"
pairs in Associative Arrays.
ELABORATING:
To understand this, we have to know what Associative Arrays are. The first thing that comes up when a conventional programmer thinks of an array (in PHP) would be something similar to:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where as, if we wanted to call the array in some later part of the code, we could do:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
So far so good. However, as humans, we might find it hard to remember that index [0]
of the array is the value of the year 2016, index [1]
of the array is a greetings, and index [2]
of the array is a simple integer value. The alternative we would then have is to use what is called an Associative Array. An Associative array has a few differences from a Sequential Array
(which is what the previous cases were since they increment the index used in a predetermined sequence, by incrementing by 1 for each following value).
Differences (between a sequential and associative array):
Durring the declaration of an Associative Array, you don't only include the value
of what you want to put in the array, but you also put the index value (called the key
) which you want to use when calling the array in later parts of the code. The following syntax is used during it's declaration: "key" => "value"
.
When using the Associative Array, the key
value would then be placed inside the index of the array to retrieve the desired value
.
For instance:
$myArray1 = array(
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33);//option 1
$myArray2 = [
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33];//option 2
$myArray3 = [];//option 3
$myArray3["Year"] = 2016;
$myArray3["Greetings"] = "hello";
$myArray3["Integer_value"] = 33;
And now, to receive the same output as before, the key
value would be used in the arrays index:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
FINAL POINT:
So from the above example, it is pretty easy to see that the =>
symbol is used to express the relationship of an Associative Array between each of the key
and value
pairs in an array DURING the initiation of the values within the array.
See the isDigit(char ch)
method:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
and pass it to the first character of the String using the String.charAt()
method.
Character.isDigit(myString.charAt(0));
I let the CI server pipe the following into a file named CHANGELOG
for a each new release with the date set in the release-filename:
>git log --graph --all --date=relative --pretty=format:"%x09 %ad %d %s (%aN)"
A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.
>>> hash("Look at me!!")
6941904779894686356
These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set
and dict
. In a list
, if you want to check if a value is in the list, with if x in values:
, Python needs to go through the whole list and compare x
with each value in the list values
. This can take a long time for a long list
. In a set
, Python keeps track of each hash, and when you type if x in values:
, Python will get the hash-value for x
, look that up in an internal structure and then only compare x
with the values that have the same hash as x
.
The same methodology is used for dictionary lookup. This makes lookup in set
and dict
very fast, while lookup in list
is slow. It also means you can have non-hashable objects in a list
, but not in a set
or as keys in a dict
. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.
Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>>
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299
This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.
Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.
I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.
If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.
I would recommend (as far as possible, and depending on the exact size of the figures):
In my experience, this is a big eater-up of non-available time (:-)
In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.