They contain byte code, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine.
Python's documentation explains the definition like this:
Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. This means that source files can be run directly without explicitly creating an executable which is then run.
Yes, you can get it with unpyclib
that can be found on pypi.
$ pip install unpyclib
Than you can decompile your .pyc file
$ python -m unpyclib.application -Dq path/to/file.pyc
I think this would be best explained by the following picture:
To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
Better than all options, you can set your signingConfig
to be equals your debug.signingConfig
.
To do that you just need to do the following:
android {
...
buildTypes {
...
wantedBuildType {
signingConfig debug.signingConfig
}
}
}
With that you will not need to know where the debug.keystore
is, the app will work for all team, even if someone use a different environment.
To change font size using the keyboard
In Windows or Linux press Ctrl+Shift+A
In MAC press CMD+Shift+A
In the popup frame, type Increase font size
or Decrease font size
, and then click Enter.
Font grows larger or smaller.
For a CSS-only solution, try using the checkbox hack. Basically, the idea is to use a checkbox and assign different styles based on whether the box is checked or not used the :checked
pseudo selector. The checkbox can be hidden, if need be, by attaching it to a label
.
link to dabblet (not mine): http://dabblet.com/gist/1506530
link to CSS Tricks article: http://css-tricks.com/the-checkbox-hack/
The standard SQL way is to use like:
where @stringVar like '%thisstring%'
That is in a query statement. You can also do this in TSQL:
if @stringVar like '%thisstring%'
See this link to a Case Study on Caching:
http://securityevaluators.com/knowledge/case_studies/caching/
Summary, according to the article, only Cache-Control: no-store
works on Chrome, Firefox and IE. IE accepts other controls, but Chrome and Firefox do not. The link is a good read complete with the history of caching and documenting proof of concept.
If someone still needs it (like I do).
The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html
We need to make the current session user a member of the role:
create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;
produces:
Role ROLE created.
Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"
Grant succeeded.
Role SET succeeded.
One line closure, copy, reset:
<?php
$fruits = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
echo (function() use ($fruits) { return reset($fruits); })();
Output:
apple
Alternatively the shorter short arrow function:
echo (fn() => reset($fruits))();
This uses by-value variable binding as above. Both will not mutate the original pointer.
I was having this error w/Citect.
Microsoft Visual C++ 2005 Service Pack 1 Redistributable Package MFC Security Update has the missing files.
I agree with Matti. Would be easy to do with some simple javascript. A quick jquery example would be something like this:
<tr>
<td><a href="http://www.example.com/">example</a></td>
<td>another cell</td>
<td>one more</td>
</tr>
and
$('tr').click( function() {
window.location = $(this).find('a').attr('href');
}).hover( function() {
$(this).toggleClass('hover');
});
then in your CSS
tr.hover {
cursor: pointer;
/* whatever other hover styles you want */
}
Use a keep alive.
On login:
session_start();
$_SESSION['last_action'] = time();
An ajax call every few (eg 20) seconds:
windows.setInterval(keepAliveCall, 20000);
Server side keepalive.php:
session_start();
$_SESSION['last_action'] = time();
On every other action:
session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
// destroy the session and quit
}
1) Ensure you're in branch where you need a copy of the file.
for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master
2) Now checkout specific file alone you want from sub branch into master,
git checkout sub_branch file_path/my_file.ext
here sub_branch
means where you have that file followed by filename you need to copy.
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Just see this page
in cmd type:
Command | clip
Then open a *.Txt
file and Paste
. That's it. Done.
This is probably the best way, since it’s reliable and works on old browsers:
function indexOfMax(arr) {
if (arr.length === 0) {
return -1;
}
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
There’s also this one-liner:
let i = arr.indexOf(Math.max(...arr));
It performs twice as many comparisons as necessary and will throw a RangeError
on large arrays, though. I’d stick to the function.
The PostgreSQL documentation on Character Types is a good reference for this. They are two different names for the same type.
System.out.println(myList.size());
Since no elements are in the list
output => 0
myList.add("newString"); // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());
Since one element is added to the list
output => 1
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
You can use innerHTML
(then parse text from HTML) or use innerText
.
let textContentWithHTMLTags = document.querySelector('div').innerHTML;
let textContent = document.querySelector('div').innerText;
console.log(textContentWithHTMLTags, textContent);
innerHTML
and innerText
is supported by all browser(except FireFox < 44) including IE6.
.spec.ts
file is used for unit testing
of your application.
If you don't to get it generated just use --spec=false
while creating new Component
. Like this
ng generate component --spec=false mycomponentName
You can also check it using jQuery.. It's quite easy:
<html>
<head>
<title>jQuery: Check if Textbox is empty</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
<form name="form1" method="post" action="">
<label for="city">City:</label>
<input type="text" name="city" id="city">
</form>
<button id="check">Check</button>
<script type="text/javascript">
$('#check').click(function () {
if ($('#city').val() == '') {
alert('Empty!!!');
} else {
alert('Contains: ' + $('#city').val());
}
});
</script>
</body>
</html>
This in not a perfect answer but will get much better performance.
SELECT *
FROM (
SELECT *
FROM mytable sample (0.01)
ORDER BY
dbms_random.value
)
WHERE rownum <= 1000
Sample will give you a percent of your actual table, if you really wanted a 1000 rows you would need to adjust that number. More often I just need an arbitrary number of rows anyway so I don't limit my results. On my database with 2 million rows I get 2 seconds vs 60 seconds.
select * from mytable sample (0.01)
The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
And it will execute with /bin/bash.
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
For Windows according to Microsoft docs
Here is the simplest example that has the key lines of code:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
plt.imshow(H, interpolation='none')
plt.show()
both floated divs need to have a width!
set 50% of width to both and it works.
BTW, the outer div, with its margin: 0 auto
will only center itself not the ones inside.
You can get port info via
@Value("${local.server.port}")
private String serverPort;
I know I'm late to the party, but to specifically answer the two questions:
"I just want to disable specific clicky-things so that:
How hard can this be?"
They stop clicking
1. For buttons like <button>
or <input type="button">
you add the attribute: disabled
.
<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>
2. For links, ANY link... actually, any HTML element, you can use CSS3 pointer events.
.selector { pointer-events:none; }
Browser support for pointer events is awesome by today's state of the art (5/12/14). But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events. So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers.
More info about pointer events:
They look disabled
Obviously this a CSS answer, so:
1. For buttons like <button>
or <input type="button">
use the [attribute]
selector:
button[disabled] { ... }
input[type=button][disabled] { ... }
--
Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/
Hope this helps.
Make sure it's not blocked at your settings
http://www.howtogeek.com/howto/16404/how-to-disable-the-new-geolocation-feature-in-google-chrome/
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF
//slightly improved code without using collection framework
package com.test;
public class TestClass {
private static Link last;
private static Link first;
public static void main(String[] args) {
//Inserting
for(int i=0;i<5;i++){
Link.insert(i+5);
}
Link.printList();
//Deleting
Link.deletefromFirst();
Link.printList();
}
protected static class Link {
private int data;
private Link nextlink;
public Link(int d1) {
this.data = d1;
}
public static void insert(int d1) {
Link a = new Link(d1);
a.nextlink = null;
if (first != null) {
last.nextlink = a;
last = a;
} else {
first = a;
last = a;
}
System.out.println("Inserted -:"+d1);
}
public static void deletefromFirst() {
if(null!=first)
{
System.out.println("Deleting -:"+first.data);
first = first.nextlink;
}
else{
System.out.println("No elements in Linked List");
}
}
public static void printList() {
System.out.println("Elements in the list are");
System.out.println("-------------------------");
Link temp = first;
while (temp != null) {
System.out.println(temp.data);
temp = temp.nextlink;
}
}
}
}
An ECMAScript 6 answer that makes use of Symbols:
const a = {value: 1};
a[Symbol.toPrimitive] = function() { return this.value++ };
console.log((a == 1 && a == 2 && a == 3));
Due to ==
usage, JavaScript is supposed to coerce a
into something close to the second operand (1
, 2
, 3
in this case). But before JavaScript tries to figure coercing on its own, it tries to call Symbol.toPrimitive
. If you provide Symbol.toPrimitive
JavaScript would use the value your function returns. If not, JavaScript would call valueOf
.
you can use sorted() method if you want it to return the sorted list. It's more convenient.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
sorted(l1,reverse=True)
list.sort() method modifies the list in-place and returns None.
if you still want to use sort you can do this.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
l1.sort(reverse=True)
print(l1)
It is an abbreviation for 'optional' , used for optional software in some distros.
You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/
Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))
Set the display
property to inline
for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
The following worked for me:
run VBoxManage internalcommands sethduuid "VDI/VMDK file" twice (the first time is just to conveniently generate an UUID, you could use any other UUID generation method instead)
open the .vbox file in a text editor
replace the UUID found in Machine uuid="{...}" with the UUID you got when you ran sethduuid the first time
replace the UUID found in HardDisk uuid="{...}" and in Image uuid="{}" (towards the end) with the UUID you got when you ran sethduuid the second time
To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.
It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER
.
Swift 4.1 introduces new -Osize
optimization mode.
In Swift 4.1 the compiler now supports a new optimization mode which enables dedicated optimizations to reduce code size.
The Swift compiler comes with powerful optimizations. When compiling with -O the compiler tries to transform the code so that it executes with maximum performance. However, this improvement in runtime performance can sometimes come with a tradeoff of increased code size. With the new -Osize optimization mode the user has the choice to compile for minimal code size rather than for maximum speed.
To enable the size optimization mode on the command line, use -Osize instead of -O.
Further reading : https://swift.org/blog/osize/
Here is the code to get the Dimensions of the complete view of the device.
var windowSize = Dimensions.get("window");
Use it like this:
width=windowSize.width,heigth=windowSize.width/0.565
tar -cvzf filename.tar.gz directory_to_compress/
Most tar
commands have a z
option to create a gzip
ed version.
Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,
tar -cvzf filename.bla directory_to_compress/
and then send the filename.bla
- contents will would be a zipped tar, so at the other end it could be retrieved as usual.
You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.
string FormatXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
// Handle and throw if fatal exception here; don't just ignore them
return xml;
}
}
[using statements are ommitted for brevity]
In my case,
word-break: break-all;
worked perfecly, hope it helps any other newcomer like me.
The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.
Here's some really simple code I used to test this (VS2015):
static void Main(string[] args)
{
Func<int, int> incr = a => a + 1;
Console.WriteLine($"P1 = {incr(5)}");
}
What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)
This is the Main function:
IL_001f: stloc.0
IL_0020: ldstr "P1 = {0}"
IL_0025: ldloc.0
IL_0026: ldc.i4.5
IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
IL_002c: box [mscorlib]System.Int32
IL_0031: call string [mscorlib]System.String::Format(string, object)
IL_0036: call void [mscorlib]System.Console::WriteLine(string)
IL_003b: ret
See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.
And here's the function called:
.method assembly hidebysig
instance int32 '<Main>b__0_0' (
int32 a
) cil managed
{
// Method begins at RVA 0x20ac
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
} // end of method '<>c'::'<Main>b__0_0'
It's a really short function, but it is a function.
Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.
In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.
"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth
"A program that doesn't run correctly doesn't need to run fast" -- Me
i use "Versions", quite easy, but not free .
This answer is useful to them who want click to chat whatsapp in website to redirect web.whatsapp.com with default content or message and in mobile device to open in whatsapp in mobile app with default content to text bar in app.
also add jquery link.
<a target="_blank" title="Contact Us On WhatsApp" href="https://web.whatsapp.com/send?phone=+91xxxxxxxxx&text=Hi, I would like to get more information.." class="whatsapplink hidemobile" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
Contact Us On WhatsApp </span>
</a>
<a target="_blank" title="Contact Us On WhatsApp" href="https://api.whatsapp.com/send?phone=+91xxxxxxxxx&text=Hi,%20I%20would%20like%20to%20get%20more%20information.." class="whatsapplink hideweb" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
Contact Us On WhatsApp </span>
</a>
<script type="text/javascript">
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
$('.hidemobile').css('display', 'none'); // OR you can use $('.hidemobile').hide();
}
else
{
$('.hideweb').css('display', 'none'); // OR you can use $('.hideweb').hide();
}
</script>
If you want to add SSL in your test environment, then you can use mkcert
. Below I mentioned the GitHub URL.
https://github.com/FiloSottile/mkcert
And also below I mentioned sample nginx configuration for reverse proxy.
server {
listen 80;
server_name test.local;
return 301 https://test.local$request_uri;
}
server {
listen 443 ssl;
server_name test.local;
ssl_certificate /etc/nginx/ssl/test.local.pem;
ssl_certificate_key /etc/nginx/ssl/test.local-key.pem;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Client-Verify SUCCESS;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://localhost:3000;
proxy_redirect off;
proxy_buffering off;
}
}
For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour
public static void LimpiarArchivosViejos()
{
DayOfWeek today = DateTime.Today.DayOfWeek;
int hora = DateTime.Now.Hour;
if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
{
CleanPdfOlds();
CleanExcelsOlds();
}
}
private static void CleanPdfOlds(){
string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(-7))
fi.Delete();
}
}
private static void CleanExcelsOlds()
{
string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
foreach (string file in files2)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(-7))
fi.Delete();
}
}
Because I fall for it, I would like to drop a note. I found this thread, because I have to rewrite an old sh script to be POSIX compatible. This basically means to circumvent the pipe/subshell problem introduced by POSIX by rewriting code like this:
some_command | read a b c
into:
read a b c << EOF
$(some_command)
EOF
And code like this:
some_command |
while read a b c; do
# something
done
into:
while read a b c; do
# something
done << EOF
$(some_command)
EOF
But the latter does not behave the same on empty input. With the old notation the while loop is not entered on empty input, but in POSIX notation it is! I think it's due to the newline before EOF, which cannot be ommitted. The POSIX code which behaves more like the old notation looks like this:
while read a b c; do
case $a in ("") break; esac
# something
done << EOF
$(some_command)
EOF
In most cases this should be good enough. But unfortunately this still behaves not exactly like the old notation if some_command prints an empty line. In the old notation the while body is executed and in POSIX notation we break in front of the body.
An approach to fix this might look like this:
while read a b c; do
case $a in ("something_guaranteed_not_to_be_printed_by_some_command") break; esac
# something
done << EOF
$(some_command)
echo "something_guaranteed_not_to_be_printed_by_some_command"
EOF
Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);
.
This might help you.
<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>
<script>
function save(){
$('#myinput').val('1');
$('#form').submit();
}
</script>
After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:
yourUIButton.backgroundColor = UIColor.blue
You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com
ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.
I hope this helps with the dynamic website you have got.
Sub multiplechrome()
Dim WebUrl As String
Dim i As Integer
For i = 1 To ActiveSheet.Cells(1, 2).Value
WebUrl = "http://" & Cells(i, 1).Value & """"
Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)
Next
End Sub
Make your toolbar like:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/menuToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:background="@color/white"
android:contentInsetLeft="10dp"
android:contentInsetRight="10dp"
android:contentInsetStart="10dp"
android:minHeight="?attr/actionBarSize"
android:padding="0dp"
app:contentInsetLeft="10dp"
app:contentInsetRight="10dp"
app:contentInsetStart="10dp"></android.support.v7.widget.Toolbar>
You need to add
contentInset
attribute to add spacing
please follow this link for more - Android Tips
In PHP DateTime (PHP >= 5.3)
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->getTimestamp();
If you want to insert NULL
only when the value
is empty
or ''
, but insert the value
when it is available.
A) Receives the form data using POST method, and calls function insert with those values.
insert( $_POST['productId'], // Will be set to NULL if empty
$_POST['productName'] ); // Will be to NULL if empty
B) Evaluates if a field was not filled up by the user, and inserts NULL
if that's the case.
public function insert( $productId, $productName )
{
$sql = "INSERT INTO products ( productId, productName )
VALUES ( :productId, :productName )";
//IMPORTANT: Repace $db with your PDO instance
$query = $db->prepare($sql);
//Works with INT, FLOAT, ETC.
$query->bindValue(':productId', !empty($productId) ? $productId : NULL, PDO::PARAM_INT);
//Works with strings.
$query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);
$query->execute();
}
For instance, if the user doesn't input anything on the productName
field of the form, then $productName
will be SET
but EMPTY
. So, you need check if it is empty()
, and if it is, then insert NULL
.
Tested on PHP 5.5.17
Good luck,
I've had the same error parsing a string containing \n
into JSON. The solution was to use string.replace('\n','\\n')
If you are using gradle. You can apply 'aplication' plugin and use the following command
applicationDefaultJvmArgs = [
"-Dlog4j.configurationFile=your.xml",
]
Code to detect the operating system of an user
let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
This worked for me: :)
ALTER TABLE your_table_name ADD COLUMN new_column_name int;
In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):
$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );
Found different way using HTML5 localstorage, I've create a library with events like API:
sysend.on('foo', function(message) {
console.log(message);
});
var input = document.getElementsByTagName('input')[0];
document.getElementsByTagName('button')[0].onclick = function() {
sysend.broadcast('foo', {message: input.value});
};
it will send messages to all other pages but not for current one.
This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document.
Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc.
I tried commenting as much as possible throughout the code so you could understand what each part is doing.
This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can’t do something with it.
Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders.
This example code will get all the files and create a list in a text document and place that text document in Folder1.
Caution: you shouldn’t save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main(string[] args)
{
// Create a header for your text file
string[] HeaderA = { "****** List of Files ******" };
System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);
// Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
// named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
{
//Now that we have a list of files, write them to a text file.
WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
}
// Now, append the header and list to the text file.
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
{
// First - call the header
foreach (string line in HeaderA)
{
file.WriteLine(line);
}
file.WriteLine(); // This line just puts a blank space between the header and list of files.
// Now, call teh list of files.
foreach (string name in arrayA)
{
file.WriteLine(name);
}
}
}
// These are just the "throw new exception" calls that are needed when converting the array's to strings.
// This one is for the Header.
private static void WriteAllLines(string v, string file)
{
//throw new NotImplementedException();
}
// And this one is for the list of files.
private static void WriteAllLines(string v, string[] arrayA)
{
//throw new NotImplementedException();
}
}
}
i guess you mean System Programs and Application programs
System Programs makes the hardware run , Applications are for specific tasks
an Example for System Programs are Device Drivers
as for the Applications you can say web browsers , word porcessros etc
For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.
Next, check that your current module is the correct renamed module and not the old one.
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
I'm not really sure of the syntax {el => this.inputEntry = el}, but when clearing an input field you assign a ref like you mentioned.
<input type="text" ref="someName" />
Then in the onClick function after you've finished using the input value, just use...
this.refs.someName.value = '';
Edit
Actually the {el => this.inputEntry = el} is the same as this I believe. Maybe someone can correct me. The value for el must be getting passed in from somewhere, to act as the reference.
function (el) {
this.inputEntry = el;
}
If destination file is read only use /y/r
xcopy /y/r source.txt dest.txt
Maybe I misunderstood your question, but wouldn't it be simpler if you copy/move the files from A to the git repo B and add the needed ones with git add?
UPDATE: From the git doc:
Cloning into an existing directory is only allowed if the directory is empty.
check http://jsfiddle.net/Z22NU/12/
function fnselect(){
alert($("tr.selected td:first" ).html());
}
That's because your first code snippet is not performing initialization, but assignment:
char myarray[4] = "abc"; // Initialization.
myarray = "abc"; // Assignment.
And arrays are not directly assignable in C.
The name myarray
actually resolves to the address of its first element (&myarray[0]
), which is not an lvalue, and as such cannot be the target of an assignment.
Although @CommonsWare's solution works, it can't be used e. g. in a layer-list
drawable. The options combining <rotate>
and <shape>
cause the problems with size. Here is a solution using the Android Vector Drawable. This Drawable is a 1x10dp white line (can be adjusted by modifying the width
, height
and strokeColor
properties):
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:viewportWidth="1"
android:viewportHeight="10"
android:width="1dp"
android:height="10dp">
<path
android:strokeColor="#FFFFFF"
android:strokeWidth="1"
android:pathData="M0.5,0 V10" />
</vector>
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
del array[0]
where 0
is the index of the object in the list (there is no array in python)
According to the HTML5 Spec:
A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)
A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top." - Source
That means that there is no such keyword as _new
in HTML5, and not in HTML4 (and consequently XHTML) either. That means, that there will be no consistent behavior whatsoever if you use this as a value for the target attribute.
As Daniel and Michael have pointed out in the comments, when using target _blank
pointing to an untrusted website, you should, in addition, set rel="noopener"
. This prevents the opening site to mess with the opener via JavaScript. See this post for more information.
Make sudo run a shell, like this:
sudo sh -c "echo foo > ~root/out"
This is a shameless plug, but I'm just now writing some extensive Javadoc for JSch.
Also, there is now a Manual in the JSch Wiki (written mainly by me).
About the original question, there is not really an example for handling the streams. Reading/writing a stream is done as always.
But there simply can't be a sure way to know when one command in a shell has finished just from reading the shell's output (this is independent of the SSH protocol).
If the shell is interactive, i.e. it has a terminal attached, it will usually print a prompt, which you could try to recognize. But at least theoretically this prompt string could also occur in normal output from a command. If you want to be sure, open individual exec
channels for each command instead of using a shell channel. The shell channel is mainly used for interactive use by a human user, I think.
If any cell in a row contains the searched phrase or word, this function shows that row otherwise hides it.
<input type="text" class="search-table"/>
$(document).on("keyup",".search-table", function () {
var value = $(this).val();
$("table tr").each(function (index) {
$row = $(this);
$row.show();
if (index !== 0 && value) {
var found = false;
$row.find("td").each(function () {
var cell = $(this).text();
if (cell.indexOf(value.toLowerCase()) >= 0) {
found = true;
return;
}
});
if (found === true) {
$row.show();
}
else {
$row.hide();
}
}
});
});
This question is pretty old but I'll add the solution I found the be the simplest at present.
library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after
Changing the port in Device Manager works for me. I was also able to fix it by finding the port that Arduino was using and then select it from the Adruion IDE from tools menu Tools>Port>Com Port
Use this
$('body').on('change', '#id', function() {
// Action goes here.
});
If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:
import socket
from contextlib import closing
def check_socket(host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
if sock.connect_ex((host, port)) == 0:
print "Port is open"
else:
print "Port is not open"
Numeral.js is a library I created that can can format numbers, currency, percentages and has support for localization.
numeral(0.7523).format('0%') // returns string "75%"
I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
'update to the cell that contains HTML you want converted
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
'update to cell you want converted HTML pasted in
.Quit
End With
End Sub
Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.
At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.
In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.
Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.
Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.
In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).
Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.
Just subtract a number:
> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"
Since the Date
class only has days, you can just do basic arithmetic on it.
If you want to use POSIXlt for some reason, then you can use it's slots:
> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
Here's a lazy one-liner, also using itertools:
from itertools import compress, product
def combinations(items):
return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) )
# alternative: ...in product([0,1], repeat=len(items)) )
Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a "1".
items=abc * mask=###
|
V
000 ->
001 -> c
010 -> b
011 -> bc
100 -> a
101 -> a c
110 -> ab
111 -> abc
Things to consider:
len(...)
on items
(workaround: if items
is something like an iterable like a generator, turn it into a list first with items=list(_itemsArg)
)items
is not random (workaround: don't be insane){2,2,1}
and {2,1,1}
will both collapse to {2,1}
(workaround: use collections.Counter
as a drop-in replacement for set
; it's basically a multiset... though you may need to later use tuple(sorted(Counter(...).elements()))
if you need it to be hashable)Demo
>>> list(combinations(range(4)))
[set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}]
>>> list(combinations('abcd'))
[set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}]
I know I am late in answering this question, but this helped me:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:background="@color/fb" >
<Button
android:id="@+id/fbLogin"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null"
android:drawableLeft="@drawable/ic_facebook"
android:gravity="center"
android:minHeight="0dp"
android:minWidth="0dp"
android:text="FACEBOOK"
android:textColor="@android:color/white" />
</FrameLayout>
I found this solution from here: Android UI struggles: making a button with centered text and icon
I was looking for exactly the same thing when I found teqhtml. It does the conversion of $ and $$ equations to images with the nice bonus of aligning the resulting image vertically with the surrounding text. Not a lot of doc but it's quite straightforward.
Hope it helps some future readers.
You can try adding a question mark as below. This worked for me.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
Add a stopping value to the array:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange", ""};
for( unsigned int a = 0; texts[a].length(); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
It may be the typo if you incorrectly wrote the placeholder
word.
In my case I misspelled it as placehoder
and got the error like this:
AttributeError: 'module' object has no attribute 'placehoder'
I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:
\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}
The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.
Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).
The example they provide:
def clock():
while True:
print(datetime.now().strftime("%H:%M:%S"), end="\r")
For printing the on the same line, as others have suggested, just use end=""
302 is a response indicating change of resource location - "Found".
The url where the resource should be now located should be in the response 'Location' header.
The "jump" should be done by the requesting client (make a new request to the resource url in the response Location header field).
String to JSON using Jackson
with com.fasterxml.jackson.databind
:
Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
I think this will be helpful.
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationVariants.all { variant ->
variant.outputs.each { output ->
project.ext { appName = 'MyAppName' }
def formattedDate = new Date().format('yyyyMMddHHmmss')
def newName = output.outputFile.name
newName = newName.replace("app-", "$project.ext.appName-")
newName = newName.replace("-release", "-release" + formattedDate)
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
}
productFlavors {
flavor1 {
}
flavor2 {
proguardFile 'flavor2-rules.pro'
}
}
The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.
This is considered as features in Gitlab.
Maintainer / Owner
access is never able to force push again for default & protected branch, as stated in this docs
Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo
, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby
in 2020.
Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.
First of all, move all your PHP code to the top. Without it, my code below wont work.
To do the redirect, use:
header('Location: http://www.example.com/');
Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.
Here you can find useful links to free books: https://stackoverflow.com/tags/php/info
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
You can use a separate class to represent the JSON object and use @SerializedName
annotations to specify the field name to grab for each data member:
public class Response {
@SerializedName("data")
private Data data;
private static class Data {
@SerializedName("translations")
public Translation[] translations;
}
private static class Translation {
@SerializedName("translatedText")
public String translatedText;
}
public String getTranslatedText() {
return data.translations[0].translatedText;
}
}
Then you can do the parsing in your parse() method using a Gson
object:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
System.out.println("Translated text: " + response.getTranslatedText());
With this approach, you can reuse the Response
class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.
here you go Sir :-)
1
.myElement{
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
2
.myElement{
text-shadow: rgba(0,0,0,.01) 0 0 1px;
}
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
in my case, the file
command tells a wrong encoding, so i tried converting with all the possible encodings, and found out the right one.
execute this script and check the result file.
for i in `iconv -l`
do
echo $i
iconv -f $i -t UTF-8 yourfile | grep "hint to tell converted success or not"
done &>/tmp/converted
How to parse parameters without an external dependency. Great question! You may be interested in picocli.
Picocli is specifically designed to solve the problem asked in the question: it is a command line parsing framework in a single file, so you can include it in source form. This lets users run picocli-based applications without requiring picocli as an external dependency.
It works by annotating fields so you write very little code. Quick summary:
<command> -xvfInputFile
as well as <command> -x -v -f InputFile
)"1..*"
, "3..5"
The usage help message is easy to customize with annotations (without programming). For example:
(source)
I couldn't resist adding one more screenshot to show what kind of usage help messages are possible. Usage help is the face of your application, so be creative and have fun!
Disclaimer: I created picocli. Feedback or questions very welcome. It is written in java, but let me know if there is any issue using it in scala and I'll try to address it.
this is very basic method to send plain text email using mail function.
<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);
ecatmur's solution will work fine. This will be better performance on large datasets, though:
data.groupby(data['date'].map(lambda x: x.year))
Any data storage for application generally uses the database. It could be relational database or no sql databases which are currently trending.
Data warehouse is also database. We can call data warehouse database as specialized data storage for the analytical reporting purposes for the company. This data used for key business decision.
The organized data helps is reporting and taking business decision effectively.
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
Actually, there are four forms of this operator:
<>
!=
^=
and even
¬= -- worked on some obscure platforms in the dark ages
which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).
With Linq
var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);
Without Linq
li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort
Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like
li = li.OrderBy(i => i).ToList();
Through Configuration, you can do this:
Model1
{
int fk_one,
int fk_two
}
Model2
{
int pk_one,
int pk_two,
}
then in the context config
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model1>()
.HasRequired(e => e.Model2)
.WithMany(e => e.Model1s)
.HasForeignKey(e => new { e.fk_one, e.fk_two })
.WillCascadeOnDelete(false);
}
}
will I get the same results?
Not really. I don't know of a workaround for PHP 5.2, though.
What is the difference between
new self
andnew static
?
self
refers to the same class in which the new
keyword is actually written.
static
, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.
In the following example, B
inherits both methods from A
. The self
invocation is bound to A
because it's defined in A
's implementation of the first method, whereas static
is bound to the called class (also see get_called_class()
).
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
The interesting thing about mb_detect_encoding
and mb_convert_encoding
is that the order of the encodings you suggest does matter:
// $input is actually UTF-8
mb_detect_encoding($input, "UTF-8", "ISO-8859-9, UTF-8");
// ISO-8859-9 (WRONG!)
mb_detect_encoding($input, "UTF-8", "UTF-8, ISO-8859-9");
// UTF-8 (OK)
So you might want to use a specific order when specifying expected encodings. Still, keep in mind that this is not foolproof.
There are services available which allow you to artificially create origin timeouts by calling an API where you specify how long the server will take to respond. Server Timeout on macgyver is an example of such a service.
For example if you wanted to test a request that takes 15 seconds to respond you would simply make a post request to the macgyver API.
JSON Payload:
{
"timeout_length": 15000
}
API Response (After 15 seconds):
{
"response": "ok"
}
Server Timeout program on macgyver
https://askmacgyver.com/explore/program/server-timeout/3U4s6g6u
$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.
When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.
<div ng-view></div>
$routeProvider
.when('/contact/', {
templateUrl: 'app/views/core/contact/contact.html',
controller: 'ContactCtrl'
});
<div ui-view>
<div ui-view='abc'></div>
<div ui-view='abc'></div>
</div>
$stateProvider
.state("contact", {
url: "/contact/",
templateUrl: '/app/Aisel/Contact/views/contact.html',
controller: 'ContactCtrl'
});
I guess ssh
is the best secured way for this, for example :
ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"
where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.
Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain
if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config
. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.
Some extra docs over the source project main pages :
ssh and ssh-agent
man ssh
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
Being specific about this keeps you away from the whole TRUE in VB is -1 and in other langauges true is just NON ZERO. Keeping the boolean field as true or false keeps java outside of this argument.
If you know they are strings, then there's no need to check for type.
"a" == "b"
However, note that string objects will not be equal.
new String("a") == new String("a")
will return false.
Call the valueOf() method to convert it to a primitive for String objects,
new String("a").valueOf() == new String("a").valueOf()
will return true
The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch
By adding #ifdef HAVE_CAMV4L
around
#include <linux/videodev.h>
in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp
and removing || defined (HAVE_CAMV4L2)
from line 174
allowed me to compile.
I just wasted my time on this and wanted to add an additional case where this error presents itself.
SQL Error (1292): Truncated incorrect DOUBLE value: 'N0003'
Test data
CREATE TABLE `table1 ` (
`value1` VARCHAR(50) NOT NULL
);
INSERT INTO table1 (value1) VALUES ('N0003');
CREATE TABLE `table2 ` (
`value2` VARCHAR(50) NOT NULL
);
INSERT INTO table2 (value2)
SELECT value1
FROM table1
WHERE 1
ORDER BY value1+0
The problem is ORDER BY value1+0
- type casting.
I know that it does not answer the question but this is the first result on Google for this error and it should have other examples where this error presents itself.
The reason of this problem when input field value is undefined then throw the warning from react. If you create one changeHandler for multiple input field and you want to change state with changeHandler then you need to assign previous value using by spread operator. As like my code here.
constructor(props){
super(props)
this.state = {
user:{
email:'',
password:''
}
}
}
// This handler work for every input field
changeHandler = event=>{
// Dynamically Update State when change input value
this.setState({
user:{
...this.state.user,
[event.target.name]:event.target.value
}
})
}
submitHandler = event=>{
event.preventDefault()
// Your Code Here...
}
render(){
return (
<div className="mt-5">
<form onSubmit={this.submitHandler}>
<input type="text" value={this.state.user.email} name="email" onChage={this.changeHandler} />
<input type="password" value={this.state.user.password} name="password" onChage={this.changeHandler} />
<button type="submit">Login</button>
</form>
</div>
)
}
Abstract your initialization into a method, and call the method from mounted
and wherever else you want.
new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})
Then possibly have a button in your template to start over.
<button v-if="playerWon" @click="init">Play Again</button>
In this button, playerWon
represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init
.
After insertion code,
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
If you want to catch the focus event dynamiclly on every input on your component :
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Checkout the full code here : https://stackblitz.com/edit/angular-93jdir
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list
will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.
That said, It's often unavoidable and the functions that do this are:
for 2-D arrays:
for 3-D arrays (the above plus):
for N-D arrays:
No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)
Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not that hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.
This should do the trick for you.
For one word:
if (!string.Contains("One"))
For two words:
if (!(string.Contains("One") && string.Contains("Two")))
In some tests here, it worked perfectly this way:
Decimal.Round(value, 2);
Hope this helps
After some searching I found this on a Google groups discussion:
docker currently inhibits this capability for enhanced safety.
That is because the ulimit settings of the host system apply to the docker container. It is regarded as a security risk that programs running in a container can change the ulimit settings for the host.
The good news is that you have two different solutions to choose from.
sys_resource
from lxc_template.go
and recompile docker. Then
you'll be able to set the ulimit as high as you like.or
I applied the second method:
sudo service docker stop;
changed the limits in /etc/security/limits.conf
reboot the machine
run my container
run ulimit -a
in the container to confirm the open files limit has been inherited.
See: https://groups.google.com/forum/#!searchin/docker-user/limits/docker-user/T45Kc9vD804/v8J_N4gLbacJ
I prefer to have the server return the date without modification, and have javascript do the view massaging. My API returns "MM/DD/YYYY hh:mm:ss" from SQL Server.
Resource
angular.module('myApp').factory('myResource',
function($resource) {
return $resource('api/myRestEndpoint/', null,
{
'GET': { method: 'GET' },
'QUERY': { method: 'GET', isArray: true },
'POST': { method: 'POST' },
'PUT': { method: 'PUT' },
'DELETE': { method: 'DELETE' }
});
}
);
Controller
var getHttpJson = function () {
return myResource.GET().$promise.then(
function (response) {
if (response.myDateExample) {
response.myDateExample = $filter('date')(new Date(response.myDateExample), 'M/d/yyyy');
};
$scope.myModel= response;
},
function (response) {
console.log(response.data);
}
);
};
myDate Validation Directive
angular.module('myApp').directive('myDate',
function($window) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var moment = $window.moment;
var acceptableFormats = ['M/D/YYYY', 'M-D-YYYY'];
function isDate(value) {
var m = moment(value, acceptableFormats, true);
var isValid = m.isValid();
//console.log(value);
//console.log(isValid);
return isValid;
};
ngModel.$parsers.push(function(value) {
if (!value || value.length === 0) {
return value;
};
if (isDate(value)) {
ngModel.$setValidity('myDate', true);
} else {
ngModel.$setValidity('myDate', false);
}
return value;
});
}
}
}
);
HTML
<div class="form-group">
<label for="myDateExample">My Date Example</label>
<input id="myDateExample"
name="myDateExample"
class="form-control"
required=""
my-date
maxlength="50"
ng-model="myModel.myDateExample"
type="text" />
<div ng-messages="myForm.myDateExample.$error" ng-if="myForm.$submitted || myForm.myDateExample.$touched" class="errors">
<div ng-messages-include="template/validation/messages.html"></div>
</div>
</div>
template/validation/messages.html
<div ng-message="required">Required Field</div>
<div ng-message="number">Must be a number</div>
<div ng-message="email">Must be a valid email address</div>
<div ng-message="minlength">The data entered is too short</div>
<div ng-message="maxlength">The data entered is too long</div>
<div ng-message="myDate">Must be a valid date</div>
In modern JS you can simply use async
/await
, like:
async function upload() {
return new Promise((resolve, reject) => {
$.ajax({
url: $(this).attr('href'),
type: 'GET',
timeout: 30000,
success: (response) => {
resolve(response);
},
error: (response) => {
reject(response);
}
})
})
}
Then call it in an async
function like:
let response = await upload();
If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)
CREATE EXTENSION "uuid-ossp";
ERROR: extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
CREATE EXTENSION "uuid-ossp";
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------------------+------------------+---------------------------+--------
public | uuid_generate_v1 | uuid | | normal
public | uuid_generate_v1mc | uuid | | normal
public | uuid_generate_v3 | uuid | namespace uuid, name text | normal
public | uuid_generate_v4 | uuid | | normal
db=# select uuid_generate_v4();
uuid_generate_v4
--------------------------------------
b19d597c-8f54-41ba-ba73-02299c1adf92
(1 row)
What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.
Use hidden
.
<select>_x000D_
<option hidden>Choose</option>_x000D_
<option>Item 1</option>_x000D_
<option>Item 2</option>_x000D_
</select>
_x000D_
This doesn't unset it but you can however hide it in the options while it's displayed by default.
Managing Java versions on Mac OSX is a nightmare. I recently switched over to using JDK 1.7, deleting JDK 6 from my MacBook entirely (I also had traces of JDK 5 - this laptop has been updated a few times).
Here's what I did to move to JDK 7.
1) download the latest from Oracle (http://www.oracle.com/technetwork/java/javase/downloads/index.html) and install it.
2) Remove (using rm - if you've got backups, you can revert if you make a mistake) all the JDK6 and JRE6 files.
At this stage, you should see:
% ls /Library/Java/JavaVirtualMachines/
jdk1.7.0_nn.jdk
(and nothing else)
3) In the folder /Library/Java/Extensions/, you'll need to remove all the old jar files, the ones that correspond to other releases of Java. If you don't, you'll get the infamous message about the wrong version of tools.jar (see Builds failing after upgrading to Java7, Missing Tools.jar and bad class versions). It is not enough to rename the jar files, because Java will open every jar in that folder - I moved mine into a sub-directory. It's safe to remove them once you know everything else works.
I haven't found I need to set JAVA_HOME for simple things.
Note: I just tried running IntelliJ and it will not start unless you have Apple's JDK 6 installed (see http://youtrack.jetbrains.com/issue/IDEA-93710). Same is true for Eclipse. Netbeans works fine.
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
For some reason no one mentioned git-tree
. See https://stackoverflow.com/a/424142/1657819
git-tree
is preferred because it's a plumbing command; meant to be programmatic (and, presumably, faster)
(assuming base branch is master
)
git diff-tree --no-commit-id --name-only -r master..branch-name
However this will show you all files which were affected in the branch, if you want to see explicitly modified files only, you can use --diff-filter
:
git diff-tree --no-commit-id --name-only -r master..branch-name --diff-filter=M
Also one can use --name-status
instead of --name-only
to see the status of the files (A
/M
/D
and so on)
In IE you have to use attachEvent
rather than the standard addEventListener
.
A common practice is to check if the addEventListener
method is available and use it, otherwise use attachEvent
:
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
You can make a function to do it:
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
alert('element clicked');
});
You can run an example of the above code here.
The third argument of addEventListener
is useCapture
; if true, it indicates that the user wishes to initiate event capturing.
GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.
A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
Private Sub CommandButton1_Click()
Dim Data As Object, Employee As Object
Application.ScreenUpdating = False
Set Data = ThisWorkbook.Sheets("Data")
Set Employee = ThisWorkbook.Sheets("Employee Names")
Data.Range("AK1").Value = "Lookup"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"
Application.DisplayAlerts = False
Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
Data.Range("AK:AK").Delete
Data.AutoFilterMode = False
'Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"
Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")
Dr.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
'DrfeeRequested.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")
Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")
Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"
Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")
Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
TodayDT = Format(Now())
Weekdy = Weekday(Now())
If Weekdy = 2 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 3 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 4 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 5 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 6 Then
LastTwoDays = Now() - Weekday(Now(), 3)
Else
MsgBox "Today Satuarday OR Sunday Data is not Available"
End If
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"
Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")
Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"
Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")
Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.Range("A1").AutoFilter
End Sub
Private Sub CommandButton2_Click()
Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear
MsgBox "Please paste new data in data sheet"
End Sub
clrscr
is not standard C function. According to internet, it used to be a thing in old Borland C.
Is clrscr(); a function in C++?
// Require body-parser (to receive post data from clients)
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
If you want to delete the table from the schema perform below operation --
rails db:rollback
Steps for Using Group by,Having By and Order by...
Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.
It seems you require the following plugin: https://github.com/yearofmoo/AngularJS-Scope.onReady
It basically gives you the functionality to run your directive code after the your scope or data is loaded i.e. $scope.$whenReady
In your service, add the following code.
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.
The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.
Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <
, &
and "
, which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including "
and \
).
Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.
So, I guess you just could decide which to use like this:
Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.
Otherwise, use the numeric escape sequences.
Try connecting without any password:
mysql -u root
I believe the initial default is no password for the root account (which should obviously be changed as soon as possible).
$(document).ready(function(){_x000D_
$(".chk").click(function(){_x000D_
var d = $("input[name=test]"); if(d.is(":checked")){_x000D_
//_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="test"> `test1`_x000D_
<input type="checkbox" name="test"> `test2`_x000D_
<input type="checkbox" name="test"> `test3`_x000D_
<input type="button" value="check" class='chk'/>
_x000D_
Try doing this. Works for IE8, FF3.6, Chrome
<body>
<table>
<tr>
<td>
<div style="word-wrap: break-word; width: 100px">gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div>
</td>
</tr>
</table>
</body>
I don't know if this helps but I just installed Server 2008 Express and was disappointed when I couldn't find the query analyzer but I was able to use the command line 'sqlcmd' to access my server. It is a pain to use but it works. You can write your code in a text file then import it using the sqlcmd command. You also have to end your query with a new line and type the word 'go'.
Example of query file named test.sql:
use master;
select name, crdate from sysdatabases where xtype='u' order by crdate desc;
go
Example of sqlcmd:
sqlcmd -S %computername%\RLH -d play -i "test.sql" -o outfile.sql & notepad outfile.sql
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
You can convert most of the columns by just calling convert_objects
:
In [36]:
df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date object
WD int64
Manpower float64
2nd object
CTR object
2ndU float64
T1 int64
T2 int64
T3 int64
T4 float64
dtype: object
For column '2nd' and 'CTR' we can call the vectorised str
methods to replace the thousands separator and remove the '%' sign and then astype
to convert:
In [39]:
df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date object
WD int64
Manpower float64
2nd int32
CTR float64
2ndU float64
T1 int64
T2 int64
T3 int64
T4 object
dtype: object
In [40]:
df.head()
Out[40]:
Date WD Manpower 2nd CTR 2ndU T1 T2 T3 T4
0 2013/4/6 6 NaN 2645 5.27 0.29 407 533 454 368
1 2013/4/7 7 NaN 2118 5.89 0.31 257 659 583 369
2 2013/4/13 6 NaN 2470 5.38 0.29 354 531 473 383
3 2013/4/14 7 NaN 2033 6.77 0.37 396 748 681 458
4 2013/4/20 6 NaN 2690 5.38 0.29 361 528 541 381
Or you can do the string handling operations above without the call to astype
and then call convert_objects
to convert everything in one go.
UPDATE
Since version 0.17.0
convert_objects
is deprecated and there isn't a top-level function to do this so you need to do:
df.apply(lambda col:pd.to_numeric(col, errors='coerce'))
See the docs and this related question: pandas: to_numeric for multiple columns
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Gearplay
{
/// <summary>
/// ?????? ?????????????? ??? OpenFolderBrows.xaml
/// </summary>
public partial class OpenFolderBrows : Page
{
internal string SelectedFolderPath { get; set; }
public OpenFolderBrows()
{
InitializeComponent();
Selectedpath();
InputLogicalPathCollection();
}
internal void Selectedpath()
{
Browser.Navigate(@"C:\");
Browser.Navigated += Browser_Navigated;
}
private void Browser_Navigated(object sender, NavigationEventArgs e)
{
SelectedFolderPath = e.Uri.AbsolutePath.ToString();
//MessageBox.Show(SelectedFolderPath);
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
}
string [] testing { get; set; }
private void InputLogicalPathCollection()
{ // add Menu items for Cotrol
string[] DirectoryCollection_Path = Environment.GetLogicalDrives(); // Get Local Drives
testing = new string[DirectoryCollection_Path.Length];
//MessageBox.Show(DirectoryCollection_Path[0].ToString());
MenuItem[] menuItems = new MenuItem[DirectoryCollection_Path.Length]; // Create Empty Collection
for(int i=0;i<menuItems.Length;i++)
{
// Create collection depend how much logical drives
menuItems[i] = new MenuItem();
menuItems[i].Header = DirectoryCollection_Path[i];
menuItems[i].Name = DirectoryCollection_Path[i].Substring(0,DirectoryCollection_Path.Length-1);
DirectoryCollection.Items.Add(menuItems[i]);
menuItems[i].Click += OpenFolderBrows_Click;
testing[i]= DirectoryCollection_Path[i].Substring(0, DirectoryCollection_Path.Length - 1);
}
}
private void OpenFolderBrows_Click(object sender, RoutedEventArgs e)
{
foreach (string str in testing)
{
if (e.OriginalSource.ToString().Contains("Header:"+str)) // Navigate to Local drive
{
Browser.Navigate(str + @":\");
}
}
}
private void Goback_Click(object sender, RoutedEventArgs e)
{// Go Back
try
{
Browser.GoBack();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Goforward_Click(object sender, RoutedEventArgs e)
{ //Go Forward
try
{
Browser.GoForward();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FolderForSave_Click(object sender, RoutedEventArgs e)
{
// Separate Click For Go Back same As Close App With send string var to Main Window ( Main class etc.)
this.NavigationService.GoBack();
}
}
}
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
For me, using EF6 and Visual Studio 2015 I entered query
in the immediate window and it gave me the generated SQL Statement
I had the same question. I have tried all solutions provided above and none of them worked... But I have found a solution that works for me, and hopefully for others too.
<center>
![your image caption](image.png)
</center>
This code will center both the image and the caption. It is essential that you leave lines between <center>
, the image code, and </center>
, otherwise the image will be centered but the caption will disappear.
If you want your image to have a clickable link, you can embed things like
[![your image caption](image.png)](www.link_to_image.com)
However, the caption will no longer appear.
So if you want a clickable caption you will have to do it in two steps:
<center>
![](image.png)
[your image caption](www.link_to_image.com)
</center>
Same here, make sure there are empty lines in between each command ones. If you want both the image and the caption to be clickable, then combine the middle and the last codes above. I hope this helps a bit.
Change color values in the array
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(Color.parseColor("#008000"),
Color.parseColor("#ADFF2F"))
);
gradientDrawable.cornerRadius = 0f;
//Set Gradient
linearLayout.setBackground(gradientDrawable);
Result
Try quitting Visual Studio, delete the relevant pubxml.user file in your PublishProfiles directory, restart VS and publish. Worked on VS 2019.
GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.
In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
It is working for me in Win7 64 bit.
SaaS: Software as a Service Cloud application services or “Software as a Service” (SaaS) are probably the most popular form of cloud computing and are easy to use. SaaS uses the Web to deliver applications that are managed by a third-party vendor and whose interface is accessed on the clients’ side. Most SaaS applications can be run directly from a Web browser, without any downloads or installations required. SaaS eliminates the need to install and run applications on individual computers. With SaaS, it’s easy for enterprises to streamline their maintenance and support, because everything can be managed by vendors: applications, runtime, data, middleware, O/S, virtualization, servers, storage, and networking. Gmail is one famous example of an SaaS mail provider.
PaaS: Platform as a Service The most complex of the three, cloud platform services or “Platform as a Service” (PaaS) deliver computational resources through a platform. What developers gain with PaaS is a framework they can build upon to develop or customize applications. PaaS makes the development, testing, and deployment of applications quick, simple, and cost-effective, eliminating the need to buy the underlying layers of hardware and software. One comparison between SaaS vs. PaaS has to do with what aspects must be managed by users, rather than providers: With PaaS, vendors still manage runtime, middleware, O/S, virtualization, servers, storage, and networking, but users manage applications and data.
IaaS: Infrastructure as a Service Cloud infrastructure services, known as “Infrastructure as a Service” (IaaS), deliver computer infrastructure (such as a platform virtualization environment), storage, and networking. Instead of having to purchase software, servers, or network equipment, users can buy these as a fully outsourced service that is usually billed according to the amount of resources consumed. Basically, in exchange for a rental fee, a third party allows you to install a virtual server on their IT infrastructure. Compared to SaaS and PaaS, IaaS users are responsible for managing more: applications, data, runtime, middleware, and O/S. Vendors still manage virtualization, servers, hard drives, storage, and networking. What users gain with IaaS is infrastructure on top of which they can install any required platforms. Users are responsible for updating these if new versions are released.
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
, @Size
and @Min
are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:
manufacturer
shall never be null
licensePlate
shall never be null and must be between 2 and 14 characters long
seatCount
shall be at least 2.
Here are some Tips:
DELETE
200 (if you want send some additional data in the Response) or 204 (recommended).
202 Operation deleted has not been committed yet.
If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)
Other errors:
- 400 Bad Request (Malformed syntax or a bad query is strange but possible).
- 401 Unauthorized Authentication failure
- 403 Forbidden: Authorization failure or invalid Application ID.
- 405 Not Allowed. Sure.
- 409 Resource Conflict can be possible in complex systems.
- And 501, 502 in case of errors.
PUT
If you're updating an element of a collection
- 200/204 with the same reasons as DELETE above.
- 202 if the operation has not been commited yet.
The referenced element doesn't exists:
PUT can be 201 (if you created the element because that is your behaviour)
404 If you don't want to create elements via PUT.
400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).
401 Unauthorized
403 Forbidden: Authentication failure or invalid Application ID.
405 Not Allowed. Sure.
409 Resource Conflict can be possible in complex systems, as in DELETE.
422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values
And 501, 502 in case of errors.
Have you checked these official docs?
HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
- will listen to the event emitted by the host element that's declared with @HostListener
.
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.
@HostBinding
- will bind the property to the host element, If a binding changes, HostBinding
will update the host element.
NOTE: Both links have been removed recently. The "HostBinding-HostListening" portion of the style guide may be a useful alternative until the links return.
Here's a simple code example to help picture what this means:
DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"
role
property -- declared with @HostBinding
-- to the host's element
role
is an attribute, since we're using attr.role
.<p myDir>
becomes <p mydir="" role="admin">
when you view it in developer tools.onClick
event declared with @HostListener
, attached to the component's host element, changing role
with each click.
<p myDir>
is clicked is that its opening tag changes from <p mydir="" role="admin">
to <p mydir="" role="guest">
and back.directives.ts
import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';
@Directive({selector: '[myDir]'})
export class HostDirective {
@HostBinding('attr.role') role = 'admin';
@HostListener('click') onClick() {
this.role= this.role === 'admin' ? 'guest' : 'admin';
}
}
AppComponent.ts
import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';
@Component({
selector: 'my-app',
template:
`
<p myDir>Host Element
<br><br>
We have a (HostListener) listening to this host's <b>click event</b> declared with @HostListener
<br><br>
And we have a (HostBinding) binding <b>the role property</b> to host element declared with @HostBinding
and checking host's property binding updates.
If any property change is found I will update it.
</p>
<div>View this change in the DOM of the host element by opening developer tools,
clicking the host element in the UI.
The role attribute's changes will be visible in the DOM.</div>
`,
directives: [HostDirective]
})
export class AppComponent {}
Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:
class Enumerator(object):
def __init__(self, name):
self.name = name
def __eq__(self, other):
if self.name == other:
return True
return self is other
def __ne__(self, other):
if self.name != other:
return False
return self is other
def __repr__(self):
return 'Enumerator({0})'.format(self.name)
def __str__(self):
return self.name
class Enum(object):
def __init__(self, *enumerators):
for e in enumerators:
setattr(self, e, Enumerator(e))
def __getitem__(self, key):
return getattr(self, key)
Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.
Example:
class Cow(object):
State = Enum(
'standing',
'walking',
'eating',
'mooing',
'sleeping',
'dead',
'dying'
)
state = State.standing
In [1]: from enum import Enum
In [2]: c = Cow()
In [3]: c2 = Cow()
In [4]: c.state, c2.state
Out[4]: (Enumerator(standing), Enumerator(standing))
In [5]: c.state == c2.state
Out[5]: True
In [6]: c.State.mooing
Out[6]: Enumerator(mooing)
In [7]: c.State['mooing']
Out[7]: Enumerator(mooing)
In [8]: c.state = Cow.State.dead
In [9]: c.state == c2.state
Out[9]: False
In [10]: c.state == Cow.State.dead
Out[10]: True
In [11]: c.state == 'dead'
Out[11]: True
In [12]: c.state == Cow.State['dead']
Out[11]: True
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
You can simply do ifconfig
on host machine to check your host IP, then connect to the ip from within your container, works perfectly for me.
Query to find out all the datatype of columns being used in any database
SELECT distinct DATA_TYPE FROM INFORMATION_SCHEMA.columns
WHERE table_schema = '<db_name>' AND column_name like '%';
data.reindex(index=data.index[::-1])
or simply:
data.iloc[::-1]
will reverse your data frame, if you want to have a for
loop which goes from down to up you may do:
for idx in reversed(data.index):
print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
or
for idx in reversed(data.index):
print(idx, data.Even[idx], data.Odd[idx])
You are getting an error because reversed
first calls data.__len__()
which returns 6. Then it tries to call data[j - 1]
for j
in range(6, 0, -1)
, and the first call would be data[5]
; but in pandas dataframe data[5]
means column 5, and there is no column 5 so it will throw an exception. ( see docs )
Assuming thant the content of mandrill_events
is an object (not a string), you can also use shift()
function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;
In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".
This is the mathematical way:
For year, month (1 to 12):
int daysInMonth = month !== 2 ?
31 - (((month - 1) % 7) % 2) :
28 + (year % 4 == 0 ? 1 : 0) - (year % 100 == 0 ? 1 : 0) + (year % 400 == 0 ? 1 : 0)
You may use jQuery in it like
$('#yesh').click(function(){
*****HERE GOES THE FUNCTION*****
});
Besides jQuery is easy to use.
You can make changes in colors etc using simple jQUery or Javascript.
I think that the problem is that you put #ifdef
instead of #ifndef
at the top of your header.h
file.
The guy who solved this posted it as LGPL and you're not allowed to modify it. I didn't even click on it when I saw that. Here's my version. This needs to be tested. There are probably bugs. Please post any updates. No warranty. You can modify this all you want, call it your own, print it out on a piece of paper and use it for kennel scrap, ... don't care.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
namespace DigitalBoundaryGroup
{
class HttpNameValueCollection
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
else
Post = HttpUtility.ParseQueryString(post_string);
}
public HttpNameValueCollection(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}
}
The following should work:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
->where('reservation_from', '<=', $to)
->get();
public class Itemfound{
public static void main(String args[]){
if( Arrays.asList("a","b","c").contains("a"){
System.out.println("It is here");
}
}
}
This is what you looking for. The contains() method simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
In our case, we had dropped support for SSL3, TLS1.0, and TLS1.1 for PCI-DSS compliance on our origin servers. However, you have to manually add support for TLS 1.1+ on your CloudFront origin server config. The AWS console displays the client-to-CF SSL settings, but does not easily show you CF-to-origin settings until you drill down. To fix, in the AWS console under CloudFront:
Yes, with set_index you can make Locality
your row index.
data.set_index('Locality', inplace=True)
If inplace=True
is not provided, set_index
returns the modified dataframe as a result.
Example:
> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
> df.loc['ABBOTSFORD'].values
array([427000, 448000])
> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
This concept is not that easy as it looks. We can access static members without inheritance, which is HasA-relation. We can access static members by extending the parent class also. That doesn't imply that it is an ISA-relation (Inheritance). Actually static members belong to the class, and static is not an access modifier. As long as the access modifiers permit to access the static members we can use them in other classes. Like if it is public then it will be accessible inside the same package and also outside the package. For private we can't use it anywhere. For default, we can use it only within the package. But for protected we have to extend the super class. So getting the static method to other class does not depend on being Static. It depends on Access modifiers. So, in my opinion, Static members can access if the access modifiers permit. Otherwise, we can use them like we use by Hasa-relation. And has a relation is not inheritance. Again we can not override the static method. If we can use other method but cant override it, then it is HasA-relation. If we can't override them it won't be inheritance.So the writer was 100% correct.
As far as I can tell reading the ES6 Promise specification and the standard promise specification theres no clause preventing an implementation from handling this case - however its not implemented in the following libraries:
I assume the reason for them omiting multi arg resolves is to make changing order more succinct (i.e. as you can only return one value in a function it would make the control flow less intuitive) Example:
new Promise(function(resolve, reject) {
return resolve(5, 4);
})
.then(function(x,y) {
console.log(y);
return x; //we can only return 1 value here so the next then will only have 1 argument
})
.then(function(x,y) {
console.log(y);
});
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>