So this is old but... just in case someone finds this in a search.
Just use "#/"
instead of "#"
and the page won't jump.
if (a % 2 == 0) {
} else {
}
Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).
Have a look at this
for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.
(<([^>]+)>| )
You can test it here: https://regex101.com/r/kB0rQ4/1
Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text
Príliš žlutoucký kun
úpel dábelské ódy
and the file uses windows-1250 format. If you use FileReader you will get this result:
P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy
So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.
Example:
String encoding = "Cp1250";
File file = new File("foo.txt");
if (file.exists()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("file doesn't exist");
}
In case you want to read the file character after character do not use BufferedReader.
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
int data = isr.read();
while (data != -1) {
System.out.print((char) data);
data = isr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
There are only two options:
Find out by reading all rows (and then you might as well store them)
run a specialized SELECT COUNT(*) query beforehand.
Going twice through the DataReader loop is really expensive, you would have to re-execute the query.
And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.
Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<>
or DataTable
) and then copy the data to any format you want. The in-memory operation will always be much more efficient.
My rule is simple. If you are using C++ prefer C++ libraries and not C :)
Imread uses PIL library, if the library is installed use : "from scipy.ndimage import imread"
Source: http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html
%x
is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.
%02x
means if your provided value is less than two digits then 0
will be prepended.
You provided value 16843009
and it has been converted to 1010101
which a hex value.
I had a similar error. The answers here helped me figure out what to do.
index.html
<!--The div element for the map -->
<div id="map"></div>
<!--The link to external javascript file that has initMap() function-->
<script src="main.js">
<!--Google api, this calls initMap() function-->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap">
</script>
main.js // This gives error
// The initMap function has not been executed
const initMap = () => {
const mapDisplayElement = document.getElementById('map');
// The address is Uluru
const address = {lat: -25.344, lng: 131.036};
// The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
};
The answers here helped me figure out a solution. I used an immediately invoked the function (IIFE ) to work around it.
The error is as at the time of calling the google maps api the initMap() function has not executed.
main.js // This works
const mapDisplayElement = document.getElementById('map');
// The address is Uluru
// Run the initMap() function imidiately,
(initMap = () => {
const address = {lat: -25.344, lng: 131.036};
// The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
})();
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
from http://api.jquery.com/closest/
The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:
.closest()
- Begins with the current element
- Travels up the DOM tree until it finds a match for the supplied selector
- The returned jQuery object contains zero or one element
.parents()
- Begins with the parent element
- Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
- The returned jQuery object contains zero, one, or multiple elements
.parent()
- Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.
Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.
Here are related threads:
If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,
git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin
Please remove
.git\index.lock
File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.
git reset --hard HEAD
git reset --hard origin
Hope that helps!!!
I got the same issue when i export FMDB module in xcode 4.6. Later i found a fmdb.m in my my file list which was causing this issue. After i removed from the project it works fine
Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"
There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:
Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0
Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.
First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).
Neither is supported by Windows command-line ftp.exe
. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.
Using WinSCP, your batch file would look like (for SFTP):
echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat
And the batch file:
winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%
Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP%
syntax), the batch file simplifies to:
winscp.com /log=ftpcmd.log /command ^
"open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
"put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
"exit"
For the purpose of -hostkey
switch, see verifying the host key in script.
Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:
All you need to tweak is the source file name (use the %TIMESTAMP%
syntax as shown previously) and the path to the log file.
For FTPS, replace the sftp://
in the open
command with ftpes://
(explicit TLS/SSL) or ftps://
(implicit TLS/SSL). Remove the -hostkey
switch.
winscp.com /log=ftpcmd.log /command ^
"open ftps://ftp_user:[email protected] -explicit" ^
"put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
"exit"
You may need to add the -certificate
switch, if your server's certificate is not issued by a trusted authority.
Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.
See a complete conversion guide from ftp.exe
to WinSCP.
You should also read the Guide to automating file transfers to FTP server or SFTP server.
Note to using %TIMESTAMP#yyyymmdd%
instead of %date%
: A format of %date%
variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date%
resolves to ct 06. 11. 2014
, what might be problematic when used as a part of a file name.
For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd%
resolves to 20170515
on any locale.
(I'm the author of WinSCP)
i use as following for over come this matter
edittext_style.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
android:color="#c8c8c8"/>
<corners android:radius="0dp" />
And applied as bellow
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editTextName"
android:background="@drawable/edit_text_style"/>
try like this..
In jQuery 1.8, this can be done as follows:
(function($){
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
})(jQuery);
Git will not store the password when you use URLs like that. Instead, it will just store the username, so it only needs to prompt you for the password the next time. As explained in the manual, to store the password, you should use an external credential helper. For Windows, you can use the Windows Credential Store for Git. This helper is also included by default in GitHub for Windows.
When using it, your password will automatically be remembered, so you only need to enter it once. So when you clone, you will be asked for your password, and then every further communication with the remote will not prompt you for your password again. Instead, the credential helper will provide Git with the authentication.
This of course only works for authentication via https; for ssh access ([email protected]/repository.git
) you use SSH keys and those you can remember using ssh-agent
(or PuTTY’s pageant if you’re using plink).
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
First, you're using the modifiers under an incorrect assumption.
Pattern.MULTILINE
or (?m)
tells Java to accept the anchors ^
and $
to match at the start and end of each line (otherwise they only match at the start/end of the entire string).
Pattern.DOTALL
or (?s)
tells Java to allow the dot to match newline characters, too.
Second, in your case, the regex fails because you're using the matches()
method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)*
have matched.
So if you're simply looking for a string that starts with User Comments:
, use the regex
^\s*User Comments:\s*(.*)
with the Pattern.DOTALL
option:
Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
ResultString
will then contain the text after User Comments:
You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...)
, but other JS APIs are intentionally made inaccessible.
It's also still possible to get the URL depending on the context. See other answers for more details.
Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)
If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!
class Foo{
public static void main(String[] args){
Bar myInstance = new Bar();
myInstance.do(); // works!
Bar.do(); // doesn't work!
Bar.doSomethingStatic(); // works!
}
}
class Bar{
public do() {
// do something
}
public static doSomethingStatic(){
}
}
Also remember, classes in Java should start with an uppercase letter.
I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:
ls /usr/local/Cellar/boost*
This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.
Sub Trim_Cells_Array_Method()
Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long
lRows = Selection.Rows.count
lCols = Selection.Columns.count
ReDim arrData(1 To lRows, 1 To lCols)
ReDim arrReturnData(1 To lRows, 1 To lCols)
Set rng = Selection
arrData = rng.value
For j = 1 To lCols
For i = 1 To lRows
arrReturnData(i, j) = Trim(arrData(i, j))
Next i
Next j
rng.value = arrReturnData
Set rng = Nothing
End Sub
Checkout your laravel/framework version on your composer.json file,
If it's either "^6.0" or higher than "^5.9",
you have to use php artisan ui:auth
instead of php artisan make:auth
.
Before using that you have to install new dependencies by calling
composer require laravel/ui --dev
in the current directory.
Try phoneNumber.setVisibility(View.GONE);
int size=5;
int ar[size ]={O};
/* This operation gives an error -
variable sized array may not be
initialised. Then just try this.
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
ar[i]=0;
}
import { View, Dimensions } from 'react-native'
var { width, height } = Dimensions.get('window')
// Create Component
<View style={{
borderBottomColor: 'black',
borderBottomWidth: 0.5,
width: width - 20,}}>
</View>
You can use Reflector and also use Add-In FileGenerator to extract source code into a project.
Try this:
echo mysql_result($result, 0);
This is enough because you are only fetching one field of one row.
There is actually a lot simpler and cleaner version than using request animationframe or timeouts. Iam suprised no one brought it up: the vanilla-js onload handler. If you can, use component did mount, if not, simply bind a function on the onload hanlder of the jsx component. If you want the function to run every render, also execute it before returning you results in the render function. the code would look like this:
runAfterRender = () => _x000D_
{_x000D_
const myElem = document.getElementById("myElem")_x000D_
if(myElem)_x000D_
{_x000D_
//do important stuff_x000D_
}_x000D_
}_x000D_
_x000D_
render()_x000D_
{_x000D_
this.runAfterRender()_x000D_
return (_x000D_
<div_x000D_
onLoad = {this.runAfterRender}_x000D_
>_x000D_
//more stuff_x000D_
</div>_x000D_
)_x000D_
}
_x000D_
}
I've tried this and it works:
yourelement.next().val();
yourelement could be:
$('#elementIdName').next().val();
good luck!
I like the answer by @thebeancounter, but prefer to parameterize the unknowns, the only problem being a vulnerability to exploits on the table name. If you're sure it's okay, then this works:
def get_col_names(cursor, tablename):
"""Get column names of a table, given its name and a cursor
(or connection) to the database.
"""
reader=cursor.execute("SELECT * FROM {}".format(tablename))
return [x[0] for x in reader.description]
If it's a problem, you could add code to sanitize the tablename.
ManagementFactory.getThreadMXBean().getThreadCount()
doesn't limit itself to thread groups as Thread.activeCount()
does.
You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:
Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs
) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
There's a guide on MSDN.
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
If one want to attach a process, this process must have the same owner. The root is able to attach to any process.
LocalDate date = LocalDate.now();
DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
try {
Date utilDate= formatter.parse(date.toString());
} catch (ParseException e) {
// handle exception
}
Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see
df["rowName", "columnName"] <- value
df[df$serial.id==5, "gender"] <- 1
What you want to do is fetch the value from the input and assign it to a new Date instance.
let date = document.getElementById('dateInput');
let formattedDate = new Date(date.value);
console.log(formattedDate);
You can use
String hex = String.format("#%02x%02x%02x", r, g, b);
Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF
vs. #ffffff
).
xgboost-0.6-cp36-cp36m-win_amd64.whl
for anaconda 3 (python 3.6)C:\
cd C:\
pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
conda update scikit-learn
If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:
$('#exampleBtn').click(function() {
function();
});
Add the following css to disable the default scroll:
body {
overflow: hidden;
}
And change the #content
css to this to make the scroll only on content body:
#content {
max-height: calc(100% - 120px);
overflow-y: scroll;
padding: 0px 10%;
margin-top: 60px;
}
Edit:
Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
bottom: 30px;_x000D_
right: 0;_x000D_
left: 0;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
background-color: #4C4;_x000D_
height: 50px;_x000D_
}_x000D_
footer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #4C4;_x000D_
height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
There is also another approach without the use of DomXPath
or Zend_Dom_Query
.
Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.
function getElementsByClass(&$parentNode, $tagName, $className) {
$nodes=array();
$childNodeList = $parentNode->getElementsByTagName($tagName);
for ($i = 0; $i < $childNodeList->length; $i++) {
$temp = $childNodeList->item($i);
if (stripos($temp->getAttribute('class'), $className) !== false) {
$nodes[]=$temp;
}
}
return $nodes;
}
suppose you have a variable $html
the following HTML:
<html>
<body>
<div id="content_node">
<p class="a">I am in the content node.</p>
<p class="a">I am in the content node.</p>
<p class="a">I am in the content node.</p>
</div>
<div id="footer_node">
<p class="a">I am in the footer node.</p>
</div>
</body>
</html>
use of getElementsByClass
is as simple as:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");
$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
With this command:
dpkg -s mysql-server | grep Status
When autocomplete changes a value, it fires a autocompletechange event, not the change event
$(document).ready(function () {
$('#tags').on('autocompletechange change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
});
Demo: Fiddle
Another solution is to use select event, because the change event is triggered only when the input is blurred
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
Demo: Fiddle
The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:
#### 1.1 My Subtitle \
1.1 My Subtitle
Next paragraph text.
An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).
### My Subtitle
1.1 My Subtitle
Next paragraph text.
Once you have established that they don't match, you still have a problem -- what to do about it. Often, the certificate may merely be assembled incorrectly. When a CA signs your certificate, they send you a block that looks something like
-----BEGIN CERTIFICATE-----
MIIAA-and-a-buncha-nonsense-that-is-your-certificate
-and-a-buncha-nonsense-that-is-your-certificate-and-
a-buncha-nonsense-that-is-your-certificate-and-a-bun
cha-nonsense-that-is-your-certificate-and-a-buncha-n
onsense-that-is-your-certificate-AA+
-----END CERTIFICATE-----
they'll also send you a bundle (often two certificates) that represent their authority to grant you a certificate. this will look something like
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-your-request
-this-is-the-certificate-that-signed-your-request-this
-is-the-certificate-that-signed-your-request-this-is-t
he-certificate-that-signed-your-request-this-is-the-ce
rtificate-that-signed-your-request-A
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-for-that-one
-this-is-the-certificate-that-signed-for-that-one-this
-is-the-certificate-that-signed-for-that-one-this-is-t
he-certificate-that-signed-for-that-one-this-is-the-ce
rtificate-that-signed-for-that-one-this-is-the-certifi
cate-that-signed-for-that-one-AA
-----END CERTIFICATE-----
except that unfortunately, they won't be so clearly labeled.
a common practice, then, is to bundle these all up into one file -- your certificate, then the signing certificates. But since they aren't easily distinguished, it sometimes happens that someone accidentally puts them in the other order -- signing certs, then the final cert -- without noticing. In that case, your cert will not match your key.
You can test to see what the cert thinks it represents by running
openssl x509 -noout -text -in yourcert.cert
Near the top, you should see "Subject:" and then stuff that looks like your data. If instead it lookslike your CA, your bundle is probably in the wrong order; you might try making a backup, and then moving the last cert to the beginning, hoping that is the one that is your cert.
If this doesn't work, you might just have to get the cert re-issued. When I make a CSR, I like to clearly label what server it's for (instead of just ssl.key or server.key) and make a copy of it with the date in the name, like mydomain.20150306.key etc. that way they private and public key pairs are unlikely to get mixed up with another set.
Whilst I was looking for my answer for the same question, I found this:
<img src="img.png" style=max-
width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0">
You can use it inside a tag (iframe or img) the image will adjust based on it's device.
I tried the above for a Float64Array and it just did not work.
I ended up realising that really the data needed to be read 'INTO' the view in correct chunks. This means reading 8 bytes at a time from the source Buffer.
Anyway this is what I ended up with...
var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new Float64Array(ab);
var viewIndex = 0;
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8) {
view[viewIndex] = buff.readDoubleLE(bufferIndex);
viewIndex++;
}
My solution that worked was to open R studio options and select global miror (the field was empty before) and the error went away.
It works in a different way for variables copied by reference:
$a = 5;
$b = &$a;
unset($b); // just say $b should not point to any variable
print $a; // 5
$a = 5;
$b = &$a;
$b = null; // rewrites value of $b (and $a)
print $a; // nothing, because $a = null
You can also debug tomcat using the community edition (Unlike what is said above).
Start tomcat in debug mode, for example like this: .\catalina.bat jpda run
In intellij: Run > Edit Configurations > +
Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)
Select Run > Debug "somename"
In Xcode 9 in the left panel open/choose your file in project navigator. If file is not there, drug-and-drop it into the project navigator.
On right panel find Text Settings and change Line Endings to Windows (CRLF) .
Keep in mind, the following is not intended to be a substitute for a proper security solution.
After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.
using System.Data.SQLite;
namespace EncryptDB
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"C:\Programming\sqlite3\db.db";
string passwordString = "password";
byte[] passwordBytes = GetBytes(passwordString);
SQLiteConnection.CreateFile(connectionString);
SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
conn.SetPassword(passwordBytes);
conn.Open();
SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
sqlCmd.ExecuteNonQuery();
sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
sqlCmd.ExecuteNonQuery();
conn.Close();
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
bytes = System.Text.Encoding.Default.GetBytes(str);
return bytes;
}
}
}
Optionally, you can remove conn.SetPassword(passwordBytes);
, and replace it with conn.ChangePassword("password");
which needs to be placed after conn.Open();
instead of before. Then you won't need the GetBytes method.
To decrypt, it's just a matter of putting the password in your connection string before the call to open.
string filename = @"C:\Programming\sqlite3\db.db";
string passwordString = "password";
SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
conn.Open();
You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable
$(document).ready(function() {
intro = "something";
});
although you cant use the variable immediately, but it would be accessible to other functions
Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)}
and I got errors, but when I change my code to exec sp...
it works very well.
I post my code in hope this helps others with problems like mine:
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
cs.setEscapeProcessing(true);
cs.setQueryTimeout(90);
cs.setString(1, "valueA");
cs.setString(2, "valueB");
cs.setString(3, "0418");
//commented, because no need to register parameters out!, I got results from the resultset.
//cs.registerOutParameter(1, Types.VARCHAR);
//cs.registerOutParameter(2, Types.VARCHAR);
rs = cs.executeQuery();
ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
while (rs.next()) {
ObjectX to = new ObjectX();
to.setFecha(rs.getString(1));
to.setRefId(rs.getString(2));
to.setRefNombre(rs.getString(3));
to.setUrl(rs.getString(4));
listaObjectX.add(to);
}
return listaObjectX;
} catch (SQLException se) {
System.out.println("Error al ejecutar SQL"+ se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Plenty of other answers that work. :)
var groups = _.groupBy(itemArray, 1);
var result = _.map(sortArray, function (i) { return groups[i].shift(); });
I'm guessing that most people came here looking for an equivalent to PHP's array_multisort (I did) so I thought I'd post that answer as well. There are a couple options:
1. There's an existing JS implementation of array_multisort(). Thanks to @Adnan for pointing it out in the comments. It is pretty large, though.
2. Write your own. (JSFiddle demo)
function refSort (targetData, refData) {
// Create an array of indices [0, 1, 2, ...N].
var indices = Object.keys(refData);
// Sort array of indices according to the reference data.
indices.sort(function(indexA, indexB) {
if (refData[indexA] < refData[indexB]) {
return -1;
} else if (refData[indexA] > refData[indexB]) {
return 1;
}
return 0;
});
// Map array of indices to corresponding values of the target array.
return indices.map(function(index) {
return targetData[index];
});
}
3. Lodash.js or Underscore.js (both popular, smaller libraries that focus on performance) offer helper functions that allow you to do this:
var result = _.chain(sortArray)
.pairs()
.sortBy(1)
.map(function (i) { return itemArray[i[0]]; })
.value();
...Which will (1) group the sortArray into [index, value]
pairs, (2) sort them by the value (you can also provide a callback here), (3) replace each of the pairs with the item from the itemArray at the index the pair originated from.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.
SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.
If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:
exec p_Example 42
When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.
From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.
This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.
Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:
SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use
These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.
Once you are done you can turn this option off with the following statement:
SET <<option>> OFF
Unless you have a strong preference my recommendation is to use the STATISTICS XML
option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.
SHOWPLAN_TEXT
- Displays a basic text based estimated execution plan, without executing the querySHOWPLAN_ALL
- Displays a text based estimated execution plan with cost estimations, without executing the querySHOWPLAN_XML
- Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.STATISTICS PROFILE
- Executes the query and displays a text based actual execution plan.STATISTICS XML
- Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.
Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!
The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.
If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.
We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.
SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.
Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).
You can't capture an execution plan for encrypted stored procedures.
An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).
This is a topic worthy enough for a (free) book in its own right.
Default argument values are evaluated at function define-time, but self
is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.
It's a common pattern to default an argument to None
and add a test for that in code:
def p(self, b=None):
if b is None:
b = self.a
print b
Here is the best way to use radio buttons in Angular2. There is no need to use the (click) event or a RadioControlValueAccessor to change the binded property value, setting [checked] property does the trick.
<input name="options" type="radio" [(ngModel)]="model.options" [value]="1"
[checked]="model.options==1" /><br/>
<input name="options" type="radio" [(ngModel)]="model.options" [value]="2"
[checked]="model.options==2" /><br/>
I published an example of using radio buttons: Angular 2: how to create radio buttons from enum and add two-way binding? It works from at least Angular 2 RC5.
For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.
Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.
Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).
When I use postman to send a file which is 5.6M to an external network, I faced the same issue. The same action is succeeded on my own computer and local testing environment.
After checking all the server configs and HTTP headers, I found that the reason is Postman may have some trouble simulating requests to external HTTP requests. Finally, I did the sendfile request on the chrome HTML page successfully. Just as a reference :)
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.
Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:
Pro:
Con:
Simple syntax, only a handful of different data types are supported.
No support for comments.
Pro:
Con:
So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.
Please feel free to add pros and cons. I'm not an XML expert ;)
Herman's solution works, but it can be simplified because Sqlite allows to store any value type on any field.
Here is a simpler version that uses one Value
field declared as TEXT
to store any value:
CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value TEXT);
INSERT OR REPLACE INTO Variables VALUES ('VarStr', 'Val1');
INSERT OR REPLACE INTO Variables VALUES ('VarInt', 123);
INSERT OR REPLACE INTO Variables VALUES ('VarBlob', x'12345678');
SELECT Value
FROM Variables
WHERE Name = 'VarStr'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarInt'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarBlob';
I was looking for something that looked like jquery for generating dom in C# (I don't need to parse). Unfortunately no luck in finding a lightweight solution so I created this simple class that is inherited from System.Xml.Linq.XElement. The key feature is that you can chain the operator like when using jquery in javascript so it's more fluent. It's not fully featured but it does what I need and if there is interest I can start a git.
public class DomElement : XElement
{
public DomElement(string name) : base(name)
{
}
public DomElement(string name, string value) : base(name, value)
{
}
public DomElement Css(string style, string value)
{
style = style.Trim();
value = value.Trim();
var existingStyles = new Dictionary<string, string>();
var xstyle = this.Attribute("style");
if (xstyle != null)
{
foreach (var s in xstyle.Value.Split(';'))
{
var keyValue = s.Split(':');
existingStyles.Add(keyValue[0], keyValue.Length < 2 ? null : keyValue[1]);
}
}
if (existingStyles.ContainsKey(style))
{
existingStyles[style] = value;
}
else
{
existingStyles.Add(style, value);
}
var styleString = string.Join(";", existingStyles.Select(s => $"{s.Key}:{s.Value}"));
this.SetAttributeValue("style", styleString);
return this;
}
public DomElement AddClass(string cssClass)
{
var existingClasses = new List<string>();
var xclass = this.Attribute("class");
if (xclass != null)
{
existingClasses.AddRange(xclass.Value.Split());
}
var addNewClasses = cssClass.Split().Where(e => !existingClasses.Contains(e));
existingClasses.AddRange(addNewClasses);
this.SetAttributeValue("class", string.Join(" ", existingClasses));
return this;
}
public DomElement Text(string text)
{
this.Value = text;
return this;
}
public DomElement Append(string text)
{
this.Add(text);
return this;
}
public DomElement Append(DomElement child)
{
this.Add(child);
return this;
}
}
Sample:
void Main()
{
var html = new DomElement("html")
.Append(new DomElement("head"))
.Append(new DomElement("body")
.Append(new DomElement("p")
.Append("This paragraph contains")
.Append(new DomElement("b", "bold"))
.Append(" text.")
)
.Append(new DomElement("p").Text("This paragraph has just plain text"))
)
;
html.ToString().Dump();
var table = new DomElement("table").AddClass("table table-sm").AddClass("table-striped")
.Append(new DomElement("thead")
.Append(new DomElement("tr")
.Append(new DomElement("td").Css("padding-left", "15px").Css("color", "red").Css("color", "blue")
.AddClass("from-now")
.Append(new DomElement("div").Text("Hi there"))
.Append(new DomElement("div").Text("Hey there"))
.Append(new DomElement("div", "Yo there"))
)
)
)
;
table.ToString().Dump();
}
output from above code:
<html>
<head />
<body>
<p>This paragraph contains<b>bold</b> text.</p>
<p>This paragraph has just plain text</p>
</body>
</html>
<table class="table table-sm table-striped">
<thead>
<tr>
<td style="padding-left:15px;color:blue" class="from-now">
<div>Hi there</div>
<div>Hey there</div>
<div>Yo there</div>
</td>
</tr>
</thead>
</table>
private static void printStar(int x) {
int i, j;
for (int y = 0; y < x; y++) { // number of row of '*'
for (i = y; i < x - 1; i++)
// number of space each row
System.out.print(' ');
for (j = 0; j < y * 2 + 1; j++)
// number of '*' each row
System.out.print('*');
System.out.println();
}
}
class expression can be used for simplicity.
// Foo.js
'use strict';
// export default class Foo {}
module.exports = class Foo {}
-
// main.js
'use strict';
const Foo = require('./Foo.js');
let Bar = new class extends Foo {
constructor() {
super();
this.name = 'bar';
}
}
console.log(Bar.name);
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
To install 3.0 which is the latest stable version:
$ git clone http://github.com/antirez/redis.git
$ cd redis && git checkout 3.0
$ make redis-cli
Optionally, you can put the compiled executable in your load path for convenience:
$ ln -s src/redis-cli /usr/local/bin/redis-cli
Here is modern variant that can be used for ints
of different sizes.
#include <type_traits>
#include <bitset>
template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
return std::bitset<sizeof(T) * 8>(i).to_string();
}
You're calling write_file with arguments like this:
write_file(foo, bar)
But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.
It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen
because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.
While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.
my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
TLDR: they are equivalent Error(x) === new Error(x)
.
// this:
const x = Error('I was created using a function call!');
????// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
throw and throw Error will are functionally equivalent. But when you catch them and serialize them to console.log they are not serialized exactly the same way:
throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');
Console.log(e) of the above will produce 2 different results:
Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!
Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)
git mergetool
Then add your changes and go on
git rebase --continue
Good luck
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
Need to add package
sudo apt-get install libpq-dev
to install pg gem in RoR
You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
Happy coding.
To get sequence id use
SELECT pg_get_serial_sequence('tableName', 'ColumnName');
This will gives you sequesce id as tableName_ColumnName_seq
To Get Last seed number use
select currval(pg_get_serial_sequence('tableName', 'ColumnName'));
or if you know sequence id already use it directly.
select currval(tableName_ColumnName_seq);
It will gives you last seed number
To Reset seed number use
ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45
I use this:
clock_t start, end;
double elapsed;
start = clock();
//Start code to time
//End code to time
end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);
But I'm not sure about CLOCKS_PER_SEC on the iPhone. You might want to leave it off.
.zone() has been deprecated, and you should use utcOffset instead:
// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')
SELECT id FROM `table` ORDER BY id DESC LIMIT 1
Although I doubt in its productiveness but it's 100% reliable
When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_download(s3path, destination)
directly or the copy-pasted code:
def s3_download(source, destination,
exists_strategy='raise',
profile_name=None):
"""
Copy a file from an S3 source to a local destination.
Parameters
----------
source : str
Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
destination : str
exists_strategy : {'raise', 'replace', 'abort'}
What is done when the destination already exists?
profile_name : str, optional
AWS profile
Raises
------
botocore.exceptions.NoCredentialsError
Botocore is not able to find your credentials. Either specify
profile_name or add the environment variables AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
See https://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
exists_strategies = ['raise', 'replace', 'abort']
if exists_strategy not in exists_strategies:
raise ValueError('exists_strategy \'{}\' is not in {}'
.format(exists_strategy, exists_strategies))
session = boto3.Session(profile_name=profile_name)
s3 = session.resource('s3')
bucket_name, key = _s3_path_split(source)
if os.path.isfile(destination):
if exists_strategy is 'raise':
raise RuntimeError('File \'{}\' already exists.'
.format(destination))
elif exists_strategy is 'abort':
return
s3.Bucket(bucket_name).download_file(key, destination)
from collections import namedtuple
S3Path = namedtuple("S3Path", ["bucket_name", "key"])
def _s3_path_split(s3_path):
"""
Split an S3 path into bucket and key.
Parameters
----------
s3_path : str
Returns
-------
splitted : (str, str)
(bucket, key)
Examples
--------
>>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
"""
if not s3_path.startswith("s3://"):
raise ValueError(
"s3_path is expected to start with 's3://', " "but was {}"
.format(s3_path)
)
bucket_key = s3_path[len("s3://"):]
bucket_name, key = bucket_key.split("/", 1)
return S3Path(bucket_name, key)
In this simple case, where someClass.f
is not inheriting any data from the class and not attaching anything to the class, a possible solution would be to separate out f
, so it can be pickled:
import multiprocessing
def f(x):
return x*x
class someClass(object):
def __init__(self):
pass
def go(self):
pool = multiprocessing.Pool(processes=4)
print pool.map(f, range(10))
AnyObject
is the official way to use a weak reference in Swift.
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate: AnyObject {
}
From Apple:
To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.
At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:
sed -i '' -e's/[[:space:]]*$//' "$1"
If working in Java 1.8 you can leverage the DateTimeFormatterBuilder
public static boolean isTimeStampValid(String inputString)
{
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm:ss.SSSZ]" + "[yyyy-MM-dd]"));
DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
try {
dateTimeFormatter.parse(inputString);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
See post: Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?
If you don't pass any argument then even in that case args gets initialized but without any item/element. Try the following one, you will get the same effect:
public static void main(String[] args) throws InterruptedException {
String [] dummy= new String [] {};
if(dummy[0] == null)
{
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}
If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.
sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))
I have toyed with this for forever, and finally found something that seems to always work!
textField = new JTextField() {
public void addNotify() {
super.addNotify();
requestFocus();
}
};
Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.
And generally it does a good job...
param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}
Or if you need to pass multiple parameters:
param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
$iTunes.<AnyProperty> = $x2
}
We had a similar problem with BIRT reports in that we wanted to report on those days that had no data. Since there were no entries for those dates, the easiest solution for us was to create a simple table that stored all dates and use that to get ranges or join to get zero values for that date.
We have a job that runs every month to ensure that the table is populated 5 years out into the future. The table is created thus:
create table all_dates (
dt date primary key
);
No doubt there are magical tricky ways to do this with different DBMS' but we always opt for the simplest solution. The storage requirements for the table are minimal and it makes the queries so much simpler and portable. This sort of solution is almost always better from a performance point-of-view since it doesn't require per-row calculations on the data.
The other option (and we've used this before) is to ensure there's an entry in the table for every date. We swept the table periodically and added zero entries for dates and/or times that didn't exist. This may not be an option in your case, it depends on the data stored.
If you really think it's a hassle to keep the all_dates
table populated, a stored procedure is the way to go which will return a dataset containing those dates. This will almost certainly be slower since you have to calculate the range every time it's called rather than just pulling pre-calculated data from a table.
But, to be honest, you could populate the table out for 1000 years without any serious data storage problems - 365,000 16-byte (for example) dates plus an index duplicating the date plus 20% overhead for safety, I'd roughly estimate at about 14M [365,000 * 16 * 2 * 1.2 = 14,016,000 bytes]), a minuscule table in the scheme of things.
In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds
file. Not so for Rda
> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)
## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5
## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to <environment: R_GlobalEnv>
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values.
> x
[1] 1 2 3 4 5
Note: this will not work with ASP.Net Core because WebImage depends on System.Web, but on previous versions of ASP.Net I used this snippet many times and was useful.
String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg";
var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
{
var thumbnail = new WebImage(stream).Resize(80, 80);
thumbnail.Save(ThumbfullPath2, "jpg");
}
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Using python 64 bit solves lot of problems.
If you can't find the clipboard, then close that excel sheet and reopen it again. This will solve your problem.
There is no log file. Each node.js "app" is a separate entity. By default it will log errors to STDERR and output to STDOUT. You can change that when you run it from your shell to log to a file instead.
node my_app.js > my_app_log.log 2> my_app_err.log
Alternatively (recommended), you can add logging inside your application either manually or with one of the many log libraries:
let string = " Test Trimmed String "
For Removing white Space and New line use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
For Removing only Spaces from string use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)
As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el))
method will produce the following warning:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
Converting your columns to numpy arrays should do the job (I prefer StandardScaler):
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())
-- Edit Nov 2018 (Tested for pandas 0.23.4)--
As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix()
returns FutureWarning
. Therefore, it should be replaced by .values
:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit_transform(dfTest[['A','B']].values)
-- Edit May 2019 (Tested for pandas 0.24.2)--
As joelostblom mentions in the comments, "Since 0.24.0
, it is recommended to use .to_numpy()
instead of .values
."
Updated example:
import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
A B C
0 -1.995290 -1.571117 big
1 0.436356 -0.603995 small
2 0.460289 0.100818 big
3 0.630058 0.985826 small
4 0.468586 1.088469 small
Use parentheses to group the individual branches:
IF EXIST D:\RPS_BACKUP\backups_to_zip\ (goto zipexist) else goto zipexistcontinue
In your case the parser won't ever see the else
belonging to the if
because goto
will happily accept everything up to the end of the command. You can see a similar issue when using echo
instead of goto
.
Also using parentheses will allow you to use the statements directly without having to jump around (although I wasn't able to rewrite your code to actually use structured programming techniques; maybe it's too early or it doesn't lend itself well to block structures as the code is right now).
In php 7 there is the php ini option opcache.file_cache that saves the bytecode in a specific folder. In could be useful to in php cli script that are "compiled" and saved in a specific folder for a optimized reuse.
Opcache it is not compiling but is something similar.
Also make sure the div is currently appended to the DOM and visible.
In your Ruby on Rails controller you can use:
private
before_filter :safari_cookie_fix
def safari_cookie_fix
user_agent = UserAgent.parse(request.user_agent) # Uses useragent gem!
if user_agent.browser == 'Safari' # we apply the fix..
return if session[:safari_cookie_fixed] # it is already fixed.. continue
if params[:safari_cookie_fix].present? # we should be top window and able to set cookies.. so fix the issue :)
session[:safari_cookie_fixed] = true
redirect_to params[:return_to]
else
# Redirect the top frame to your server..
render :text => "<script>alert('start redirect');top.window.location='?safari_cookie_fix=true&return_to=#{set_your_return_url}';</script>"
end
end
end
An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.
Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();
This is what I am going to use based on marc_s answer:
SELECT
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)
FROM WEBPAGECONTENT
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0
Return a substring on the search where the search criteria exists
In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.
If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.
If you want to search for multilines by the character literal, remember to check the rightmost regex icon.
In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.
Another way to fix this would be to go to the properties of the server on eclipse (right click on server -> properties) In general tab you would see location as workspace.metadata. Click on switch location.
Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:
import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])
Since .sheet_names
returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).
I find that the --tree-filter
option used in other answers can be very slow, especially on larger repositories with lots of commits.
Here is the method I use to completely remove a directory from the git history using the --index-filter
option, which runs much quicker:
# Make a fresh clone of YOUR_REPO
git clone YOUR_REPO
cd YOUR_REPO
# Create tracking branches of all branches
for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done
# Remove DIRECTORY_NAME from all commits, then remove the refs to the old commits
# (repeat these two commands for as many directories that you want to remove)
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch DIRECTORY_NAME/' --prune-empty --tag-name-filter cat -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
# Ensure all old refs are fully removed
rm -Rf .git/logs .git/refs/original
# Perform a garbage collection to remove commits with no refs
git gc --prune=all --aggressive
# Force push all branches to overwrite their history
# (use with caution!)
git push origin --all --force
git push origin --tags --force
You can check the size of the repository before and after the gc
with:
git count-objects -vH
The command ansible localhost -m setup
basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.
When you run the echo
command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:
- hosts: localhost
tasks:
- debug: var=ansible_date_time
- debug: msg="the current date is {{ ansible_date_time.date }}"
Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:
PLAY [localhost] **************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [debug var=ansible_date_time] *******************************************
ok: [localhost] => {
"ansible_date_time": {
"date": "2015-07-09",
"day": "09",
"epoch": "1436461166",
"hour": "16",
"iso8601": "2015-07-09T16:59:26Z",
"iso8601_micro": "2015-07-09T16:59:26.896629Z",
"minute": "59",
"month": "07",
"second": "26",
"time": "16:59:26",
"tz": "UTC",
"tz_offset": "+0000",
"weekday": "Thursday",
"year": "2015"
}
}
TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
ok: [localhost] => {
"msg": "the current date is 2015-07-09"
}
PLAY RECAP ********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0
This can also happen if you restore a database and the user already exists with different schema, leaving you unable to assign the correct permissions.
To correct this run:
USE your_database
EXEC sp_change_users_login 'Auto_Fix', 'user', NULL, 'cf'
GO
EXEC sp_change_users_login 'update_one', 'user', 'user'
GO
As I used ul:not(:first-child)
is a perfect solution.
div ul:not(:first-child) {
background-color: #900;
}
Why is this a perfect because by using ul:not(:first-child)
, we can apply CSS on inner elements. Like li, img, span, a
tags etc.
But when used others solutions:
div ul + ul {
background-color: #900;
}
and
div li~li {
color: red;
}
and
ul:not(:first-of-type) {}
and
div ul:nth-child(n+2) {
background-color: #900;
}
These restrict only ul level CSS. Suppose we cannot apply CSS on li
as `div ul + ul li'.
For inner level elements the first Solution works perfectly.
div ul:not(:first-child) li{
background-color: #900;
}
and so on ...
To 1): Yes, on most CPUs, SHA-256 is about only 40% as fast as MD5.
To 2): I would argue for a different algorithm than MD5 in such a case. I would definitely prefer an algorithm that is considered safe. However, this is more a feeling. Cases where this matters would be rather constructed than realistic, e.g. if your backup system encounters an example case of an attack on an MD5-based certificate, you are likely to have two files in such an example with different data, but identical MD5 checksums. For the rest of the cases, it doesn't matter, because MD5 checksums have a collision (= same checksums for different data) virtually only when provoked intentionally. I'm not an expert on the various hashing (checksum generating) algorithms, so I can not suggest another algorithm. Hence this part of the question is still open. Suggested further reading is Cryptographic Hash Function - File or Data Identifier on Wikipedia. Also further down on that page there is a list of cryptographic hash algorithms.
To 3): MD5 is an algorithm to calculate checksums. A checksum calculated using this algorithm is then called an MD5 checksum.
Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )
The dump itself will be faster. (for what I tested it was double as fast)
Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.
So I would go for "&& gzip" instead of "| gzip"
Important: check for free disk space first with df -h
since you will need more then piping | gzip.
mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql
-> which will also result in 1 file called dumpfilename.sql.gz
Furthermore the option --single-transaction
prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here
mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql
q <- c(1,1,2,2,3,3,3,4,4,5,5,7,7)
rm <- q[11]
remove(rm)
q
q[13] = NaN
q
q %in% 7
This sets the 13 in a vector to not a number(NAN) it shows false remove(q[c(11,12,13)]) if you try this you will see that remove function don't work on vector number. you remove entire vector but maybe not a single element.
The mysql_install_db
script also needs the datadir
parameter:
mysql_install_db --user=root --datadir=$db_datapath
On Maria DB you use the install script mysql_install_db
to install and initialize. In my case I use an environment variable for the data path. Not only does mysqld
need to know where the data is (specified via commandline), but so does the install script.
You can do it in the following way: So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.
function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
const roundedNumber = number.toFixed(decimals);
let integerPart = '', fractionalPart = '';
if (decimals == 0) {
integerPart = roundedNumber;
decimalSeparator = '';
} else {
let numberParts = roundedNumber.split('.');
integerPart = numberParts[0];
fractionalPart = numberParts[1];
}
integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
return `${integerPart}${decimalSeparator}${fractionalPart}`;
}
Use:
let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
let randomNumber = Math.random() * (max - min) + min;
let formated = format(randomNumber, 4, ',', '.'); // formated number
console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');
If you are looking to highlight a shell session command sequence as it looks to the user (with prompts, not just as contents of a hypothetical script file), then the right identifier to use at the moment is console:
```console
foo@bar:~$ whoami
foo
```
Under Windows only: You may try to use ini_set()
functionDocs for the SMTP
Docs and smtp_port
Docs settings:
ini_set('SMTP', 'mysmtphost');
ini_set('smtp_port', 25);
This is a sample code I used to counter the problem.
\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}
First subtract the pivot point (cx,cy)
, then rotate it, then add the point again.
Untested:
POINT rotate_point(float cx,float cy,float angle,POINT p)
{
float s = sin(angle);
float c = cos(angle);
// translate point back to origin:
p.x -= cx;
p.y -= cy;
// rotate point
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
// translate point back:
p.x = xnew + cx;
p.y = ynew + cy;
return p;
}
I like using this tool to permit easily to send email HTML and TXT with easy context processing: https://github.com/divio/django-emailit
Here is the steps I followed to export the .ipa
Try this command:
sudo gedit helloWorld.txt
it, will open up a text editor to edit your file.
OR
sudo nano helloWorld.txt
Here, you can edit your file in the terminal window.
In Java 8 and later it could be done in one line using class java.time.LocalTime.
In the formatting pattern, lowercase hh
means 12-hour clock while uppercase HH
means 24-hour clock.
Code example:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
See this code run live at IdeOne.com.
15:30
See Oracle Tutorial.
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
If you want your CSS to be copied into the output without being processed, you can use the (inline)
directive. e.g.,
@import (inline) '../timepicker/jquery.ui.timepicker.css';
You can do it like this:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);
here 'kk:mm:ss' is right answer, I confused with Oracle database, sorry.
It has to do with how the function is called- basically the order in which things are put on the the stack and who is responsible for cleanup.
Here's the documentation, but it doesn't mean much unless you understand the first part:
http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
Delete your source tree that was gunzipped or gzipped and extracted to folder and reextract again. Supply your options again
./configure --with-option=/path/etc ...
Then if all libs are present, your make should succeed.
I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.
The 1st package xlrd was installed by "pip install" without problems in my Python home.
The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.
The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:
#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)
I attached the file here: http://ifolder.su/43507580
Write to [email protected] if it got expired.
P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
During initialization you have to set to false the option enableOnReadonly which by default is true.
$('#datepicker').datepicker({
enableOnReadonly: false
});
Then, you need to make the field readonly
$('#datepicker').prop('readonly', true);
See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];
MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.
Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.
However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h
, so most of the idealistic dedication just ends up being a waste of time.
I know I'm late :) But this how i do it:
public static void AddOrUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
For more information look at MSDN
To apply different classes when different expressions evaluate to true
:
<div ng-class="{class1 : expression1, class2 : expression2}">
Hello World!
</div>
To apply multiple classes when an expression holds true:
<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
Hello World!
</div>
or quite simply:
<div ng-class="{'class1 class2' : expression1}">
Hello World!
</div>
Notice the single quotes surrounding css classes.
As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.
The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.
To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.
You may also try appending a space at the start and end of keyword: /\s+123456\s+/i
.
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);
// returns "Variable myFirstName with value 'John'"
xargs on MacOS doesn't have -d option, so this solution uses -0 instead.
Get ls to output one file per line, then translate newlines into nulls and tell xargs to use nulls as the delimiter:
ls -1 *mp3 | tr "\n" "\0" | xargs -0 mplayer
The same idea as Tatu(thanks I'll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.
<html>
<head>
<title>excelToTable</title>
<script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<textarea>a1 a2 a3
b1 b2 b3</textarea>
<div></div>
<input type="button" onclick="convert()" value="convert"/>
<script>
function convert(){
var xl = $('textarea').val();
$('div').html(
'<table><tr><td>' +
xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') +
'</tr></table>'
)
}
</script>
</body>
</html>
This may also be useful: {{ form.field.as_hidden }}
In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:
Right-click on "Anaconda Prompt" again.
Click "Properties"
Add the path you want your anaconda prompt to open up into in the "Start In:" section.
Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.
Here's what I initially did, which does work, however it seems rather long-winded and ugly (global static anything is never good)
1: App.xaml.cs
public partial class App : Application
{
// create a new global custom WPF Command
public static readonly RoutedUICommand LoggedIn = new RoutedUICommand();
}
2: LoginForm.xaml
// bind the global command to a local eventhandler
<CommandBinding Command="client:App.LoggedIn" Executed="OnLoggedIn" />
3: LoginForm.xaml.cs
// implement the local eventhandler in codebehind
private void OnLoggedIn( object sender, ExecutedRoutedEventArgs e )
{
DialogResult = true;
Close();
}
4: LoginFormViewModel.cs
// fire the global command from the viewmodel
private void OnRemoteServerReturnedSuccess()
{
App.LoggedIn.Execute(this, null);
}
I later on then removed all this code, and just had the LoginFormViewModel
call the Close method on it's view. It ended up being much nicer and easier to follow. IMHO the point of patterns is to give people an easier way to understand what your app is doing, and in this case, MVVM was making it far harder to understand than if I hadn't used it, and was now an anti-pattern.
I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
Change it to
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
</web-app>
save the project, and your error would gone.
After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.
Hopefully error would be gone then.
Thanks
So, we have a situation when we need to statically get class object or a class full/simple name without an explicit usage of MyClass.class
syntax.
It can be really handy in some cases, e.g. logger instance for the kotlin upper-level functions (in this case kotlin creates a static Java class not accessible from the kotlin code).
We have a few different variants for getting this info:
new Object(){}.getClass().getEnclosingClass();
noted by Tom Hawtin - tackline
getClassContext()[0].getName();
from the SecurityManager
noted by Christoffer
new Throwable().getStackTrace()[0].getClassName();
by count ludwig
Thread.currentThread().getStackTrace()[1].getClassName();
from Keksi
and finally awesome
MethodHandles.lookup().lookupClass();
from Rein
I've prepared a jmh benchmark for all variants and results are:
# Run complete. Total time: 00:04:18
Benchmark Mode Cnt Score Error Units
StaticClassLookup.MethodHandles_lookup_lookupClass avgt 30 3.630 ± 0.024 ns/op
StaticClassLookup.AnonymousObject_getClass_enclosingClass avgt 30 282.486 ± 1.980 ns/op
StaticClassLookup.SecurityManager_classContext_1 avgt 30 680.385 ± 21.665 ns/op
StaticClassLookup.Thread_currentThread_stackTrace_1_className avgt 30 11179.460 ± 286.293 ns/op
StaticClassLookup.Throwable_stackTrace_0_className avgt 30 10221.209 ± 176.847 ns/op
MethodHandles.lookup().lookupClass();
new Object(){}.getClass().getEnclosingClass();
If you need it in many places and don't want your bytecode to bloat due to tons of anonymous classes – SecurityManager
is your friend (third best option).
But you can't just call getClassContext()
– it's protected in the SecurityManager
class. You will need some helper class like this:
// Helper class
public final class CallerClassGetter extends SecurityManager
{
private static final CallerClassGetter INSTANCE = new CallerClassGetter();
private CallerClassGetter() {}
public static Class<?> getCallerClass() {
return INSTANCE.getClassContext()[1];
}
}
// Usage example:
class FooBar
{
static final Logger LOGGER = LoggerFactory.getLogger(CallerClassGetter.getCallerClass())
}
getStackTrace()
from exception or the Thread.currentThread()
. Very inefficient and can return only the class name as a String
, not the Class<*>
instance.If you want to create a logger instance for static kotlin utils (like me :), you can use this helper:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
// Should be inlined to get an actual class instead of the one where this helper declared
// Will work only since Java 7 and Android API 26!
@Suppress("NOTHING_TO_INLINE")
inline fun loggerFactoryStatic(): Logger
= LoggerFactory.getLogger(MethodHandles.lookup().lookupClass())
Usage example:
private val LOGGER = loggerFactoryStatic()
/**
* Returns a pseudo-random, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* @param min the least value returned
* @param max the upper bound (exclusive)
*
* @return the next value
* @throws IllegalArgumentException if least greater than or equal to bound
* @see java.util.concurrent.ThreadLocalRandom.nextDouble(double, double)
*/
fun Random.nextDouble(min: Double = .0, max: Double = 1.0): Double {
if (min >= max) {
if (min == max) return max
LOGGER.warn("nextDouble: min $min > max $max")
return min
}
return nextDouble() * (max - min) + min
}
In 1.0, the functionality was bound to (
and tab
and shift-tab
, in 2.0 tab
was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab
. (
was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab
.
So press Shift-Tab
.
This is a perfect use-case for DISTINCT ON
- a Postgres specific extension of the standard DISTINCT
:
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY category, date DESC;
Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST
:
DISTINCT ON
is simple and fast. Detailed explanation in this related answer:
For big tables with many rows per category
consider an alternative approach:
Using MS SQL Server 2012, you need to perform 3 basic steps:
First, generate .sql
file containing only the structure of the source DB
.sql
file locallySecond, replace the source DB with the destination one in the .sql
file
Finally, populate with data
Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
You are done.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Did you try:
<Directory /path/to/your/wp-admin>
Order allow,deny
Allow from all
</Directory>
Generally, I see continue
(and break
) as a warning that the code might use some refactoring, especially if the while
or for
loop declaration isn't immediately in sight. The same is true for return
in the middle of a method, but for a slightly different reason.
As others have already said, continue
moves along to the next iteration of the loop, while break
moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue
/break
and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue
/break
failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue
, break
, and return
(other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
Align the table to center.
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center">
Your Content
</td>
</tr>
</table>
Where you have "your content" if it is a table, set it to the desired width and you will have centred content.
The simple solution is:
1.keep the image file and HTML file in the same folder.
2.code: <img src="Desert.png">
// your image name.
3.keep the folder in D drive.
Keeping the folder on the desktop(which is c drive) you can face the issue of permission.
You should use the .End(xlup)
but instead of using 65536 you might want to use:
sheetvar.Rows.Count
That way it works for Excel 2007 which I believe has more than 65536 rows
you can use the collector like this
Stream<String> io = Stream.of("foo" , "lan" , "mql");
io.collect(Collectors.toCollection(ArrayList<String>::new));
Convert the string to an integer base 16 then to hexadecimal.
print hex(int(string, base=16))
These are built-in functions.
http://docs.python.org/2/library/functions.html#int
Example
>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>>
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.
public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
T returnObject = default(T);
if (string.IsNullOrEmpty(XmlFilename)) return default(T);
try
{
StreamReader xmlStream = new StreamReader(XmlFilename);
XmlSerializer serializer = new XmlSerializer(typeof(T));
returnObject = (T)serializer.Deserialize(xmlStream);
}
catch (Exception ex)
{
ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
}
return returnObject;
}
Then you'd call it like this:
MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
The problem is that you need to include B.h
in your A.h
file. The problem is that in the definition of A
, the compiler still doesn't know what B
is. You should include all the definitions of all the types you are using.
You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:
setTimeout("Func1()", 3000);
This will call 'Func1()' after 3 seconds.
Edit:
Credit goes to the commenters, but you can pass anonymous functions to setTimeout.
setTimeout(function() {
//Do some stuff here
}, 3000);
This is much more efficient and does not invoke javascript's eval function.
just pass the columnName as parameter of YEAR
SELECT YEAR(ASOFDATE) from PSASOFDATE;
another is to use DATE_FORMAT
SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;
UPDATE 1
I bet the value is varchar with the format MM/dd/YYYY, it that's the case,
SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));
LAST RESORT if all the queries fail
use SUBSTRING
SELECT SUBSTRING('11/15/2012', 7, 4)
i know i'm late but this might help. you can add specific type of image or other file type and do validation in your code :
<input style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf" (change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">
handleFileInput(event) {
console.log(event);
const file = event.target.files[0];
if (file.size > 2097152) {
throw err;
} else if (
file.type !== "application/pdf" &&
file.type !== "application/wps-office.pdf" &&
file.type !== 'application/pdf' && file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== "image/png"
) {
throw err;
} else {
console.log('file valid')
}
}
You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM
type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat
works well).
implode(' ',$array);
Simple steps to install python in Ubuntu:
Download Python
$ cd /usr/src
$ wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
Extract the downloaded package
$ sudo tar xzf Python-3.6.0.tgz
Compile Python source
$ cd Python-3.6.0
$ sudo ./configure
$ sudo make altinstall
Note make altinstall
is used to prevent replacing the default python binary file /usr/bin/python
.
check the python version
# python3.6 -V
You are using .index()
which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0)
will always return 2
, no matter how many times 1.0
occurs in the list.
Use enumerate()
to add indices to your loop instead:
def find(lst, a, b):
result = []
for i, x in enumerate(lst):
if x<a or x>b:
result.append(i)
return result
You can collapse this into a list comprehension:
def find(lst, a, b):
return [i for i, x in enumerate(lst) if x<a or x>b]
After trying all the above and using the answer from @Aaron Hall, I was getting memory errors for a ~90 Mb file on a computer running Window 10, 8 Gb RAM and Python 3.5 32-bit. I was recommended by a colleague to use numpy
instead and it works wonders.
By far, the fastest to read an entire binary file (that I have tested) is:
import numpy as np
file = "binary_file.bin"
data = np.fromfile(file, 'u1')
Multitudes faster than any other methods so far. Hope it helps someone!
Try these steps:
Clean the solution.
Build every project separately.
Resolve any errors if found (sometimes, VS is not showing errors until you build it separately).
Then try to run migration again.
in the terminal window on your mac, press control+c
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
Keep it simple...
$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);
Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode ()
. People have posted how to use that, so I am not including it here.
Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:
$str = '1';
($str == 1) // true but
($str === 1) //false
Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.
IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize
Assign value(_getCurrentHolidayList) inside the loop
foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
if (_holidayItem.CountryId == Countryid)
_getCurrentHolidayList = _holidayItem.Holiday;
}
After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.
var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);
if you mentioned like below, It will not throw any error.
IEnumerable<DateTime?> _getCurrentHolidayList =null;
Cookies are key/value pairs used by websites to store state information on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store information on the browser.
Browser request example:
GET /index.html HTTP/1.1
Host: www.example.com
Example answer from the server:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest of the response
Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.
GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*
Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.
You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...
Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.
Cookie Pros:
Cookie Cons:
Session Pros:
Session Cons:
For example, I will create a table called users
as below and give a column named date
a default value NOW()
create table users_parent (
user_id varchar(50),
full_name varchar(240),
login_id_1 varchar(50),
date timestamp NOT NULL DEFAULT NOW()
);
Thanks
you have to create a custom DataGridView
`
namespace System.Windows.Forms
{
class MyDataGridView : DataGridView
{
public bool PreventUserClick = false;
public MyDataGridView()
{
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (PreventUserClick) return;
base.OnMouseDown(e);
}
}
}
` note that you have to first compile the program once with the added class, before you can use the new control.
then go to The .Designer.cs and change the old DataGridView to the new one without having to mess up you previous code.
private System.Windows.Forms.DataGridView dgv; // found close to the bottom
…
private void InitializeComponent() {
...
this.dgv = new System.Windows.Forms.DataGridView();
...
}
to (respective)
private System.Windows.Forms.MyDataGridView dgv;
this.dgv = new System.Windows.Forms.MyDataGridView();
I think you meant something like "*" (star) as a wildcard for example:
or in your example: "bird*" => everything that starts with bird
I had a similar problem and wrote a function with RegExp:
//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
}_x000D_
_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
// for this solution to work on any string, no matter what characters it has_x000D_
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
_x000D_
// "." => Find a single character, except newline or line terminator_x000D_
// ".*" => Matches any string that contains zero or more characters_x000D_
rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
_x000D_
// "^" => Matches any string with the following at the beginning of it_x000D_
// "$" => Matches any string with that in front at the end of it_x000D_
rule = "^" + rule + "$"_x000D_
_x000D_
//Create a regular expression object for matching string_x000D_
var regex = new RegExp(rule);_x000D_
_x000D_
//Returns true if it finds a match, otherwise it returns false_x000D_
return regex.test(str);_x000D_
}_x000D_
_x000D_
//Examples_x000D_
alert(_x000D_
"1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
"2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_
);
_x000D_
If you want to read more about the used functions:
This should work(with or without 'javascript:' part):
<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
alert(a, b);
}
</script>