I recently created a component called SwipeableView
as subclass of UIView
, written in Swift 5.1 . It support all 4 direction, has several customisation options and can animate and interpolate different attributes and items ( such as layout constraints, background/tint color, affine transform, alpha channel and view center, all of them demoed with the respective show case ). It also supports the swiping coordination with the inner scroll view if set or auto detected. Should be pretty easy and straightforward to be used ( I hope )
Link at https://github.com/LucaIaco/SwipeableView
proof of concept:
Hope it helps
Based on @AdilSoomro's great answer. I have come up with this:
@interface MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel
animated:(BOOL)animated;
-(double) getZoomLevel;
@end
@implementation MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
[self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}
-(double) getZoomLevel {
return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta));
}
@end
Just use this function.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = CategorytableView.indexPathForSelectedRow
let indexNumber = index?.row
let VC = segue.destination as! DestinationViewController
VC.value = self.data
}
EDIT Since not so recently by now, MinGW-w64 has "absorbed" one of the toolchain building projects. The downloads can be found here. The installer should work, and allow you to pick a version that you need.
Note the Qt SDK comes with the same toolchain. So if you are developing in Qt and using the SDK, just use the toolchain it comes with.
Another alternative that has up to date toolchains comes from... harhar... a Microsoft developer, none other than STL (Stephan T. Lavavej, isn't that a spot-on name for the maintainer of MSVC++ Standard Library!). You can find it here. It includes Boost.
Another option which is highly useful if you care for prebuilt dependencies is MSYS2, which provides a Unix shell (a Cygwin fork modified to work better with Windows pathnames and such), also provides a GCC. It usually lags a bit behind, but that is compensated for by its good package management system and stability. They also provide a functional Clang with libc++ if you care for such thing.
I leave the below for reference, but I strongly suggest against using MinGW.org, due to limitations detailed below. TDM-GCC (the MinGW-w64 version) provides some hacks that you may find useful in your specific situation, although I recommend using vanilla GCC at all times for maximum compatibility.
GCC for Windows is provided by two projects currently. They both provide a very own implementation of the Windows SDK (headers and libraries) which is necessary because GCC does not work with Visual Studio files.
The older mingw.org, which @Mat already pointed you to. They provide only a 32-bit compiler. See here for the downloads you need:
Alternatively, download mingw-get and use that.
The newer mingw-w64, which as the name predicts, also provides a 64-bit variant, and in the future hopefully some ARM support. I use it and built toolchains with their CRT. Personal and auto builds are found under "Toolchains targetting Win32/64" here. They also provide Linux to Windows cross-compilers. I suggest you try a personal build first, they are more complete. Try mine (rubenvb) for GCC 4.6 to 4.8, or use sezero's for GCC 4.4 and 4.5. Both of us provide 32-bit and 64-bit native toolchains. These packages include everything listed above. I currently recommend the "MinGW-Builds" builds, as these are currently sanctioned as "official builds", and come with an installer (see above).
For support, send an email to [email protected] or post on the forum via sourceforge.net.
Both projects have their files listed on sourceforge, and all you have to do is either run the installer (in case of mingw.org) or download a suitable zipped package and extract it (in the case of mingw-w64).
There are a lot of "non-official" toolchain builders, one of the most popular is TDM-GCC. They may use patches that break binary compatibility with official/unpatched toolchains, so be careful using them. It's best to use the official releases.
I'm not sure if this is what you wanted, but this is a very hackish way to include php. What you do is you put the php you want to run in another file, and then you include that file in an image. For example:
RunFromHTML.php
<?php
$file = fopen("file.txt", "w");
//This will create a file called file.txt,
//provided that it has write access to your filesystem
fwrite($file, "Hello World!");
//This will write "Hello World!" into file.txt
fclose($file);
//Always remember to close your files!
?>
RunPhp.html
<html>
<!--head should be here, but isn't for demonstration's sake-->
<body>
<img style="display: none;" src="RunFromHTML.php">
<!--This will run RunFromHTML.php-->
</body>
</html>
Now, after visiting RunPhp.html, you should find a file called file.txt in the same directory that you created the above two files, and the file should contain "Hello World!" inside of it.
That method will not work. The <title>
only supports plain text. You will need to create an .ico
image with the filename of favicon.ico
and save it into the root folder of your site (where your default page is).
Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head>
section of your HTML and reference your icon:
<link rel="shortcut icon" href="your_image_path_and_name.ico" />
You can use Photoshop (with a plug in) or GIMP (free) to create an .ico
file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).
Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.
Update 2: You can also use .png
images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico
files.
Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP
means that any INSERT
without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP
means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable
without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP
and DATETIME
columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMP
s) When you use TIMESTAMP
s, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
Here are two approaches:
@echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%
::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
Use set_index
with stack
for MultiIndex Series
, then for DataFrame
add reset_index
with rename
:
df1 = (df.set_index(["location", "name"])
.stack()
.reset_index(name='Value')
.rename(columns={'level_2':'Date'}))
print (df1)
location name Date Value
0 A test Jan-2010 12
1 A test Feb-2010 20
2 A test March-2010 30
3 B foo Jan-2010 18
4 B foo Feb-2010 20
5 B foo March-2010 25
You could add flex-basis: 100%
to achieve this.
.header {
display: flex;
}
.item {
flex-basis: 100%;
text-align: center;
border: 1px solid black;
}
For what it's worth, you could also use flex: 1
for the same results as well.
The shorthand of flex: 1
is the same as flex: 1 1 0
, which is equivalent to:
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
text-align: center;
border: 1px solid black;
}
If you want to overwrite specific changes, you need some way of telling it which ones you want to forget.
You could try selectively stashing the changes you want to abandon using git stash --patch
and then dropping that stash with git stash drop
. You can then pull in the remote changes and merge them as normal.
You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.
To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.
Have a look at this link about installing self-signed certificates.
A solution could be to use a local file which retrieves the remote content
remoteInclude.php
<?php
$url = $_GET['url'];
$contents = file_get_contents($url);
echo $contents;
The HTML
<iframe frameborder="1" id="frametest" src="/remoteInclude.php?url=REMOTE_URL_HERE"></iframe>
<script>
$("#frametest").load(function (){
var contents =$("#frametest").contents();
});
Actually you need to wait till the push animation ends. So you can delegate UINavigationController and prevent pushing till the animation ends.
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
waitNavigation = NO;
}
-(void)showGScreen:(id)gvc{
if (!waitNavigation) {
waitNavigation = YES;
[_nav popToRootViewControllerAnimated:NO];
[_nav pushViewController:gvc animated:YES];
}
}
Running through vimtutor only took me 30 minutes, which was enough to get familiar with vim. It was worth every second of it.
You can solve this problem by using AJAX. You don't need to load JQuery for AJAX but it has a better error and success handling than native JS.
I would do it like so:
1) add an click eventlistener to all my anchors on the page. 2) on click, you can setup an ajax-request to your php, in the POST-DATA you set the anchor id or the text-value 3) the php gets the value and you can setup a request to your database. Then you return the value which you need and echo it to the ajax-request. 4) your success function of the ajax-request is doing some stuff
For more information about ajax-requests look back here:
-> Ajax-Request NATIVE https://blog.garstasio.com/you-dont-need-jquery/ajax/
A simple JQuery examle:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
Get simple name instead of path.
String onlyClassName = this.getLocalClassName();
call above method in onCreate
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
If you want to do this by code, you can add the behavior like this:
serviceHost.Description.Behaviors.Remove(
typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
You could also create an ssh tunnel.
docker-compose.yml
:
---
version: '2'
services:
kibana:
image: "kibana:4.5.1"
links:
- elasticsearch
volumes:
- ./config/kibana:/opt/kibana/config:ro
elasticsearch:
build:
context: .
dockerfile: ./docker/Dockerfile.tunnel
entrypoint: ssh
command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"
docker/Dockerfile.tunnel
:
FROM buildpack-deps:jessie
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install ssh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/config && \
chown $USER:$USER -R /root/.ssh
config/ssh/config
:
# Elasticsearch Server
Host elasticsearch
HostName jump.host.czerasz.com
User czerasz
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
This way the elasticsearch
has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.
For iOS 7 I use this,
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
header.textLabel.textColor = [UIColor orangeColor];
}
Here is Swift 3.0 version with header resizing
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
header.textLabel!.textColor = UIColor.orange
}
}
In my opinion, the best way to do this is by implementing your own Clone()
method as shown below.
class Person
{
public string head;
public string feet;
// Downside: It has to be manually implemented for every class
public Person Clone()
{
return new Person() { head = this.head, feet = this.feet };
}
}
class Program
{
public static void Main(string[] args)
{
Person a = new Person() { head = "bigAF", feet = "smol" };
Person b = a.Clone();
b.head = "notEvenThatBigTBH";
Console.WriteLine($"{a.head}, {a.feet}");
Console.WriteLine($"{b.head}, {b.feet}");
}
}
Output:
bigAf, smol
notEvenThatBigTBH, smol
b
is totally independent to a
, due to it not being a reference, but a clone.
Hope I could help!
Put it this way
where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS'))
Where
R is table name.
TIME_STAMP is FieldName in Table R.
I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.
Now the SSH option is under the security settings
Click Your Avatar --> Bitbucket Settings --> SSH Key --> Add Key
Paste your public key
Code for MainActivity.java file.
package com.android_examples.com.toastbackgroundcolorchange;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button BT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BT = (Button)findViewById(R.id.button1);
BT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT);
View toastView = ToastMessage.getView();
toastView.setBackgroundResource(R.layout.toast_background_color);
ToastMessage.show();
}
});
}
}
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" />
</RelativeLayout>
Code for toast_background_color.xml layout file created in res->layout folder.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke
android:width="3dp"
android:color="#ffffff" ></stroke>
<padding android:left="20dp" android:top="20dp"
android:right="20dp" android:bottom="20dp" />
<corners android:radius="10dp" />
<gradient android:startColor="#ff000f"
android:endColor="#ff0000"
android:angle="-90"/>
</shape>
The continue
keyword will do what you are after. break
will exit out of the foreach
loop, so you'll want to avoid that.
To float a div to the right pull-right
is the recommend way, I feel you are doing things right may be you only need to use text-align:right;
<div class="container">
<div class="row-fluid">
<div class="span6">
<p>Text left</p>
</div>
<div class="span6 pull-right" style="text-align:right">
<p>text right</p>
</div>
</div>
</div>
</div>
Do not forget that you also can pass these use
variables by reference.
The use cases are when you need to change the use
'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).
$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
$newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);
Now $newarray
will comprise (pseudocode here for brevity) [{times2:2},{times2:4}]
.
On the contrary, using $newarray
with no &
modifier would make outer $newarray
variable be read-only accessible from within the closure scope. But $newarray
within closure scope would be a completelly different newly created variable living only within the closure scope.
Despite both variables' names are the same these would be two different variables. The outer $newarray
variable would comprise []
in this case after the code has finishes.
If you want to save data that is derived from a Javascript canvas.toDataURL()
function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
?>
I had the same problem and resulted that was an "every day" error in the rails controller. I don't know why, but on production, puma runs the error again and again causing the message:
upstream timed out (110: Connection timed out) while reading response header from upstream
Probably because Nginx tries to get the data from puma again and again.The funny thing is that the error caused the timeout message even if I'm calling a different action in the controller, so, a single typo blocks all the app.
Check your log/puma.stderr.log file to see if that is the situation.
The simplest answer, assuming you don't mind the vagaries and variations in format between different platforms, is the standard %p
notation.
The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)
On some platforms, that will include a leading 0x
and on others it won't, and the letters could be in lower-case or upper-case, and the C standard doesn't even define that it shall be hexadecimal output though I know of no implementation where it is not.
It is somewhat open to debate whether you should explicitly convert the pointers with a (void *)
cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void
'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char *
address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).
If you aren't happy with the implementation-defined behaviour of %p
, then use C99 <inttypes.h>
and uintptr_t
instead:
printf("0x%" PRIXPTR "\n", (uintptr_t)your_pointer);
This allows you to fine-tune the representation to suit yourself. I chose to have the hex digits in upper-case so that the number is uniformly the same height and the characteristic dip at the start of 0xA1B2CDEF
appears thus, not like 0xa1b2cdef
which dips up and down along the number too. Your choice though, within very broad limits. The (uintptr_t)
cast is unambiguously recommended by GCC when it can read the format string at compile time. I think it is correct to request the cast, though I'm sure there are some who would ignore the warning and get away with it most of the time.
Kerrek asks in the comments:
I'm a bit confused about standard promotions and variadic arguments. Do all pointers get standard-promoted to void*? Otherwise, if
int*
were, say, two bytes, andvoid*
were 4 bytes, then it'd clearly be an error to read four bytes from the argument, non?
I was under the illusion that the C standard says that all object pointers must be the same size, so void *
and int *
cannot be different sizes. However, what I think is the relevant section of the C99 standard is not so emphatic (though I don't know of an implementation where what I suggested is true is actually false):
§6.2.5 Types
¶26 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
(C11 says exactly the same in the section §6.2.5, ¶28, and footnote 48.)
So, all pointers to structures must be the same size as each other, and must share the same alignment requirements, even though the structures the pointers point at may have different alignment requirements. Similarly for unions. Character pointers and void pointers must have the same size and alignment requirements. Pointers to variations on int
(meaning unsigned int
and signed int
) must have the same size and alignment requirements as each other; similarly for other types. But the C standard doesn't formally say that sizeof(int *) == sizeof(void *)
. Oh well, SO is good for making you inspect your assumptions.
The C standard definitively does not require function pointers to be the same size as object pointers. That was necessary not to break the different memory models on DOS-like systems. There you could have 16-bit data pointers but 32-bit function pointers, or vice versa. This is why the C standard does not mandate that function pointers can be converted to object pointers and vice versa.
Fortunately (for programmers targetting POSIX), POSIX steps into the breach and does mandate that function pointers and data pointers are the same size:
§2.12.3 Pointer Types
All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to
void *
shall not alter the representation. Avoid *
value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.Note: The ISO C standard does not require this, but it is required for POSIX conformance.
So, it does seem that explicit casts to void *
are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf()
. On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void *
without a cast.
I've posted a new solution for this on another thread.
It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.
SELECT username FROM all_users ORDER BY username;
Use assertNull(...)
@Test
public void foo() {
try {
//execute code that you expect not to throw Exceptions.
} catch (Exception e){
assertNull(e);
}
}
mysql_query("LOAD DATA LOCAL INFILE '/path/to/file' INTO TABLE mytable");
You can use replace_entities from w3lib.html library
In [202]: from w3lib.html import replace_entities
In [203]: replace_entities("£682m")
Out[203]: u'\xa3682m'
In [204]: print replace_entities("£682m")
£682m
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
command.Parameters.AddWithValue("@param1", klantId));
command.Parameters.AddWithValue("@param2", klantNaam));
command.Parameters.AddWithValue("@param3", klantVoornaam));
command.ExecuteNonQuery();
}
}
Recently I am also faced the same problem, while submitting my own WordPress plugin to the directory, Finally, i figured out and worked me,
Just add a comment/ Commit message. It will work,
I used TortiseSVN.
Changing the image source is the solution. You can indeed do this by adding a timestamp or random number to the image.
Better would be to add a checksum of eg the data the image represents. This enables caching when possible.
As per comment from @Paul, If display: block is specified, span stops to be an inline element and an element after it appears on next line.
I came here to find solution to my span height problem and I got a solution of my own
Adding overflow:hidden;
and keeing it inline will solve the problem just tested in IE8 Quirks mode
For me it wasn't working even with hibernate.hbm2ddl.auto
set to update
. It turned out that the generated creation SQL was invalid, because one of my column names (user
) was an SQL keyword. This failed softly, and it wasn't obvious what was going on until I inspected the logs.
In imports
import re
In run time processing:
RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):
It should be mentioned that not using re.compile
is wasteful. Every time the above match method is called, the regular expression will be compiled. This is also faulty practice in other programming languages. The below is the better practice.
In app initialization:
self.RE_TEST = re.compile('test', re.IGNORECASE)
In run time processing:
if self.RE_TEST.match('TeSt'):
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
try
<img src="https://cdn.glitch.com/0e4d1ff3-5897-47c5-9711-d026c01539b8%2Fbddfd6e4434f42662b009295c9bab86e.gif?v=1573157191712" alt="this slowpoke moves" width="250" alt="404 image"/>
_x000D_
and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.
Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.
If it has to be "nested", this would be one way, to get your job done:
SELECT o.name AS country, o.headofstate
FROM country o
WHERE o.headofstate like 'A%'
AND (
SELECT i.population
FROM city i
WHERE i.id = o.capital
) > 100000
A JOIN
would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015
All those implementation about finding the keyboard view and adding the done button at the 3rd row (that is why button.y = 163 b/c keyboard's height is 216) are fragile because iOS keeps change the view hierarchy. For example none of above codes work for iOS9.
I think it is more safe to just find the topmost view, by [[[UIApplication sharedApplication] windows] lastObject], and just add the button at bottom left corner of it, doneButton.frame = CGRectMake(0, SCREEN_HEIGHT-53, 106, 53);// portrait mode
For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy
by using the pipe |
after the cURL command.
Example: curl https://www.google.com/robots.txt | pbcopy
. This will copy all the content from the given URL to your clipboard.
When setting an image in a tableViewCell
or collectionViewCell
, this worked for me:
Place the following code in your cellForRowAtIndexPath
or cellForItemAtIndexPath
// Obtain pointer to cell. Answer assumes that you've done this, but here for completeness.
CheeseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cheeseCell" forIndexPath:indexPath];
// Grab the image from document library and set it to the cell.
UIImage *myCheese = [UIImage imageNamed:@"swissCheese.png"];
[cell.cheeseThumbnail setImage:myCheese forState:UIControlStateNormal];
NOTE: xCode seemed to get hung up on this for me. I had to restart both xCode and the Simulator, it worked properly.
This assumes that you've got cheeseThumbnail set up as an IBOutlet... and some other stuff... hopefully you're familiar enough with table/collection views and can fit this in.
Hope this helps.
Oh! just read comments in question, dear I missed it. but just letting the answer be here in case it can be useful to some other person
I tried "Ctrl+C" and "Ctrl+ Break" none worked. I was using SQL Plus that came with Oracle Client 10.2.0.1.0. SQL Plus is used by most as client for connecting with Oracle DB. I used the Cancel, option under File menu and it stopped the execution!
Once you click File wait for few mins then the select command halts and menu appears click on Cancel.
Come out of the "python interpreter."
I hope this should work
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
Let me add my own answer, because I believe the others are missing the point of Docker.
Using VOLUME
in the Dockerfile is the Right Way™, because you let Docker know that a certain directory contains permanent data. Docker will create a volume for that data and never delete it, even if you remove all the containers that use it.
It also bypasses the union file system, so that the volume is in fact an actual directory that gets mounted (read-write or readonly) in the right place in all the containers that share it.
Now, in order to access that data from the host, you only need to inspect your container:
# docker inspect myapp
[{
.
.
.
"Volumes": {
"/var/www": "/var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6...",
"/var/cache/nginx": "/var/lib/docker/vfs/dir/62499e6b31cb3f7f59bf00d8a16b48d2...",
"/var/log/nginx": "/var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87..."
},
"VolumesRW": {
"/var/www": false,
"/var/cache/nginx": true,
"/var/log/nginx": true
}
}]
What I usually do is make symlinks in some standard place such as /srv, so that I can easily access the volumes and manage the data they contain (only for the volumes you care about):
ln -s /var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6... /srv/myapp-www
ln -s /var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87... /srv/myapp-log
Try to add
GRANT USAGE ON SCHEMA public to readonly;
You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.
To Extend on @Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if(j <= c && i <= r) {
myArray[i][j] = 1;
} else {
myArray[i][j] = 0;
}
}
}
It's complicated.
First of all, in this code
const p = new Promise((resolve) => {
resolve(4);
});
the type of p
is inferred as Promise<{}>
. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p
should be Promise<number>
.
Then, Promise<{}>
is compatible with Promise<number>
, because basically the only property a promise has is then
method, and then
is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1
.
But the purpose of async
is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2
because {}
is obvioulsy not compatible with number
.
So the async
behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:
const whatever2 = async (): Promise<number> => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
For XP: Start > Control Panel > Java > Security > (Set to Medium) http://www.java.com/en/download/help/java_update.xml
Just another way to do it is to use the built-in file access technique:
(get-item .\filename.exe).VersionInfo | FL
You can also get any particular property off the VersionInfo, thus:
(get-item .\filename.exe).VersionInfo.FileVersion
This is quite close to the dir technique.
A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.
About efficiency, the virtual functions are slightly less efficient as the early-binding functions.
"This virtual call mechanism can be made almost as efficient as the "normal function call" mechanism (within 25%). Its space overhead is one pointer in each object of a class with virtual functions plus one vtbl for each such class" [A tour of C++ by Bjarne Stroustrup]
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener
then add the variable Button button1;
then add this to your onCreate()
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
when you implement OnClickListener you need to add the inherited method onClick()
where you will handle your clicks
Example:
import math
x = 5.55
print((math.floor(x*100)%100))
This is will give you two numbers after the decimal point, 55 from that example. If you need one number you reduce by 10 the above calculations or increase depending on how many numbers you want after the decimal.
I made it work with this:
.element {
transition: height 3s ease-out, width 5s ease-in;
}
EDIT: I noticed a few downvotes and took another look at this Q&A. Most people seem to miss that the OP asked for fields to be dynamically selected based on the caller-provided list of fields. You can't do this with the statically-defined json struct tag.
If what you want is to always skip a field to json-encode, then of course use json:"-"
to ignore the field (also note that this is not required if your field is unexported - those fields are always ignored by the json encoder). But that is not the OP's question.
To quote the comment on the json:"-"
answer:
This [the
json:"-"
answer] is the answer most people ending up here from searching would want, but it's not the answer to the question.
I'd use a map[string]interface{} instead of a struct in this case. You can easily remove fields by calling the delete
built-in on the map for the fields to remove.
That is, if you can't query only for the requested fields in the first place.
Getting Java to properly notify you of encoding errors is tricky. You must use the most verbose and, alas, the least used of the four alternate contructors for each of InputStreamReader
and OutputStreamWriter
to receive a proper exception on an encoding glitch.
For file I/O, always make sure to always use as the second argument to both OutputStreamWriter
and InputStreamReader
the fancy encoder argument:
Charset.forName("UTF-8").newEncoder()
There are other even fancier possibilities, but none of the three simpler possibilities work for exception handing. These do:
OutputStreamWriter char_output = new OutputStreamWriter(
new FileOutputStream("some_output.utf8"),
Charset.forName("UTF-8").newEncoder()
);
InputStreamReader char_input = new InputStreamReader(
new FileInputStream("some_input.utf8"),
Charset.forName("UTF-8").newDecoder()
);
As for running with
$ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere
The problem is that that will not use the full encoder argument form for the character streams, and so you will again miss encoding problems.
Here’s a longer example, this one managing a process instead of a file, where we promote two different input bytes streams and one output byte stream all to UTF-8 character streams with full exception handling:
// this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
Process
slave_process = Runtime.getRuntime().exec("perl -CS script args");
// fetch his stdin byte stream...
OutputStream
__bytes_into_his_stdin = slave_process.getOutputStream();
// and make a character stream with exceptions on encoding errors
OutputStreamWriter
chars_into_his_stdin = new OutputStreamWriter(
__bytes_into_his_stdin,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newEncoder()
);
// fetch his stdout byte stream...
InputStream
__bytes_from_his_stdout = slave_process.getInputStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stdout = new InputStreamReader(
__bytes_from_his_stdout,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
// fetch his stderr byte stream...
InputStream
__bytes_from_his_stderr = slave_process.getErrorStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stderr = new InputStreamReader(
__bytes_from_his_stderr,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
Now you have three character streams that all raise exception on encoding errors, respectively called chars_into_his_stdin
, chars_from_his_stdout
, and chars_from_his_stderr
.
This is only slightly more complicated that what you need for your problem, whose solution I gave in the first half of this answer. The key point is this is the only way to detect encoding errors.
Just don’t get me started about PrintStream
s eating exceptions.
SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object
, and the subarrays retain their identity.
Following that, you could do something like this:
In [5]: result=np.array([np.zeros((1)),np.zeros((2))])
In [6]: result
Out[6]: array([array([ 0.]), array([ 0., 0.])], dtype=object)
In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0., 1., 2.])
In [8]: result[0]
Out[8]: array([ 0.])
In [9]: result[0]=np.append([result[0]],[1,2])
In [10]: result
Out[10]: array([array([ 0., 1., 2.]), array([ 0., 0.])], dtype=object)
However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1]
, not result[0,1]
. If the subarrays are all the same length, I have to use np.array(result.tolist())
to produce a 2d array.
NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor
of the TextBox
.
I think what you really want to do is enable the TextBox
and set the ReadOnly
property to true
.
It's a bit tricky to change the color of the text in a disabled TextBox
. I think you'd probably have to subclass and override the OnPaint
event.
ReadOnly
though should give you the same result as !Enabled
and allow you to maintain control of the color and formatting of the TextBox
. I think it will also still support selecting and copying text from the TextBox
which is not possible with a disabled TextBox
.
Another simple alternative is to use a Label
instead of a TextBox
.
Use .text() to extract the content of the div
var text = $('#field-function_purpose').text()
It is mentioned under "Index expressions".
An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
v, ok = a[x] v, ok := a[x] var v, ok = a[x]
yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.
DisplayFor
is also useful for templating. You could write a template for your Model, and do something like this:
@Html.DisplayFor(m => m)
Similar to @Html.EditorFor(m => m)
. It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.
Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:
http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/
It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress
data annotation, DisplayFor
will render it as a mailto:
link.
On windows, You only need to open the command prompt and type:
dotnet --version
If the .net core framework installed you will get current installed version
see screenshot:
Open notepad as administrator and write:
@echo %cd%
Save it in c:\windows\system32\ with the name "pwd.cmd" (be careful not to save pwd.cmd.txt)
Then you have the pwd command.
Works for me:
grep "\bsearch_word\b" text_file > output.txt
\b
indicates/sets boundaries.
Seems to work pretty fast
Convert.ChangeType()
doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:
public static class Converter
{
public static T ConvertTo<T>(object value)
{
return ConvertTo(value, default(T));
}
public static T ConvertTo<T>(object value, T defaultValue)
{
if (value == DBNull.Value)
{
return defaultValue;
}
return (T) ChangeType(value, typeof(T));
}
public static object ChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
// if it's not a nullable type, just pass through the parameters to Convert.ChangeType
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// null input returns null output regardless of base type
if (value == null)
{
return null;
}
// it's a nullable type, and not null, which means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
conversionType = Nullable.GetUnderlyingType(conversionType);
}
else if (conversionType.IsEnum)
{
// strings require Parse method
if (value is string)
{
return Enum.Parse(conversionType, (string) value);
}
// primitive types can be instantiated using ToObject
else if (value is int || value is uint || value is short || value is ushort ||
value is byte || value is sbyte || value is long || value is ulong)
{
return Enum.ToObject(conversionType, value);
}
else
{
throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
"not supported for enum conversions.", conversionType.FullName));
}
}
return Convert.ChangeType(value, conversionType);
}
}
Then your implementation of GetQueryString<T> can be:
public static T GetQueryString<T>(string key)
{
T result = default(T);
string value = HttpContext.Current.Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
try
{
result = Converter.ConvertTo<T>(value);
}
catch
{
//Could not convert. Pass back default value...
result = default(T);
}
}
return result;
}
Update Swift 4.1
Here we create a struct to implement the Tuple usage and validate the OTP text length. That needs to be of 2 fields for this example.
struct ValidateOTP {
var code: String
var isValid: Bool }
func validateTheOTP() -> ValidateOTP {
let otpCode = String(format: "%@%@", txtOtpField1.text!, txtOtpField2.text!)
if otpCode.length < 2 {
return ValidateOTP(code: otpCode, isValid: false)
} else {
return ValidateOTP(code: otpCode, isValid: true)
}
}
Usage:
let isValidOTP = validateTheOTP()
if isValidOTP.isValid { print(" valid OTP") } else { self.alert(msg: "Please fill the valid OTP", buttons: ["Ok"], handler: nil)
}
Hope it helps!
Thanks
Visual examples help with this kind of question.
In order to create a gradient, you create an xml file in res/drawable. I am calling mine my_gradient_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
</shape>
You set it to the background of some view. For example:
<View
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@drawable/my_gradient_drawable"/>
Set the angle
for a linear
type. It must be a multiple of 45 degrees.
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
Set the gradientRadius
for a radial
type. Using %p
means it is a percentage of the smallest dimension of the parent.
<gradient
android:type="radial"
android:gradientRadius="10%p"
android:startColor="#f6ee19"
android:endColor="#115ede" />
I don't know why anyone would use a sweep, but I am including it for completeness. I couldn't figure out how to change the angle, so I am only including one image.
<gradient
android:type="sweep"
android:startColor="#f6ee19"
android:endColor="#115ede" />
You can also change the center of the sweep or radial types. The values are fractions of the width and height. You can also use %p
notation.
android:centerX="0.2"
android:centerY="0.7"
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
The thread module does work simultaneously unlike multiprocess, but the timing is a bit off. The code below prints a "1" and a "2". These are called by different functions respectively. I did notice that when printed to the console, they would have slightly different timings.
from threading import Thread
def one():
while(1 == num):
print("1")
time.sleep(2)
def two():
while(1 == num):
print("2")
time.sleep(2)
p1 = Thread(target = one)
p2 = Thread(target = two)
p1.start()
p2.start()
Output: (Note the space is for the wait in between printing)
1
2
2
1
12
21
12
1
2
Not sure if there is a way to correct this, or if it matters at all. Just something I noticed.
I have same problem. I solved install this setup. (I use vs 2015 (4.6))
You can also convert the URI to file and then to bytes if you want to upload the photo to your server.
Check out : https://www.stackoverflow.com/a/49575321
A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.
For example, see: Application Scripting Framework
Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:
A subscriptable object is any object that implements the __getitem__
special method (think lists, dictionaries).
Take a look at this link: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
How they work is too broad of a subject to cover in one SO post.
Here is one of the best explanations of indexes I have seen. Unfortunately it is for SQL Server and not MySQL. I'm not sure how similar the two are...
I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable
instance you create will internally be wrapped and executed as a thread.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
threadExecutor.execute(
new Runnable() {
@Override
public void run() {
System.out.println("blah");
}
}
);
} finally {
threadExecutor.shutdownNow();
}
For convenience, see the code on JDoodle.
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
And then you probably need to install all of vendor packages, so
composer install
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
var selectDate = element.datepicker({
dateFormat:'dd/mm/yy',
onSelect:function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
}).on('changeDate', function(ev) {
selectDate.hide();
ngModelCtrl.$setViewValue(element.val());
scope.$apply();
});
The Untick-tick (check-uncheck) "Automatically manage signing".) of Xcode checkboxes don't work for me (as many suggested on the top).
It happens with frameworks linked in your project.
Build settings
Signing Identity
Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:
total = 0;
for i = 1:numel(A)
total = total+A(i);
end
Be careful all of the other answers have some problem in IE.
Lets have this situation - button with prepended icon. All browsers handles this correctly, but IE takes the width of the element and scales the before content to fit it. JSFiddle
#mydiv1 { width: 200px; height: 30px; background: green; }
#mydiv1:before {
content: url("data:url or /standard/url.svg");
}
Solution is to set size to before element and leave it where it is:
#mydiv2 { width: 200px; height: 30px; background: green; }
#mydiv2:before {
content: url("data:url or /standard/url.svg");
display: inline-block;
width: 16px; //only one size is alright, IE scales uniformly to fit it
}
The background-image
+ background-size
solutions works as well, but is little unhandy, since you have to specify the same sizes twice.
The result in IE11:
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
import { from } from 'rxjs';
from(firebase.auth().createUserWithEmailAndPassword(email, password))
.subscribe((user: any) => {
console.log('test');
});
Here is a shorter version using a combination of some of the answers above to convert your code from a promise to an observable.
I don't think it makes a real difference for Strings. What is contiguous in an array of strings is the references to the strings, the strings themselves are stored at random places in memory.
Arrays vs. Lists can make a difference for primitive types, not for objects. IF you know in advance the number of elements, and don't need flexibility, an array of millions of integers or doubles will be more efficient in memory and marginally in speed than a list, because indeed they will be stored contiguously and accessed instantly. That's why Java still uses arrays of chars for strings, arrays of ints for image data, etc.
Perl solution:
perl -lane 'splice @F,0,1; print join " ",@F' file
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-e
execute the perl code
splice @F,0,1
cleanly removes column 0 from the @F array
join " ",@F
joins the elements of the @F array, using a space in-between each element
Python solution:
python -c "import sys;[sys.stdout.write(' '.join(line.split()[1:]) + '\n') for line in sys.stdin]" < file
For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.
Then the command that you should use is:
git clone https://username:[email protected]/reponame/projectname.git
Made a Grunt build with the Bootstrap 3.3.5 grid only:
https://github.com/horgen/grunt-builds/tree/master/bootstrap-grid
~10KB minimized.
If you need some other parts from Bootstrap just include them in /src/less/bootstrap.less.
For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.
On macOS High Sierra, this solved my issue:
sudo gem update --system -n /usr/local/bin/gem
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
Trying using :
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);
This will fit your imageview to the screen with the correct ratio.
You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.
Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/
I've basic demo -
//app.js
import {sum} from './calc.js'
console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }
export {sum};
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>ES6</h1>
<script src="app.js" type="module"></script>
</body>
</html>
Hope it helps!
I was able to solve it by running
git config --list --show-origin
and then seeing that I had a line:
file:c:/Users/user/.gitconfig http.sslversion=sslv3
I edited the file, c:/Users/user/.gitconfig, and deleted the line [http] and the line sslversion=sslv3 and that fixed it for me.
Based on the doc
<div class="row">
<div class="span4 collapse-group">
<h2>Heading</h2>
<p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
$('.row .btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
});
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
use state is not always needed you can just simply do this
let paymentList = [
{"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]
then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.
<div className="card-body">
<div className="table-responsive">
<table className="table table-striped">
<thead>
<tr>
<th>Transaction ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{
paymentList.map((payment, key) => (
<tr key={key}>
<td>{payment.txnid}</td>
<td>{payment.fname}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
A lot of good answers already for Ubuntu. I'm on Linux and had the same problem but none of the commands above worked for me.
With Linux and php70 I used the following command which worked great:
sudo yum install php70-mbstring -y
To find duplicate counts use below command as requested by you :
sort filename | uniq -c | awk '{print $2, $1}'
If you already use Kotlin Gradle DSL, the alternative to using it this way:
Here's my project structure
|-root
|----- app
|--------- libs // I choose to store the aar here
|-------------- my-libs-01.aar
|-------------- my-libs-02.jar
|--------- build.gradle.kts // app module gradle
|----- common-libs // another aar folder/directory
|----------------- common-libs-01.aar
|----------------- common-libs-02.jar
|----- build.gradle.kts // root gradle
My app/build.gradle.kts
fileTree
// android related config above omitted...
dependencies {
// you can do this to include everything in the both directory
// Inside ./root/common-libs & ./root/app/libs
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.aar"))))
implementation(fileTree(mapOf("dir" to "../common-libs", "include" to listOf("*.jar", "*.aar"))))
}
flatDirs
// android related config above omitted...
repositories {
flatDir {
dirs = mutableSetOf(File("libs"), File("../common-libs")
}
}
dependencies {
implementation(group = "", name = "my-libs-01", ext = "aar")
implementation(group = "", name = "my-libs-02", ext = "jar")
implementation(group = "", name = "common-libs-01", ext = "aar")
implementation(group = "", name = "common-libs-02", ext = "jar")
}
The group
was needed, due to its mandatory (not optional/has default value) in kotlin implementation
, see below:
// Filename: ReleaseImplementationConfigurationAccessors.kt
package org.gradle.kotlin.dsl
fun DependencyHandler.`releaseImplementation`(
group: String,
name: String,
version: String? = null,
configuration: String? = null,
classifier: String? = null,
ext: String? = null,
dependencyConfiguration: Action<ExternalModuleDependency>? = null
)
Disclaimer:
The difference using no.1 & flatDirs
no.2 approach, I still don't know much, you might want to edit/comment to this answer.
References:
The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.
In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".
In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.
Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.
See this link for a comparison of the two ways.
I saw very bad regexes in this page.. so i came with my own:
\b((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b
Explanation:
num-group = (0-9|10-99|100-199|200-249|250-255)
<border> + { <num-group> + <dot-cahracter> }x3 + <num-group> + <border>
Here you can verify how it works here
Based on my Comment here is one way to get what you want done:
Start byt selecting any cell in your range and Press Ctrl + T
This will give you this pop up:
make sure the Where is your table text is correct and click ok you will now have:
Now If you add a column header in D it will automatically be added to the table all the way to the last row:
Now If you enter a formula into this column:
After you enter it, the formula will be auto filled all the way to last row:
Now if you add a new row at the next row under your table:
Once entered it will be resized to the width of your table and all columns with formulas will be added also:
Hope this solves your problem!
use below statement if safe_mode
is off
set_time_limit(0);
I have no touch
and chmod
command in my cmd.exe
and git update-index --chmod=+x foo.sh
doesn't work for me.
I finally resolve it by setting skip-worktree
bit:
git update-index --skip-worktree --chmod=+x foo.sh
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
This is the method which i used to convert the integer to string.Correct me if i did wrong.
/**
* @param a
* @return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}
I normally set paths in
~/.bashrc
However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7
and it was sufficient for me.
you can also define multiple java_home's and have only one of them active (rest commented).
suppose in your bashrc file, you have
export JAVA_HOME=......jdk1.7
#export JAVA_HOME=......jdk1.8
notice 1.8 is commented. Once you do
source ~/.bashrc
jdk1.7 will be in path.
you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.
I would grab date.js or else you will need to roll your own formatting function.
I've had some success, although it relies on a few properties to work:
table-layout: fixed
border-collapse: separate
and cell 'widths' that divide/span easily, i.e. 4 x cells of 25% width:
.div-table-cell,_x000D_
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.div-table {_x000D_
display: table;_x000D_
border: solid 1px #ccc;_x000D_
border-left: none;_x000D_
border-bottom: none;_x000D_
table-layout: fixed;_x000D_
margin: 10px auto;_x000D_
width: 50%;_x000D_
border-collapse: separate;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
.div-table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.div-table-cell {_x000D_
display: table-cell;_x000D_
padding: 15px;_x000D_
border-left: solid 1px #ccc;_x000D_
border-bottom: solid 1px #ccc;_x000D_
text-align: center;_x000D_
background: #ddd;_x000D_
}_x000D_
_x000D_
.colspan-3 {_x000D_
width: 300%;_x000D_
display: table;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
.row-1 .div-table-cell:before {_x000D_
content: "row 1: ";_x000D_
}_x000D_
_x000D_
.row-2 .div-table-cell:before {_x000D_
content: "row 2: ";_x000D_
}_x000D_
_x000D_
.row-3 .div-table-cell:before {_x000D_
content: "row 3: ";_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.div-table-row-at-the-top {_x000D_
display: table-header-group;_x000D_
}
_x000D_
<div class="div-table">_x000D_
_x000D_
<div class="div-table-row row-1">_x000D_
_x000D_
<div class="div-table-cell">Cell 1</div>_x000D_
<div class="div-table-cell">Cell 2</div>_x000D_
<div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="div-table-row row-2">_x000D_
_x000D_
<div class="div-table-cell colspan-3">_x000D_
Cor blimey he's only gone and done it._x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="div-table-row row-3">_x000D_
_x000D_
<div class="div-table-cell">Cell 1</div>_x000D_
<div class="div-table-cell">Cell 2</div>_x000D_
<div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
https://jsfiddle.net/sfjw26rb/2/
Also, applying display:table-header-group or table-footer-group is a handy way of jumping 'row' elements to the top/bottom of the 'table'.
Both support the same functions. jquery.min.js
is a compressed version of jquery.js
(whitespaces and comments stripped out, shorter variable names, ...) in order to preserve bandwidth. In terms of functionality they are absolutely the same. It is recommended to use this compressed version in production environment.
Replace the line in htpasswd file:
go to: http://www.htaccesstools.com/htpasswd-generator-windows/
(if the link is expired, search another generator from google.com)
Enter your username and password. The site will generate encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".
You might also need to 'clear' the 'Authentication data' from tortoisSVN -> settings -> saved data
In Python 3.1+ you can specify multiple context expressions, and they will be processed as if multiple with
statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
This also means that you can use the alias from the first expression in the second (useful when working with db connections/cursors):
with get_conn() as conn, conn.cursor() as cursor:
cursor.execute(sql)
I was looking for an integer value in named column, so I did the below:
int index = dgv_myDataGridView.CurrentCell.RowIndex;
int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)
The good thing about this is that the column can be in any position in the grid view and you will still get the value.
Cheers
In Bootstrap 4 alpha-6 version, As navbar is using flex model, you can use justify-content-end
in parent's div and remove mr-auto
.
<div class="collapse navbar-collapse justify-content-end" id="navbarText">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
This works like a charm :)
You could also have problems if the string has <
, >
or &
chars in it, etc. Pass it to cgi.escape()
to deal with those.
http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape
In my dimens.xml I have
<dimen name="test">48dp</dimen>
In code If I do
int valueInPixels = (int) getResources().getDimension(R.dimen.test)
this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)
exactly as docs state :
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.
so if you want exact dp value just as in xml just divide it with DisplayMetrics density
int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)
dp will be 48 now
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output: 0002 0006
If you just want a field won't get persisted, both transient and @Transient work. But the question is why @Transient since transient already exists.
Because @Transient field will still get serialized!
Suppose you create a entity, doing some CPU-consuming calculation to get a result and this result will not save in database. But you want to sent the entity to other Java applications to use by JMS, then you should use @Transient
, not the JavaSE keyword transient
. So the receivers running on other VMs can save their time to re-calculate again.
This is the Kotlin extension function I use for this
/**
* Sets the specified Typeface Style on the first instance of the specified substring(s)
* @param one or more [Pair] of [String] and [Typeface] style (e.g. BOLD, ITALIC, etc.)
*/
fun TextView.setSubstringTypeface(vararg textsToStyle: Pair<String, Int>) {
val spannableString = SpannableString(this.text)
for (textToStyle in textsToStyle) {
val startIndex = this.text.toString().indexOf(textToStyle.first)
val endIndex = startIndex + textToStyle.first.length
if (startIndex >= 0) {
spannableString.setSpan(
StyleSpan(textToStyle.second),
startIndex,
endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
this.setText(spannableString, TextView.BufferType.SPANNABLE)
}
Usage:
text_view.text="something bold"
text_view.setSubstringTypeface(
Pair(
"something bold",
Typeface.BOLD
)
)
.
text_view.text="something bold something italic"
text_view.setSubstringTypeface(
Pair(
"something bold ",
Typeface.BOLD
),
Pair(
"something italic",
Typeface.ITALIC
)
)
You don't have any example code but I assume you want to do something like this?
@View({
directives: [NgClass],
styles: [`
.${TodoModel.COMPLETED} {
text-decoration: line-through;
}
.${TodoModel.STARTED} {
color: green;
}
`],
template: `<div>
<span [ng-class]="todo.status" >{{todo.title}}</span>
<button (click)="todo.toggle()" >Toggle status</button>
</div>`
})
You assign ng-class
to a variable which is dynamic (a property of a model called TodoModel
as you can guess).
todo.toggle()
is changing the value of todo.status
and there for the class of the input is changing.
This is an example for class name but actually you could do the same think for css properties.
I hope this is what you meant.
This example is taken for the great egghead tutorial here.
EF 6.1
public void DeleteWhere<TEntity>(Expression<Func<TEntity, bool>> predicate = null)
where TEntity : class
{
var dbSet = context.Set<TEntity>();
if (predicate != null)
dbSet.RemoveRange(dbSet.Where(predicate));
else
dbSet.RemoveRange(dbSet);
context.SaveChanges();
}
Usage:
// Delete where condition is met.
DeleteWhere<MyEntity>(d => d.Name == "Something");
Or:
// delete all from entity
DeleteWhere<MyEntity>();
If you are that particular to pass elements to viewmodel You can use
CommandParameter="{Binding ElementName=ManualParcelScanScreen}"
Go to Control Panel\System and Security\System\Advanced System Settings
then look for Environment Variables
.
Your user variables should contain Path=Path\to\Anaconda3\Scripts
.
You need to figure where your Anaconda3
folder is (i.e. the path to this folder) . Mine was in C:\Users
.
You need to add conda
to PATH
. To do so, type:
export PATH=/path/to/anaconda3/bin:$PATH
.
Same thing, you need to figure the path to anaconda3
folder (Usually, the path is stored in $HOME
)
If you don't want to do this everytime you start a session, you can also add conda
to PATH
in your .bashrc
file:
echo 'export PATH=/path/to/anaconda3/bin:$PATH' >> ~/.bashrc
As Django documentation says:
prefetch_related()
Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.
This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.
select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.
prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.
More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related
My one stop solution for Linux commands on windows is scoop. Install scoop from scoop.sh
scoop install openssl
openssl rand -base64 32
Dca3c3pptVkcb8fx243wN/3f/rQxx/rWYL8y7rZrGrA=
call DispatchQueue.main.after(when: DispatchTime, execute: () -> Void)
I'd highly recommend using the Xcode tools to convert to Swift 3 (Edit > Convert > To Current Swift Syntax). It caught this for me
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
After calling an request, set timeout to initialize slick slider.
var options = {
arrows: false,
slidesToShow: 1,
variableWidth: true,
centerPadding: '10px'
}
$.ajax({
type: "GET",
url: review_url+"?page="+page,
success: function(result){
setTimeout(function () {
$(".reviews-page-carousel").slick(options)
}, 500);
}
})
Do not initialize slick slider at start. Just initialize after an AJAX with timeout. That should work for you.
Python has a "not" operator, right? Is it not just "not"? As in,
return not bool
Providing both JAVA_HOME and JDK_HOME with identical Path without \bin helped for me! My settings:
\Program Files\Java\jdk1.8.0_05
%JAVA_HOME%
...%JAVA_HOME%\bin
Write this line after your insert code
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Insert is successfull')", true);
Further reading for any of the topics here: The Definitive Guide to Linux System Calls
I verified these using GNU Assembler (gas) on Linux.
x86-32 aka i386 Linux System Call convention:
In x86-32 parameters for Linux system call are passed using registers. %eax
for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.
The return value is in %eax
. All other registers (including EFLAGS) are preserved across the int $0x80
.
I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.
If there are more than six arguments,
%ebx
must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.
For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80
: Hello, world in assembly language with Linux system calls?
There is a faster way to make 32-bit system calls: using sysenter
. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter
dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80
. You should normally call into the vDSO instead of using sysenter
directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter
, and everything else to do with system calls.)
x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:
Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80
http://www.int80h.org/bsdasm/#default-calling-convention
(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)
Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the x86 tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)
Here is the snippet from this section:
- User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
- A system-call is done via the
syscall
instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.- The number of the syscall has to be passed in register %rax.
- System-calls are limited to six arguments, no argument is passed directly on the stack.
- Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is
-errno
.- Only values of class INTEGER or class MEMORY are passed to the kernel.
Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)
This 32-bit int $0x80
ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.
x86-32 Function Calling convention:
In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call
instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.
Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp
before a call
, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double
or something.
Some other modern 32-bit systems still don't require more than 4 byte stack alignment.
x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).
In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.
For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:
Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:
- If the class is MEMORY, pass the argument on the stack.
- If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used
So %rdi, %rsi, %rdx, %rcx, %r8 and %r9
are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call
instruction should be given. The stack (%rsp
) must be 16B-aligned when call
executes.
If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)
The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)
Variadic functions (like printf
) always need %al
= the number of FP register args.
There are rules for when to pack structs into registers (rdx:rax
on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.
Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.
Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page.
But after adding below code in my server.js
file it is save my day but it's not a proper solution or not a good way .
app.use(function(req, res, next){
var d = res.status(404);
if(d){
res.sendfile('index.html');
}
});
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
We can make it So simple like below
<input type="number" onkeydown="javascript: return event.keyCode == 69 ? false : true" />
_x000D_
Updated Answer
we can make it even more simple as @88 MPG suggests
<input type="number" onkeydown="return event.keyCode !== 69" />
_x000D_
Selenium doesn't currently offer API for this, but there are several ways to initiate an HTTP request in your test. It just depends what language you are writing in.
In Java for example, it might look like this:
// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
// continue with test
if (response.toString().equals("expected response"){
// do selenium
}
Try DataGridView.CurrentCellAddress.
Returns: A Point that represents the row and column indexes of the currently active cell.
E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )
I had this problem for quite a while, and like everybody else the answers above didn't apply to my project.
In my project I had linked up a project to my project and it was throwing ClassDefNotFoundError every time some code for the other project was executed.
So this was my solution. I went to project properties of my project and Java Build Path. Pressed the "Source"-tab and "link source" from src-folder of the other project to my own project and named a new folder "core-src".
Hopes this solution helps someone
In ef core, you can change the migration that was created after add migration. And then do update-database. A sample has given below:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(name: "Type", table: "Users", newName: "Discriminator", schema: "dbo");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(name: "Discriminator", table: "Users", newName: "Type", schema: "dbo");
}
Changing a constant type will lead to an Undefined Behavior.
However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.
Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.
OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http
, specifically the HttpClientHandler
, and found the following:
if (ExecutionContext.IsFlowSuppressed())
{
IWebProxy webProxy = (IWebProxy) null;
if (this.useProxy)
webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
this.SafeCaptureIdenity(state);
}
So after assessing that the ExecutionContext.IsFlowSuppressed()
might have been the culprit, I wrapped our Impersonation code as follows:
using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
// HttpClient code goes here!
}
The code inside of SafeCaptureIdenity
(not my spelling mistake), grabs WindowsIdentity.Current()
which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.
It now seems to work for us, phew!
May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.
With [email protected] :
// declare
@mixin button( $bgcolor:blue ){
background:$bgcolor;
}
and use without value, button will be blue
//use
.my_button{
@include button();
}
and with value, button will be red
//use
.my_button{
@include button( red );
}
works with hexa too
I usually use a bat script for that. Here's what I typically use:
@echo off
set d=%~dp0
java -Xmx400m -cp "%d%myapp.jar;%d%libs/mylib.jar" my.main.Class %*
The %~dp0 extract the directory where the .bat is located. This allows the bat to find the locations of the jars without requiring any special environment variables nor the setting of the PATH variable.
EDIT: Added quotes to the classpath. Otherwise, as Joey said, "fun things can happen with spaces"
Here's a quick code snippet that will find the first non-empty line in a string:
string line1;
while (
((line1 = sr.ReadLine()) != null) &&
((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }
if(line1 == null){ /* Error - no non-empty lines in string */ }
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
My site configuration file is example.conf in sites-available folder So you can create a symbolic link as
ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
The element.class selector is for styling situations such as this:
<span class="large"> </span>
<p class="large"> </p>
.large {
font-size:150%; font-weight:bold;
}
p.large {
color:blue;
}
Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.
As others have pointed out, what you're working with is descendant selectors.
You're pretty much right about cout
and cin
. They are objects (not functions) defined inside the std
namespace. Here are their declarations as defined by the C++ standard:
Header
<iostream>
synopsis#include <ios> #include <streambuf> #include <istream> #include <ostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; }
::
is known as the scope resolution operator. The names cout
and cin
are defined within std
, so we have to qualify their names with std::
.
Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:
class foo
{
public:
foo();
void bar();
};
The constructor named foo
is a member of the class named foo
. They have the same name because its the constructor. The function bar
is also a member of foo
.
Because they are members of foo
, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar
outside the class, you need to do it like so:
foo::foo()
{
// Implement the constructor
}
void foo::bar()
{
// Implement bar
}
This is because they are being defined outside the class. If you had not put the foo::
qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo
. For example, this is entirely different bar
:
void bar()
{
// Implement different bar
}
It's allowed to have the same name as the function in the foo
class because it's in a different scope. This bar
is in the global scope, whereas the other bar
belonged to the foo
class.
Here is my sugestion:
Dim i As integer, j as integer
With Worksheets("TimeOut")
i = 26
Do Until .Cells(8, i).Value = ""
For j = 9 to 100 ' I do not know how many rows you will need it.'
.Cells(j, i).Formula = "YourVolFormulaHere"
.Cells(j, i + 1).Formula = "YourCapFormulaHere"
Next j
i = i + 2
Loop
End With
Although this is an old-ish question, take a look at xmlVM http://www.xmlvm.org/clr2jvm, I'm not sure if it's mature enough yet, although it has been around for several years now. XMLvm was made, I believe, primarily for translating Android Java apps to the iPhone, however, its XML-code-translation-based framework is flexible enough to do other combinations (see the diagrams on the site).
As for a reason to do this conversion, maybe there is a need to 'hijack' some of the highly abundant oss code out there and use it within his/their own [Java] project.
Cheers
Rich
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
sometimes if a new header file is added, and this error starts coming due to that, you need to add library as well to get rid of unresolved external symbol
.
for example:
#include WtsApi32.h
will need:
#pragma comment(lib, "Wtsapi32.lib")
In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.
The first step is to create the helper class for the HTTP client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace callApi.Helpers
{
public class CallApi
{
private readonly Uri BaseUrlUri;
private HttpClient client = new HttpClient();
public CallApi(string baseUrl)
{
BaseUrlUri = new Uri(baseUrl);
client.BaseAddress = BaseUrlUri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public HttpClient getClient()
{
return client;
}
public HttpClient getClientWithBearer(string token)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
}
}
Then you can use this class in your code.
This is an example of how you call the REST API without bearer using the above class.
// GET API/values
[HttpGet]
public async Task<ActionResult<string>> postNoBearerAsync(string email, string password,string baseUrl, string action)
{
var request = new LoginRequest
{
email = email,
password = password
};
var callApi = new CallApi(baseUrl);
var client = callApi.getClient();
HttpResponseMessage response = await client.PostAsJsonAsync(action, request);
if (response.IsSuccessStatusCode)
return Ok(await response.Content.ReadAsAsync<string>());
else
return NotFound();
}
This is an example of how you can call the REST API that require bearer.
// GET API/values
[HttpGet]
public async Task<ActionResult<string>> getUseBearerAsync(string token, string baseUrl, string action)
{
var callApi = new CallApi(baseUrl);
var client = callApi.getClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync(action);
if (response.IsSuccessStatusCode)
{
return Ok(await response.Content.ReadAsStringAsync());
}
else
return NotFound();
}
You can also refer to the below repository if you want to see the working example of how it works.
Alternate solution. Include your external CSS in your HTML file by
<link rel="stylesheet" href="css/applyCSS.css"/>
inside the applyCSS.css:
#applyCSS {
/** Your Style**/
}
With collections.Counter
you could do
>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]
If appropriate, you could simply start with an empty collections.Counter
and add to it
>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc.
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy
, you can compute this with the ppf
method of the scipy.stats.norm
object. The acronym ppf
stands for percent point function, which is another name for the quantile function.
In [20]: from scipy.stats import norm
In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722
Check that it is the inverse of the CDF:
In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996
By default, norm.ppf
uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc
and scale
arguments, respectively.
In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945
If you look at the source code for scipy.stats.norm
, you'll find that the ppf
method ultimately calls scipy.special.ndtri
. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:
In [43]: from scipy.special import ndtri
In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722
Two things you can do, return an object
somethingAsync()
.then( afterSomething )
.then( afterSomethingElse );
function processAsync (amazingData) {
//processSomething
return {
amazingData: amazingData,
processedData: processedData
};
}
function afterSomething( amazingData ) {
return processAsync( amazingData );
}
function afterSomethingElse( dataObj ) {
let amazingData = dataObj.amazingData,
processedData = dataObj.proccessedData;
}
Use the scope!
var amazingData;
somethingAsync()
.then( afterSomething )
.then( afterSomethingElse )
function afterSomething( returnedAmazingData ) {
amazingData = returnedAmazingData;
return processAsync( amazingData );
}
function afterSomethingElse( processedData ) {
//use amazingData here
}
You don't need a numerical index for an object key, but many others have told you that.
Here's the actual answer:
var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
console.log( getObjectKeyIndex(json, 'key2') );
// Returns int(1) (or null if the key doesn't exist)
function getObjectKeyIndex(obj, keyToFind) {
var i = 0, key;
for (key in obj) {
if (key == keyToFind) {
return i;
}
i++;
}
return null;
}
Though you're PROBABLY just searching for the same loop that I've used in this function, so you can go through the object:
for (var key in json) {
console.log(key + ' is ' + json[key]);
}
Which will output
key1 is watevr1
key2 is watevr2
key3 is watevr3
The newly Selected answer submitted by Steven Soroka is close, but not complete. The test itself hides the fact that this is not returning a true 404 - it's returning a status of 200 - "success". The original answer was closer, but attempted to render the layout as if no failure had occurred. This fixes everything:
render :text => 'Not Found', :status => '404'
Here's a typical test set of mine for something I expect to return 404, using RSpec and Shoulda matchers:
describe "user view" do
before do
get :show, :id => 'nonsense'
end
it { should_not assign_to :user }
it { should respond_with :not_found }
it { should respond_with_content_type :html }
it { should_not render_template :show }
it { should_not render_with_layout }
it { should_not set_the_flash }
end
This healthy paranoia allowed me to spot the content-type mismatch when everything else looked peachy :) I check for all these elements: assigned variables, response code, response content type, template rendered, layout rendered, flash messages.
I'll skip the content type check on applications that are strictly html...sometimes. After all, "a skeptic checks ALL the drawers" :)
http://dilbert.com/strips/comic/1998-01-20/
FYI: I don't recommend testing for things that are happening in the controller, ie "should_raise". What you care about is the output. My tests above allowed me to try various solutions, and the tests remain the same whether the solution is raising an exception, special rendering, etc.
In my opinion, varchar(n)
has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.
TL;DR:
If you use text
type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n)
, you can prevent it.
Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text
type or varchar(n)
where n
is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n)
where n
is not too much greater than 2712, you're safe from these errors.
Below are code snippets to create and delete a cookie. The cookie is set for 1 day.
// 1 Day = 24 Hrs = 24*60*60 = 86400.
By using max-age:
document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
document.cookie = "cookieName=; max-age=- (any digit); path=/;";
By using expires:
var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
thisTag = _tags.FirstOrDefault(t => t.Key == tag);
is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.
The basic solution would be:
if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
But that requires 2 lookups.
TryGetValue(key, out value)
is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:
string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }
VS 2017 update, for C# 7 and beyond we can declare the result variable inline:
if (_tags.TryGetValue(tag, out string myValue))
{
// use myValue;
}
// use myValue, still in scope, null if not found
To update one column here are some syntax options:
Option 1
var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
}
db.SubmitChanges();
}
Update
As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status
at ones. We want to update name
and status
where the friendid
is matching. Here are some syntax options for that:
Option 1
var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
some.name=name;
}
db.SubmitChanges();
}
Update 2
In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:
db.SubmitChanges();
But for Entity Framework to commit the changes it is:
db.SaveChanges()
In my case, while using the --date option, my git process crashed. May be I did something terrible. And as a result some index.lock file appeared. So I manually deleted the .lock files from .git folder and executed, for all modified files to be commited in passed dates and it worked this time. Thanx for all the answers here.
git commit --date="`date --date='2 day ago'`" -am "update"
In your adapter class, in onBindViewHolder method, set ViewHolder to setIsRecyclable(false) as in below code.
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder p1, int p2)
{
// TODO: Implement this method
p1.setIsRecyclable(false);
// Then your other codes
}
Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.
For example:
var o = {"foo": 1, "bar": 2};
alert(Object.keys(o));
ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/
Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/
shortest Bootstrap-compatible way, no JavaScript:
.cameraicon {
height: 1.6em;/* set your own icon size */
mask: url(/camera.svg); /* path to your image */
-webkit-mask: url(/camera.svg) no-repeat center;
}
and use it like:
<td class="text-center">
<div class="bg-secondary cameraicon"/><!-- "bg-secondary" sets actual color of your icon -->
</td>
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })
to get the page scrolled with a smooth effect.
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
top: 400,_x000D_
behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
height: 1000px;_x000D_
background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
<button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
You can do something like this:
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
var i = 10;_x000D_
var int = setInterval(function() {_x000D_
window.scrollTo(0, i);_x000D_
i += 10;_x000D_
if (i >= 200) clearInterval(int);_x000D_
}, 20);_x000D_
})
_x000D_
body {_x000D_
background: #3a2613;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
ES6 recursive approach:
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
let i = h || 0;_x000D_
if (i < 200) {_x000D_
setTimeout(() => {_x000D_
window.scrollTo(0, i);_x000D_
smoothScroll(i + 10);_x000D_
}, 10);_x000D_
}_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
background: #9a6432;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
Here's how you could set a custom cookie value for the request:
var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("foo", "bar"),
new KeyValuePair<string, string>("baz", "bazinga"),
});
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
var result = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
I suspect a lot of the answers here are outdated, as I did not get the expected result from the given answer.
If you have value in KB that you would like to format according to the size, you can try the following.
[<1000]#" KB ";[<1000000]#0,00 " MB";0,## " GB"
952
=> 952 KB
1514
=> 1.51 MB
5122323
=> 5.12 GB
That's right, if you're on a mac(unix) you won't see .git in finder(the file browser). You can follow the directions above to delete and there are git commands that allow you to delete files as well(they are sometimes difficult to work with and learn, for example: on making a 'git rm -r ' command you might be prompted with a .git/ not found. Here is the git command specs:
usage: git rm [options] [--] ...
-n, --dry-run dry run
-q, --quiet do not list removed files
--cached only remove from the index
-f, --force override the up-to-date check
-r allow recursive removal
--ignore-unmatch exit with a zero status even if nothing matched
When I had to do this, deleting the objects and refs didn't matter. After I deleted the other files in the .git, I initialized a git repo with 'git init' and it created an empty repo.
#!/usr/bin/env python
import Tkinter as tk
from Tkinter import *
class windowclass():
def __init__(self,master):
self.master = master
self.frame = tk.Frame(master)
self.lbl = Label(master , text = "Label")
self.lbl.pack()
self.btn = Button(master , text = "Button" , command = self.command )
self.btn.pack()
self.frame.pack()
def command(self):
print 'Button is pressed!'
self.newWindow = tk.Toplevel(self.master)
self.app = windowclass1(self.newWindow)
class windowclass1():
def __init__(self , master):
self.master = master
self.frame = tk.Frame(master)
master.title("a")
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
self.quitButton.pack()
self.frame.pack()
def close_window(self):
self.master.destroy()
root = Tk()
root.title("window")
root.geometry("350x50")
cls = windowclass(root)
root.mainloop()
So what do you do if all the browsers (actually, Chrome 5 gave me quite good one) won't give you good enough resampling quality? You implement them yourself then! Oh come on, we're entering the new age of Web 3.0, HTML5 compliant browsers, super optimized JIT javascript compilers, multi-core(†) machines, with tons of memory, what are you afraid of? Hey, there's the word java in javascript, so that should guarantee the performance, right? Behold, the thumbnail generating code:
// returns a function that calculates lanczos weight
function lanczosCreate(lobes) {
return function(x) {
if (x > lobes)
return 0;
x *= Math.PI;
if (Math.abs(x) < 1e-16)
return 1;
var xx = x / lobes;
return Math.sin(x) * Math.sin(xx) / x / xx;
};
}
// elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes) {
this.canvas = elem;
elem.width = img.width;
elem.height = img.height;
elem.style.display = "none";
this.ctx = elem.getContext("2d");
this.ctx.drawImage(img, 0, 0);
this.img = img;
this.src = this.ctx.getImageData(0, 0, img.width, img.height);
this.dest = {
width : sx,
height : Math.round(img.height * sx / img.width),
};
this.dest.data = new Array(this.dest.width * this.dest.height * 3);
this.lanczos = lanczosCreate(lobes);
this.ratio = img.width / sx;
this.rcp_ratio = 2 / this.ratio;
this.range2 = Math.ceil(this.ratio * lobes / 2);
this.cacheLanc = {};
this.center = {};
this.icenter = {};
setTimeout(this.process1, 0, this, 0);
}
thumbnailer.prototype.process1 = function(self, u) {
self.center.x = (u + 0.5) * self.ratio;
self.icenter.x = Math.floor(self.center.x);
for (var v = 0; v < self.dest.height; v++) {
self.center.y = (v + 0.5) * self.ratio;
self.icenter.y = Math.floor(self.center.y);
var a, r, g, b;
a = r = g = b = 0;
for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
if (i < 0 || i >= self.src.width)
continue;
var f_x = Math.floor(1000 * Math.abs(i - self.center.x));
if (!self.cacheLanc[f_x])
self.cacheLanc[f_x] = {};
for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
if (j < 0 || j >= self.src.height)
continue;
var f_y = Math.floor(1000 * Math.abs(j - self.center.y));
if (self.cacheLanc[f_x][f_y] == undefined)
self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2)
+ Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
weight = self.cacheLanc[f_x][f_y];
if (weight > 0) {
var idx = (j * self.src.width + i) * 4;
a += weight;
r += weight * self.src.data[idx];
g += weight * self.src.data[idx + 1];
b += weight * self.src.data[idx + 2];
}
}
}
var idx = (v * self.dest.width + u) * 3;
self.dest.data[idx] = r / a;
self.dest.data[idx + 1] = g / a;
self.dest.data[idx + 2] = b / a;
}
if (++u < self.dest.width)
setTimeout(self.process1, 0, self, u);
else
setTimeout(self.process2, 0, self);
};
thumbnailer.prototype.process2 = function(self) {
self.canvas.width = self.dest.width;
self.canvas.height = self.dest.height;
self.ctx.drawImage(self.img, 0, 0, self.dest.width, self.dest.height);
self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
var idx, idx2;
for (var i = 0; i < self.dest.width; i++) {
for (var j = 0; j < self.dest.height; j++) {
idx = (j * self.dest.width + i) * 3;
idx2 = (j * self.dest.width + i) * 4;
self.src.data[idx2] = self.dest.data[idx];
self.src.data[idx2 + 1] = self.dest.data[idx + 1];
self.src.data[idx2 + 2] = self.dest.data[idx + 2];
}
}
self.ctx.putImageData(self.src, 0, 0);
self.canvas.style.display = "block";
};
...with which you can produce results like these!
so anyway, here is a 'fixed' version of your example:
img.onload = function() {
var canvas = document.createElement("canvas");
new thumbnailer(canvas, img, 188, 3); //this produces lanczos3
// but feel free to raise it up to 8. Your client will appreciate
// that the program makes full use of his machine.
document.body.appendChild(canvas);
};
Now it's time to pit your best browsers out there and see which one will least likely increase your client's blood pressure!
Umm, where's my sarcasm tag?
(since many parts of the code is based on Anrieff Gallery Generator is it also covered under GPL2? I don't know)
† actually due to limitation of javascript, multi-core is not supported.
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
One solution which avoids MultiIndex is to create a new datetime
column setting day = 1. Then group by this column.
df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
'Values': [5, 10, 15, 20]})
# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)
Then use groupby
as normal:
g = df.groupby('YearMonth')
res = g['Values'].sum()
# YearMonth
# 2017-09-01 20
# 2017-10-01 30
# Name: Values, dtype: int64
pd.Grouper
The subtle benefit of this solution is, unlike pd.Grouper
, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group
:
some_group = g.get_group('2017-10-01')
Calculating the last day of October is slightly more cumbersome. pd.Grouper
, as of v0.23, does support a convention
parameter, but this is only applicable for a PeriodIndex
grouper.
An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX
to string '2017-10'
. However, this is not recommended since you lose all the efficiency benefits of a datetime
series (stored internally as numerical data in a contiguous memory block) versus an object
series of strings (stored as an array of pointers).
Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH
For example if you installed to c:\Python27
set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%
Make sure you don't have a trailing '\' on the PYTHON* vars, this seems to break it aswel.
"user": {
"firstName": "Musa",
"lastName": "Aliyev",
"email": "[email protected]",
"passwordIn": "98989898", (or encoded version in front if we not using https)
"country": "Azeribaijan",
"phone": "+994707702747"
}
@CrossOrigin(methods=RequestMethod.POST)
@RequestMapping("/public/register")
public @ResponseBody MsgKit registerNewUsert(@RequestBody User u){
root.registerUser(u);
return new MsgKit("registered");
}
@Service
@Transactional
public class RootBsn {
@Autowired UserRepository userRepo;
public void registerUser(User u) throws Exception{
u.setPassword(u.getPasswordIn());
//Generate some salt and setPassword (encoded - salt+password)
User u=userRepo.save(u);
System.out.println("Registration information saved");
}
}
@Entity
@JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String country;
@Column(name="CREATED_BY")
private String createdBy;
private String email;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_LOGIN_DATE")
private Timestamp lastLoginDate;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="MODIFICATION_DATE")
private Timestamp modificationDate;
@Column(name="MODIFIED_BY")
private String modifiedBy;
private String password;
@Transient
private String passwordIn;
private String phone;
@Column(name="RECORD_DATE")
private Timestamp recordDate;
private String salt;
private String status;
@Column(name="USER_STATUS")
private String userStatus;
public User() {
}
// getters and setters
}
I was able to implement this successfully
<a [routerLink]="['/login']">abc</a>
You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.
The code should go like this:
Name_pairs np;
np.read_names()
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
_x000D_
#yourElement {
margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_