Here's an actual situation where I was forced to use a Functor to solve my problem:
I have a set of functions (say, 20 of them), and they are all identical, except each calls a different specific function in 3 specific spots.
This is incredible waste, and code duplication. Normally I would just pass in a function pointer, and just call that in the 3 spots. (So the code only needs to appear once, instead of twenty times.)
But then I realized, in each case, the specific function required a completely different parameter profile! Sometimes 2 parameters, sometimes 5 parameters, etc.
Another solution would be to have a base class, where the specific function is an overridden method in a derived class. But do I really want to build all of this INHERITANCE, just so I can pass a function pointer????
SOLUTION: So what I did was, I made a wrapper class (a "Functor") which is able to call any of the functions I needed called. I set it up in advance (with its parameters, etc) and then I pass it in instead of a function pointer. Now the called code can trigger the Functor, without knowing what is happening on the inside. It can even call it multiple times (I needed it to call 3 times.)
That's it -- a practical example where a Functor turned out to be the obvious and easy solution, which allowed me to reduce code duplication from 20 functions to 1.
I have made a bash script related to the same to check if the certificate is expired or not. You can use the same if required.
Script
https://github.com/zeeshanjamal16/usefulScripts/blob/master/sslCertificateExpireCheck.sh
ReadMe
https://github.com/zeeshanjamal16/usefulScripts/blob/master/README.md
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
If is VSCode see the workspace. If you are in other workspace this error can rise
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
It prompted me for password.
It shouldn't.
If you have the right public/private key representing a user authorized to access project-x
, then gitlab won't ask you for anything.
But that supposes that ssh -vT [email protected]
is working first.
Here you go, just tweaked readsquare's answer to return an array of all classes:
function classList(elem){
var classList = elem.attr('class').split(/\s+/);
var classes = new Array(classList.length);
$.each( classList, function(index, item){
classes[index] = item;
});
return classes;
}
Pass a jQuery element to the function, so that a sample call will be:
var myClasses = classList($('#myElement'));
mysql> select ip from foo where ip regexp '^\\s*[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]\\s*';
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
Modify the default findAll function in EntityRepository like this:
public function findAll( array $orderBy = null )
{
return $this->findBy([], $orderBy);
}
That way you can use the ''findAll'' on any query for any data table with an option to sort the query
It happens mostly when JQuery
is not installed in your project.
Install JQuery in your project by following commands according to your package manager.
yarn add jquery
npm i jquery --save
After this just import $
in your project file.
import $ from 'jquery'
I had this problem and tried the solutions mentioned here with no success.
Eventually, I realised that I was linking to the Google CDN version of the script using an http URL
while the page embedding the script was an https page
.
This caused IE to not load jquery (it prompts the user whether they want to load only secure content). Changing the Google CDN URL to use the https scheme fixed the problem for me.
The Easiest way example to show you how to do that is :
Code :
>>> points = 19.5
>>> total = 22
>>>'Correct answers: {:.2%}'.format(points/total)
`
Output : Correct answers: 88.64%
First of all, you don't need the entitlements file unless you are adding custom key/value pairs that do not exist in the provisioning profile. When your app is built, any entitlements from the provisioning profile will be copied to the app.
Given that you still see an error message about missing entitlements, I can only assume the code signing options are not correct in the build settings.
You need to make sure the correct profile is selected for the "Debug" configuration, and to be safe, that you have selected the correct profile for both the "Debug" and child-node labelled "Any iOS SDK":
Although this screenshot shows the "Automatic Developer" profile selected, choose the exact provisioning profile you want from the drop down, just for testing purposes. It could be that Xcode is automatically choosing a different profile than the one you want.
Also be sure to do a clean build, completely delete the app from your device, etc. This is just to make sure you don't have some old fluff hanging around.
This probably isn't what you wanted me to say, but this is a good use of AOP. Whip an proxy interceptor around your method, and do the timing in there.
The what, why and how of AOP is rather beyond the scope of this answer, sadly, but that's how I'd likely do it.
Edit: Here's a link to Spring AOP to get you started, if you're keen. This is the most accessible implementation of AOP that Iive come across for java.
Also, given everyone else's very simple suggestions, I should add that AOP is for when you don't want stuff like timing to invade your code. But in many cases, that sort of simple and easy approach is fine.
To use video extensions that are MKV. You should use video, not source
For example :
<!-- mkv -->
<video width="320" height="240" controls src="assets/animation.mkv"></video>
<!-- mp4 -->
<video width="320" height="240" controls>
<source src="assets/animation.mp4" type="video/mp4" />
</video>
_x000D_
It could be that you don't have privileges to some of the files. From an administrator account, try "sudo rsync -av " Alternately, enable the root account and sign in as root. That should allow you to completely hose your system and brute force your rsync! ;-) I'm not sure if the above mentioned --extended-attributes will help, but I threw it in too, just for good measure.
This seems simple enough and works both in python 2 and 3
try: subprocess.check_output('which executable',shell=True)
except: sys.exit('ERROR: executable not found')
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...
redis-cli -h <host> -p <port> keys *
where * is the pattern to list all keys
Simply delete the maintenance.flag
file in root folder and then delete the files of cache folder and session folder inside var/
folder.
Though this question is asking about group by class properties, if you want to group by multiple columns against a ADO object (like a DataTable), you have to assign your "new" items to variables:
EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
.Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
var Dups = ClientProfiles.AsParallel()
.GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
.Where(z => z.Count() > 1)
.Select(z => z);
The button isn't called the "browse button" — that's just the name your browser gives for it. Browsers are free to implement the file upload control however they like. In Safari, for example, it's called "Choose File" and it's on the opposite side of whatever you're probably using.
You can implement a custom look for the upload control using the technique outlined on QuirksMode, but that goes beyond just changing the button's text.
Hi i also got this error when i use my online databases from godaddy server i think it has the mysql version of 5.1 or more. but when i do from my localhost server (version 5.7) it was fine after that i created the table from local server and copied to the online server using mysql yog i think the problem is with character set
I would use VARCHAR
for variable length data, but not with fixed length data. Because a SHA-1 value is always 160 bit long, the VARCHAR
would just waste an additional byte for the length of the fixed-length field.
And I also wouldn’t store the value the SHA1
is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.
So I recommend you to use BINARY(20)
and the UNHEX
function to convert the SHA1
value to binary.
I compared storage requirements for BINARY(20)
and CHAR(40)
.
CREATE TABLE `binary` (
`id` int unsigned auto_increment primary key,
`password` binary(20) not null
);
CREATE TABLE `char` (
`id` int unsigned auto_increment primary key,
`password` char(40) not null
);
With million of records binary(20)
takes 44.56M, while char(40)
takes 64.57M.
InnoDB
engine.
I have a potential solution which I guess is relevent, I posted about it here:
https://www.facebook.com/antimatterstudios/posts/10150752380719364
basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code
var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);
I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.
then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.
Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.
A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt
and jshint
.
These lines add more meaning
Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.
Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:
There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.
Please Note that grunt plugin is also an npm package.
Question-1
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.
Question-2
When should I ever install packages explicitly like that without adding them to the file that manages dependencies
It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request
, then you have two options:
OR
npm install --save request
--save
options adds the dependency to package.json file as well. If you don't specify --save
option, it will only download the package but the json file will be unaffected.
You can do this either way, there will not be a substantial difference.
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
I think you must also remove security auto config from your @SpringBootApplication
annotated class:
@EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})
The most important distinction is that DateTime does not store time zone information, while DateTimeOffset does.
Although DateTime distinguishes between UTC and Local, there is absolutely no explicit time zone offset associated with it. If you do any kind of serialization or conversion, the server's time zone is going to be used. Even if you manually create a local time by adding minutes to offset a UTC time, you can still get bit in the serialization step, because (due to lack of any explicit offset in DateTime) it will use the server's time zone offset.
For example, if you serialize a DateTime value with Kind=Local using Json.Net and an ISO date format, you'll get a string like 2015-08-05T07:00:00-04
. Notice that last part (-04) had nothing to do with your DateTime or any offset you used to calculate it... it's just purely the server's time zone offset.
Meanwhile, DateTimeOffset explicitly includes the offset. It may not include the name of the time zone, but at least it includes the offset, and if you serialize it, you're going to get the explicitly included offset in your value instead of whatever the server's local time happens to be.
IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.
Yochai, if you ever read this, please see the note at the end.
For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library
one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked
while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking
Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.
Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.
[...] trawl through all your libraries and ensure they have the correct link settings
In the latter, as it in mentioned in the original post, two common problems can arise :
You have a third party library which is linked differently to your application.
You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.
For those cases, ensure you understand the problem and decide among the solutions.
Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry
This seems to work only for some characters ... including special characters for German, Portuguese, French. However, I ran into trouble with Russian, Hindi and Mandarin characters. These are not converted to Properties format 'native2ascii', instead get saved with ?? ?? ??
The only way I could get my app to display these characters correctly is by putting them in the properties file translated to UTF-8 format - as \u0915 instead of ?, or \u044F instead of ?.
Any advice?
If you are here because of Wordpress giving 404's when loading the environment, this should fix the problem:
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
status_header( 200 );
//$wp_query->is_404=false; // if necessary
The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
header("HTTP/1.1 200 OK");
header("Status: 200 All rosy");
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
I was following along the Vue documentation at https://vuejs.org/v2/guide/index.html when I ran into this issue.
Later they clarify the syntax:
So far, we’ve only registered components globally, using Vue.component:
Vue.component('my-component-name', { // ... options ... })
Globally registered components can be used in the template of any root Vue instance (new Vue) created afterwards – and even inside all >subcomponents of that Vue instance’s component tree.
(https://vuejs.org/v2/guide/components.html#Organizing-Components)
So as Umesh Kadam says above, just make sure the global component definition comes before the var app = new Vue({})
instantiation.
Here's an example of getting the stack via the traceback module, and printing it:
import traceback
def f():
g()
def g():
for line in traceback.format_stack():
print(line.strip())
f()
# Prints:
# File "so-stack.py", line 10, in <module>
# f()
# File "so-stack.py", line 4, in f
# g()
# File "so-stack.py", line 7, in g
# for line in traceback.format_stack():
If you really only want to print the stack to stderr, you can use:
traceback.print_stack()
Or to print to stdout (useful if want to keep redirected output together), use:
traceback.print_stack(file=sys.stdout)
But getting it via traceback.format_stack()
lets you do whatever you like with it.
It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.
The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?
Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.
Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var keys = Object.keys(myObject);
The above has a full polyfill but a simplified version is:
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
Alternatively replace var getKeys
with Object.prototype.keys
to allow you to call .keys()
on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
Consider also using SETX
- it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET
:
::setting variable for the current user
if not defined My_Var (
set "My_Var=My_Value"
setx My_Var My_Value
)
::setting machine defined variable
if not defined Global_Var (
set "Global_Var=Global_Value"
SetX Global_Var Global_Value /m
)
You can also edit directly the registry values:
User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
Which will allow to avoid some restrictions of SET and SETX like the variables containing =
in their names.
If you instead have a jQuery object you want to render instead of the existing content: Then just reset the content and append the new.
var itemtoReplaceContentOf = $('#regTitle');
itemtoReplaceContentOf.html('');
newcontent.appendTo(itemtoReplaceContentOf);
Or:
$('#regTitle').empty().append(newcontent);
bin/hadoop fs -get /hdfs/source/path /localfs/destination/path
bin/hadoop fs -copyToLocal /hdfs/source/path /localfs/destination/path
namenode_machine:50070
), browse to the file you intend to copy, scroll down the page and click on download the file.If you specify @GET("foobar?a=5")
, then any @Query("b")
must be appended using &
, producing something like foobar?a=5&b=7
.
If you specify @GET("foobar")
, then the first @Query
must be appended using ?
, producing something like foobar?b=7
.
That's how Retrofit works.
When you specify @GET("foobar?")
, Retrofit thinks you already gave some query parameter, and appends more query parameters using &
.
Remove the ?
, and you will get the desired result.
You need a single stream, opened for both reading and writing.
FileStream fileStream = new FileStream(
@"c:\words.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
There is a much easier way to run Java, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.you have to set the tableName you want to your dtimage that is for instance
dtImage.TableName="mydtimage";
if(!ds.Tables.Contains(dtImage.TableName))
ds.Tables.Add(dtImage);
it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage
You could use if type(ele) is dict
or use isinstance(ele, dict)
which would work if you had subclassed dict
:
d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
if isinstance(element, dict):
for k, v in element.items():
print(k,' ',v)
Use getEventListeners in Google Chrome:
getEventListeners(document.getElementByID('btnlogin'));
getEventListeners($('#btnlogin'));
Others ways to do the same is:
el = L[0][0]
m=len(L)
print L == [[el]*m]*m
Or:
first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)
Look at hooking document.onload
or in jQuery $(document).load(...)
.
There is a mistake in your 'andrroid-sdk' folder.
You selected some features while creating new project which need some components to import.
It is needed to download a special android library and place it in android-sdk
folder.
For me it works fine:
1-Create a folder with name extras
in your android-sdk
folder
2-Create a folder with name android
in extras
3-Download this file.(In my case I need this library)
4-Unzip it and copy the content (support folder) in the current android
folder
5-close Eclipse
and start it again
6-create your project again
I hope it to work for you.
That is not always true; it only works in Windows.
For interacting with terminal in putty, Linux shell,... it will be used for returning the cursor to the beginning of line.
following picture shows the usage of that:
Without '\r':
Data comes without '\r' to the putty terminal, it has just '\n'.
it means that data will be printed just in next line.
With '\r':
Data comes with '\r', i.e. string ends with '\r\n'. So the cursor in putty terminal not only will go to the next line but also at the beginning of line
I prefer the Execute via SQL*Plus option. It's in the little down-arrow menu under the "Execute as script" toolbar button.
That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.
Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...
private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
cb.DisplayMember = "Name";
cb.ValueMember = "ItemCode";
cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();
if (!string.IsNullOrEmpty(defVal))
{
var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
if (i>=0) cb.SelectedIndex = i;
}
}
Try using the [StringLength]
attribute:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.
The column of the first matrix and the row of the second matrix should be equal and the order should be like this only
column of first matrix = row of second matrix
and do not follow the below step
row of first matrix = column of second matrix
it will throw an error
A quick definition of the "permanent generation":
"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]
In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space
if an application loads a large number of classes and/or on redeployment).
Note that PermSize
is additional to the -Xmx
value set by the user on the JVM options. But MaxPermSize
allows for the JVM to be able to grow the PermSize
to the amount specified. Initially when the VM is loaded, the MaxPermSize
will still be the default value (32mb for -client
and 64mb for -server
) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize
and MaxPermSize
to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx
setting.
git remote update && git status
Found this on the answer to Check if pull needed in Git
git remote update
to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in master (eg master and origin/master).If you use
-v
withgit remote update
you can see which branches got updated, so you don't really need any further commands.
you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.
new XElement("Foo",
from s in nameValuePairList
select
new XElement("Bar",
new XAttribute("SomeAttr", "SomeAttrValue"),
new XElement("Name", s.Name),
new XElement("Value", s.Value)
)
);
The following function will delete the input character one by one till the input field is empty using PromiseWhile
driver.clearKeys = function(element, value){
return element.getAttribute('value').then(function(val) {
if (val.length > 0) {
return new Promise(function(resolve, reject) {
var len;
len = val.length;
return promiseWhile(function() {
return 0 < len;
}, function() {
return new Promise(function(resolve, reject) {
len--;
return element.sendKeys(webdriver.Key.BACK_SPACE).then(function() {
return resolve(true);
});
});
}).then(function() {
return resolve(true);
});
});
}
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.
// var firstName = 'John'; // Undefined
var lastName = 'Doe';
// if lastName or firstName is undefined, false, null or empty => fallback to empty string
lastName = lastName || '';
firstName = firstName || '';
var displayName = '';
// if lastName (or firstName) is undefined, false, null or empty
// displayName equals 'John' OR 'Doe'
// if lastName and firstName are not empty
// a space is inserted between the names
displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;
// if display name is undefined, false, null or empty => fallback to 'Unnamed'
displayName = displayName || 'Unnamed';
console.log(displayName);
If your click handler is successfully called then this should work:
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
var url = "/Artists/Details?NestId=" + NestId;
window.location.href = url;
})
EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null
, won't cause any exception at all, given that the ModelBinder won't complain about it.
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
you can easily disable any process running on port 80 and then run this command
flask run --host 0.0.0.0 --port 80
or if u prefer running it within the .py file
if __name__ == "__main__":
app.run(host=0.0.0.0, port=80)
You don't even need doubles for this. Just multiply by 100 first and then divide. Otherwise the result would be less than 1 and get truncated to zero, as you saw.
edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.
If you are only concern about showing/hiding, this code would work just fine:
$("#leftDiv").hover(function(){$(this).css("overflow","scroll");},function(){$(this).css("overflow","hidden");});
However, it might modify some elements in your design, in case you are using width=100%, considering that when you hide the scrollbar, it creates a little bit of more room for your width.
In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they're known as sequence
(see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True
Since strings are sequence, you can use slicing
to access parts of the list, denoted by list[start_index:end_index]
see Explain Python's slice notation . For example:
>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]
>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'
When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).
In the olden C days, it's an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array - when to use?
EDIT: As pointed out in recent comments, this solution may BREAK your system.
You most likely don't want to remove python3.
Please refer to the other answers for possible solutions.
Outdated answer (not recommended)
sudo apt-get remove 'python3.*'
To add row to JTable
, one of the ways is:
1) Create table using DefaultTableModel:
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Code");
model.addColumn("Name");
model.addColumn("Quantity");
model.addColumn("Unit Price");
model.addColumn("Price");
JTable table = new JTable(model);
2) To add row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3","Column 4","Column 5"});
There is no annotation to set default value.
You can set default value only on java class level:
public class JavaObject
{
public String notNullMember;
public String optionalMember = "Value";
}
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
break
is used to exit (escape) the for
-loop, while
-loop, switch
-statement that you are currently executing.
return
will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break
nor return
to escape an if-else
-statement per se. They are used to escape other scopes.
Consider the following example. The value of x
inside the while
-loop will determine if the code below the loop will be executed or not:
void f()
{
int x = -1;
while(true)
{
if(x == 0)
break; // escape while() and jump to execute code after the the loop
else if(x == 1)
return; // will end the function f() immediately,
// no further code inside this method will be executed.
do stuff and eventually set variable x to either 0 or 1
...
}
code that will be executed on break (but not with return).
....
}
I have written on this property framework for the last year. It will provide of multiple ways to load properties, and have them strongly typed as well.
Have a look at http://sourceforge.net/projects/jhpropertiestyp/
JHPropertiesTyped will give the developer strongly typed properties. Easy to integrate in existing projects. Handled by a large series for property types. Gives the ability to one-line initialize properties via property IO implementations. Gives the developer the ability to create own property types and property io's. Web demo is also available, screenshots shown above. Also have a standard implementation for a web front end to manage properties, if you choose to use it.
Complete documentation, tutorial, javadoc, faq etc is a available on the project webpage.
Another working solution for IE specific styling is
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
And then your selector
html[data-useragent*='MSIE 10.0'] body .my-class{
margin-left: -0.4em;
}
The whole code if somebody need it.
void alarm(Context context, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
AlarmReceiver mReceiver = new AlarmReceiver();
context.registerReceiver(mReceiver, intentFilter);
Intent anotherIntent = new Intent(SOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}
class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
}
}
It's important to hide the window after showing the message.
func showErrorMessage(_ message: String) {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.cancel, handler: { _ in
alertWindow.isHidden = true
}))
alertWindow.windowLevel = UIWindow.Level.alert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
}
Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.
If you want to prevent double clicking due to a slow responding server side code then this works fine:
<asp:Button ... OnClientClick="this.disabled=true;" UseSubmitBehavior="false" />
Try putting a Threading.Thread.Sleep(5000) on the _Click() event on the server and you will see the button is disabled for the time that the server is processing the click event.
No need for server side code to re-enable the button either!
Make sure upload
plugin implements this.each
in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });
To add to the accepted answer:
Bear in mind that set -e
sometimes is not enough, specially if you have pipes.
For example, suppose you have this script
#!/bin/bash
set -e
./configure > configure.log
make
... which works as expected: an error in configure
aborts the execution.
Tomorrow you make a seemingly trivial change:
#!/bin/bash
set -e
./configure | tee configure.log
make
... and now it does not work. This is explained here, and a workaround (Bash only) is provided:
#!/bin/bash set -e set -o pipefail ./configure | tee configure.log make
Simply difference between Forward
(ServletRequest request, ServletResponse response) and sendRedirect
(String url) is
forward():
forward()
method is executed in the server side.forward ()
method is provided by the servlet container.sendRedirect()
method.RequestDispatcher
interface.sendRedirect():
sendRedirect()
method is executed in the client side.sendRedirect()
method is provided under HTTP
so it can be used only with HTTP
clients.sendRedirect()
method is slower because when new request is created old request object is lost.HttpServletResponse
.This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:
ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
Internet Explorer and Edge do not support some MP4 formats that Chrome does. You can use ffprobe
to see the exact MP4 format. In my case I have these two videos:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf56.40.101
Duration: 00:00:12.10, start: 0.000000, bitrate: 287 kb/s
Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 1000x1000 [SAR 1:1 DAR 1:1], 281 kb/s, 60 fps, 60 tbr, 15360 tbn, 120 tbc (default)
Metadata:
handler_name : VideoHandler
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'b.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf57.66.102
Duration: 00:00:33.83, start: 0.000000, bitrate: 505 kb/s
Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 1280x680, 504 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
Metadata:
handler_name : VideoHandler
Both play fine in Chrome, but the first one fails in IE and Edge. The problem is that IE and Edge don't support yuv444. You can convert to a shittier colourspace like this:
ffmpeg -i input.mp4 -pix_fmt yuv420p output.mp4
I know that people will probably find this very obvious at first, but really think about this. This can often happen if you've done something wrong.
For instance, I've had this problem because I didn't add a host entry to my hosts file. The real problem was DNS resolution. Or I just got the base URL wrong.
Sometimes I get this error if the identity token came from one server, but I'm trying to use it on another.
Sometimes you'll get this error if you've got the resource wrong.
You might get this if you put the CORS middleware too late in the chain.
It is very Simple Just Follow the below step.
Enjoy!!
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
In Select2 version 4 each option has the same properties of the objects in the list;
if you have the object
Obj = {
name: "Alberas",
description: "developer",
birthDate: "01/01/1990"
}
then you retrieve the selected data
var data = $('#id-selected-input').select2('data');
console.log(data[0].name);
console.log(data[0].description);
console.log(data[0].birthDate);
In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.
Either you will
v <- c
)v, ok <- c
)v, ok <- c
)v <- c
)Only the last one technically doesn't read from the channel, but that's of little use.
If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem
instead of -I
.
Similar features exist in clang.
If you're using CMake, you can specify SYSTEM
for include_directories
.
To get the results in excel like file, you have one option to get it done with csv file. Use below commands with provided options.
jmeter -n -t /path-to-jmeter-test/file.jmx -l TestResults.csv
-n states Non GUI mode
-t states Test JMX File
-l state Log the results in provided file
Also you can pass any results related parameters dynamically in command line arguments using -Jprop.name=value which are already defined in jmeter.properties in bin folder.
Function overloading
- functions with same name, but different number of arguments
Function overriding
- concept of inheritance. Functions with same name and same number of arguments. Here the second function is said to have overridden the first
To iterate through all files and folders you can use
for /F "delims=" %%a in ('dir /b /s') do echo %%a
To iterate through all folders only not with files, then you can use
for /F "delims=" %%a in ('dir /a:d /b /s') do echo %%a
Where /s
will give all results throughout the directory tree in unlimited depth. You can skip /s
if you want to iterate through the content of that folder not their sub folder
To iterate through a particular named files and folders you can search for the name and iterate using for loop
for /F "delims=" %%a in ('dir "file or folder name" /b /s') do echo %%a
To iterate through a particular named folders/directories and not files, then use /AD
in the same command
for /F "delims=" %%a in ('dir "folder name" /b /AD /s') do echo %%a
Create a drawable resource what background you need, in my case I named it bg_custom_progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<item>
<shape android:shape="rectangle" >
<corners android:radius="5dp"/>
<gradient
android:angle="180"
android:endColor="#DADFD6"
android:startColor="#AEB9A3" />
</shape>
</item>
<item>
<clip>
<shape android:shape="rectangle" >
<corners android:radius="5dp" />
<gradient
android:angle="180"
android:endColor="#44CF4A"
android:startColor="#2BB930" />
</shape>
</clip>
</item>
<item>
<clip>
<shape android:shape="rectangle" >
<corners android:radius="5dp" />
<gradient
android:angle="180"
android:endColor="#44CF4A"
android:startColor="#2BB930" />
</shape>
</clip>
</item>
Then use this custom background like
<ProgressBar
android:id="@+id/progressBarBarMenuHome"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="6dp"
android:indeterminate="false"
android:max="100"
android:minWidth="200dp"
android:minHeight="50dp"
android:progress="10"
android:progressDrawable="@drawable/bg_custom_progressbar" />
Its works fine for me
On PostgreSQL manual
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.
I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
When do we use AtomicReference?
AtomicReference is flexible way to update the variable value atomically without use of synchronization.
AtomicReference
support lock-free thread-safe programming on single variables.
There are multiple ways of achieving Thread safety with high level concurrent API. Atomic variables is one of the multiple options.
Lock
objects support locking idioms that simplify many concurrent applications.
Executors
define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
Provide a simple example where AtomicReference should be used.
Sample code with AtomicReference
:
String initialReference = "value 1";
AtomicReference<String> someRef =
new AtomicReference<String>(initialReference);
String newReference = "value 2";
boolean exchanged = someRef.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);
Is it needed to create objects in all multithreaded programs?
You don't have to use AtomicReference
in all multi threaded programs.
If you want to guard a single variable, use AtomicReference
. If you want to guard a code block, use other constructs like Lock
/synchronized
etc.
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.
Without any jQuery:
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
console.log(decodeEntities('1 & 2')); // '1 & 2'
_x000D_
This works similarly to the accepted answer, but is safe to use with untrusted user input.
As noted by Mike Samuel, doing this with a <div>
instead of a <textarea>
with untrusted user input is an XSS vulnerability, even if the <div>
is never added to the DOM:
function decodeEntities(encodedString) {_x000D_
var div = document.createElement('div');_x000D_
div.innerHTML = encodedString;_x000D_
return div.textContent;_x000D_
}_x000D_
_x000D_
// Shows an alert_x000D_
decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">')
_x000D_
However, this attack is not possible against a <textarea>
because there are no HTML elements that are permitted content of a <textarea>
. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
// Safe, and returns the correct answer_x000D_
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))
_x000D_
Warning: Doing this using jQuery's
.html()
and.val()
methods instead of using.innerHTML
and.value
is also insecure* for some versions of jQuery, even when using atextarea
. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to.html()
. Hence code like this shows an alert in jQuery 1.8:
//<!-- CDATA_x000D_
// Shows alert_x000D_
$("<textarea>")_x000D_
.html("<script>alert(1337);</script>")_x000D_
.text();_x000D_
_x000D_
//-->
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
_x000D_
* Thanks to Eru Penkman for catching this vulnerability.
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
From http://developer.android.com/reference/android/app/Activity.html
public final void showDialog (int id) Added in API level 1
This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.
Why
How to solve?
More
I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp
Quoting Mr Initial Man from here:
Instead of this:
<div id="Top" class="info"></div><a href="#" class="a_info"></a>
Use this:
<span id="Top" class="info"></span><a href="#" class="a_info"></a>
Also, you could use this:
<div id="Top" class="info"><a href="#" class="a_info"></a></div>
And gostbustaz:
If you absoultely must use a
<div>
, you can setdiv { display: inline; }
in your stylesheet.
Of course, that essentially makes the
<div>
a<span>
.
I used maxlength and minlength with or without required
and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
_x000D_
`
If you are seeing this issue with IIS hosting, but not when F5 debugging, try creating a new application in IIS.
This fixed it for me. (windows 10) In the end i deleted the "bad" IIS application and re-created an identical one with the same name.
Better is use datatype varchar(15)
.
How about:
SELECT * FROM sometable WHERE CHAR_LENGTH(LINK) > 1
Here's the MySql string functions page (5.0).
Note that I chose CHAR_LENGTH
instead of LENGTH
, as if there are multibyte characters in the data you're probably really interested in how many characters there are, not how many bytes of storage they take. So for the above, a row where LINK is a single two-byte character wouldn't be returned - whereas it would when using LENGTH
.
Note that if LINK
is NULL
, the result of CHAR_LENGTH(LINK)
will be NULL
as well, so the row won't match.
youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
DECLARE @MyFloat [float]
SET @MyFloat = 1000109360.050
SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')
It sets the distance of the inset between the content view and the enclosing scroll view.
Obj-C
aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);
Swift 5.0
aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)
Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:
_|?_cW_?_|_?_
| |
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
_|_______|___
?
(cH = contentSize.height; cW = contentSize.width)
The scroll view encloses the content view plus whatever padding is provided by the specified content insets.
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
The line would be as shown below:
Dim x As Integer
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value
Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.
if your values are strings, here are some examples for bad hash functions:
string[0]
- the ASCII characters a-Z are way more often then othersstring.lengh()
- the most probable value is 1Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.
I had this problem connecting to http://sdf.org through Mac OS X Lion. I changed under Terminal Preferences
(?+,) > Advanced
pane, Declare Terminal as
to VT-100
.
I also marked Delete Sends Ctrl-H
because this Mac connection was confusing zsh
.
It appears to be working for my use case.
I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;
.
$(window).on("load",function() {
function fade() {
var animation_height = $(window).innerHeight() * 0.25;
var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;
$('.fade').each(function() {
var objectTop = $(this).offset().top;
var windowBottom = $(window).scrollTop() + $(window).innerHeight();
if ( objectTop < windowBottom ) {
if ( objectTop < windowBottom - animation_height ) {
$(this).html( 'fully visible' );
$(this).css( {
transition: 'opacity 0.1s linear',
opacity: 1
} );
} else {
$(this).html( 'fading in/out' );
$(this).css( {
transition: 'opacity 0.25s linear',
opacity: (windowBottom - objectTop) * ratio
} );
}
} else {
$(this).html( 'not visible' );
$(this).css( 'opacity', 0 );
}
});
}
$('.fade').css( 'opacity', 0 );
fade();
$(window).scroll(function() {fade();});
});
See it here: http://jsfiddle.net/78xjLnu1/16/
Cheers, Martin
<!-- One simple solution to your problem could be like this: -->
<div>
<input type="text" id="fname" onmousemove="javascript: alert(this.id);" />
<!-- OR -->
<input type="text" id="fname" onclick="javascript: alert(this.id);" />
</div>
<!-- Both mousemove over the field & click on the field displays "fname"-->
<!-- Works fantastic in IE, FireFox, Chrome, Opera. -->
<!-- I didn't test it for Safari. -->
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:@"%ld", year];
System.out.println("\"Hello\"")
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
The font tag has been deprecated for some time now.
That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.
And as @Alex H said, you should be using CSS for this.
You'll find that instances of list
do not provide a __hash__
--rather, that attribute of each list is actually None
(try print [].__hash__
). Thus, list
is unhashable.
The reason your code works with list
and not set
is because set
constructs a single set of items without duplicates, whereas a list can contain arbitrary data.
Use 'Exists' which returns either 0 or 1.
The query will be like:
SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
If you want a permanent solution for wordwrapping lines, go to menu File → Preference → Settings and change editor.wordWrap: "on"
. This will apply always.
However, we usually keep changing our preference to check code. So, I use the Alt + Z key to wrap written code of a file or you can go to menu View → Toggle Word Wrap. This applies whenever you want not always. And again Alt + Z to undo wordwrap (will show the full line in one line).
You can use tool dpkg for managing packages in Debian operating system.
dpkg --get-selections | grep mysql
if it's listed as installed, you got it. Else you need to get it.
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
Another way to add a default namespace to an XML Document before feeding it to JAXB is to use JDom:
Like this:
public class XMLObjectFactory {
private static Namespace DEFAULT_NS = Namespace.getNamespace("http://tempuri.org/");
public static Object createObject(InputStream in) {
try {
SAXBuilder sb = new SAXBuilder(false);
Document doc = sb.build(in);
setNamespace(doc.getRootElement(), DEFAULT_NS, true);
Source src = new JDOMSource(doc);
JAXBContext context = JAXBContext.newInstance("org.tempuri");
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement root = unmarshaller.unmarshal(src);
return root.getValue();
} catch (Exception e) {
throw new RuntimeException("Failed to create Object", e);
}
}
private static void setNamespace(Element elem, Namespace ns, boolean recurse) {
elem.setNamespace(ns);
if (recurse) {
for (Object o : elem.getChildren()) {
setNamespace((Element) o, ns, recurse);
}
}
}
You may use also
select * from pg_tables where schemaname = 'information_schema'
In generall pg* tables allow you to see everything in the db, not constrained to your permissions (if you have access to the tables of course).
you want to print something in for loop right;but you don't want it print in new line every time.. for example:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print "hi"
Example:
for i in range (0,5):
print "hi",
OUTPUT:
hi hi hi hi hi
Just a newbie here, but I was abble to make it work in a ui.bootstrap.modal with this directive:
directives.directive('focus', function($timeout) {
return {
link : function(scope, element) {
scope.$watch('idToFocus', function(value) {
if (value === element[0].id) {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});
and in the $modal.open method I used the folowing to indicate the element where the focus should be putted:
var d = $modal.open({
controller : function($scope, $modalInstance) {
...
$scope.idToFocus = "cancelaAteste";
}
...
});
on the template I have this:
<input id="myInputId" focus />
Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?
def key_for_value(d, value):
"""Return a key in `d` having a value of `value`."""
for k, v in d.iteritems():
if v == value:
return k
Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.
If you need to do this frequently, it would make sense to construct the reverse dictionary:
d_rev = dict(v,k for k,v in d.iteritems())
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
Expanding upon Gustavo Lima's answer. The same thing can be done without creating an entirely new list. The values in the list can be replaced with the differentials as the FOR
loop progresses.
def f_ClosestVal(v_List, v_Number):
"""Takes an unsorted LIST of INTs and RETURNS INDEX of value closest to an INT"""
for _index, i in enumerate(v_List):
v_List[_index] = abs(v_Number - i)
return v_List.index(min(v_List))
myList = [1, 88, 44, 4, 4, -2, 3]
v_Num = 5
print(f_ClosestVal(myList, v_Num)) ## Gives "3," the index of the first "4" in the list.
for a complete offline android studio 3.5.0 installation - you need to download all these below components
android studio, gradle, android gradle plugin and sdk.
here is a detailed step by step Stackoverflow answer for the question
Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees
Here is how to set variables in the package from code -
using Microsoft.SqlServer.Dts.Runtime;
private void Execute_Package()
{
string pkgLocation = @"c:\test.dtsx";
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["A_Variable"].Value = "Some value";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
Console.WriteLine("Package ran successfully");
else
Console.WriteLine("Package failed");
}
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
What you're trying to do sounds dangerous, as that's not the intended use of AUTO_INCREMENT
.
If you really want to find the lowest unused key value, don't use AUTO_INCREMENT
at all, and manage your keys manually. However, this is NOT a recommended practice.
Take a step back and ask "why you need to recycle key values?" Do unsigned INT
(or BIGINT
) not provide a large enough key space?
Are you really going to have more than 18,446,744,073,709,551,615
unique records over the course of your application's lifetime?
This worked for me:
For the HTML, add the required
attribute to the input element
<input class="my-input-element" type="text" placeholder="" required />
For the CSS, use the :invalid
selector to target the empty input
input.my-input-element:invalid {
}
Notes:
required
from w3Schools.com:
"When present, it specifies that an input field must be filled out before submitting the form."An index is used to speed up searching in the database. MySQL have some good documentation on the subject (which is relevant for other SQL servers as well): http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
An index can be used to efficiently find all rows matching some column in your query and then walk through only that subset of the table to find exact matches. If you don't have indexes on any column in the WHERE
clause, the SQL
server has to walk through the whole table and check every row to see if it matches, which may be a slow operation on big tables.
The index can also be a UNIQUE
index, which means that you cannot have duplicate values in that column, or a PRIMARY KEY
which in some storage engines defines where in the database file the value is stored.
In MySQL you can use EXPLAIN
in front of your SELECT
statement to see if your query will make use of any index. This is a good start for troubleshooting performance problems. Read more here:
http://dev.mysql.com/doc/refman/5.0/en/explain.html
As many others have already stated, it really depends on the use case if a Pair class is useful or not.
I think for a private helper function it is totally legitimate to use a Pair class if that makes your code more readable and is not worth the effort of creating yet another value class with all its boiler plate code.
On the other hand, if your abstraction level requires you to clearly document the semantics of the class that contains two objects or values, then you should write a class for it. Usually that's the case if the data is a business object.
As always, it requires skilled judgement.
For your second question I recommend the Pair class from the Apache Commons libraries. Those might be considered as extended standard libraries for Java:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
You might also want to have a look at Apache Commons' EqualsBuilder, HashCodeBuilder and ToStringBuilder which simplify writing value classes for your business objects.
Main Activity
public class MainActivity extends Activity {
EditText user, password;
Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user = (EditText) findViewById(R.id.username_edit);
password = (EditText) findViewById(R.id.edit_password);
login = (Button) findViewById(R.id.btnSubmit);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Second.class);
String uservalue = user.getText().toString();
String name_value = password.getText().toString();
String password_value = password.getText().toString();
intent.putExtra("username", uservalue);
intent.putExtra("password", password_value);
startActivity(intent);
}
});
}
}
Second Activity in which you want to receive Data
public class Second extends Activity{
EditText name, pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
name = (EditText) findViewById(R.id.editText1);
pass = (EditText) findViewById(R.id.editText2);
String value = getIntent().getStringExtra("username");
String pass_val = getIntent().getStringExtra("password");
name.setText(value);
pass.setText(pass_val);
}
}
Enhancement on the accepted answer by @afonsoduarte.
in case you are using bootstrap
Providing width:100%
on the style.
This is helpful if you are using bootstrap and want the image to stretch all the available width.
Specifying the height
property is optional, You can remove/keep it as you need
.cover {
object-fit: cover;
width: 100%;
/*height: 300px; optional, you can remove it, but in my case it was good */
}
By the way, there is NO need to provide the height
and width
attributes on the image
element because they will be overridden by the style.
so it is enough to write something like this.
<img class="cover" src="url to img ..." />
Major advantage :
ViewHolder
is not available by default in ListView
. We will be creating explicitly inside the getView()
.
RecyclerView
has inbuilt Viewholder
.
If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well. http://www.wingware.com/
You could try using :placeholder-shown...
input {
padding: 10px 15px;
font-size: 16px;
border-radius: 5px;
border: 2px solid lightblue;
outline: 0;
font-weight:bold;
transition: border-color 200ms;
font-family: sans-serif;
}
.validation {
opacity: 0;
font-size: 12px;
font-family: sans-serif;
color: crimson;
transition: opacity;
}
input:required:valid {
border-color: forestgreen;
}
input:required:invalid:not(:placeholder-shown) {
border-color: crimson;
}
input:required:invalid:not(:placeholder-shown) + .validation {
opacity: 1;
}
_x000D_
<input type="email" placeholder="e-mail" required>
<div class="validation">Not valid</span>
_x000D_
no great support though... caniuse
1- install exuberant ctags. If you're using osx, this article shows a little trick: http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html
2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:
ctags -R
This will create a "tags" file for you.
3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:
ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`
credit: https://coderwall.com/p/lv1qww (Note that I omitted the -e option which generates tags for emacs instead of vim)
4- Add the following line to your ~/.vimrc
set autochdir
set tags+=./tags;
(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )
5- Go to the word you'd like to follow and hit ctrl + ]
; if you'd like to go back, use ctrl+o
(source: https://stackoverflow.com/a/53929/226255)
Use character classes. A character class beginning with caret will match anything not in the class.
[^,;]
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
I made a script and published it at GitHub: get selectFile.js Easy to use, feel free to clone.
HTML
<input type=file hidden id=choose name=choose>
<input type=button onClick=getFile.simulate() value=getFile>
<label id=selected>Nothing selected</label>
JS
var getFile = new selectFile;
getFile.targets('choose','selected');
DEMO
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
This should work
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
verify(bar).DoStuff(any(Foo[].class));
You need to search for OWNER_NAME.
cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u
cat -v turn the dumpfile into visible text.
grep -o shows only the match so we don't see really long lines
uniq -u removes duplicate lines so you see less output.
This works pretty well, even on large dump files, and could be tweaked for usage in a script.
const countryResolver = (data = [{}]) => {
const countrySelecter = document.createElement('select');
countrySelecter.className = `custom-select`;
countrySelecter.id = `countrySelect`;
countrySelecter.setAttribute("aria-label", "Example select with button addon");
let opt = document.createElement("option");
opt.text = "Select language";
opt.disabled = true;
countrySelecter.add(opt, null);
let i = 0;
for (let item of data) {
let opt = document.createElement("option");
opt.value = item.Id;
opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
countrySelecter.add(opt, null);
}
return countrySelecter;
};
This question is an old one, but it shows up at the top of Google when searching for how to run a single test. I don't know if it's a recent addition, but to run a single test out of a spec you can do the following:
rspec path/to/spec:<line number>
where -line number- is a line number that contains part of your test. For example, if you had a spec like:
1:
2: it "should be awesome" do
3: foo = 3
4: foo.should eq(3)
5: end
6:
Let's say it's saved in spec/models/foo_spec.rb. Then you would run:
rspec spec/models/foo_spec.rb:2
and it would just run that one spec. In fact, that number could be anything from 2 to 5.
Hope this helps!
First of all, checked
can have a value of checked
, or an empty string.
$("input:checkbox").uniform();
$('#check1').live('click', function() {
$('#check2').attr('checked', 'checked').uniform();
});
In Java using an additional String (with StringBuilder):
public static final String reverseWordsWithAdditionalStorage(String string) {
StringBuilder builder = new StringBuilder();
char c = 0;
int index = 0;
int last = string.length();
int length = string.length()-1;
StringBuilder temp = new StringBuilder();
for (int i=length; i>=0; i--) {
c = string.charAt(i);
if (c == SPACE || i==0) {
index = (i==0)?0:i+1;
temp.append(string.substring(index, last));
if (index!=0) temp.append(c);
builder.append(temp);
temp.delete(0, temp.length());
last = i;
}
}
return builder.toString();
}
In Java in-place:
public static final String reverseWordsInPlace(String string) {
char[] chars = string.toCharArray();
int lengthI = 0;
int lastI = 0;
int lengthJ = 0;
int lastJ = chars.length-1;
int i = 0;
char iChar = 0;
char jChar = 0;
while (i<chars.length && i<=lastJ) {
iChar = chars[i];
if (iChar == SPACE) {
lengthI = i-lastI;
for (int j=lastJ; j>=i; j--) {
jChar = chars[j];
if (jChar == SPACE) {
lengthJ = lastJ-j;
swapWords(lastI, i-1, j+1, lastJ, chars);
lastJ = lastJ-lengthI-1;
break;
}
}
lastI = lastI+lengthJ+1;
i = lastI;
} else {
i++;
}
}
return String.valueOf(chars);
}
private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) {
int lengthA = endA-startA+1;
int lengthB = endB-startB+1;
int length = lengthA;
if (lengthA>lengthB) length = lengthB;
int indexA = 0;
int indexB = 0;
char c = 0;
for (int i=0; i<length; i++) {
indexA = startA+i;
indexB = startB+i;
c = array[indexB];
array[indexB] = array[indexA];
array[indexA] = c;
}
if (lengthB>lengthA) {
length = lengthB-lengthA;
int end = 0;
for (int i=0; i<length; i++) {
end = endB-((length-1)-i);
c = array[end];
shiftRight(endA+i,end,array);
array[endA+1+i] = c;
}
} else if (lengthA>lengthB) {
length = lengthA-lengthB;
for (int i=0; i<length; i++) {
c = array[endA];
shiftLeft(endA,endB,array);
array[endB+i] = c;
}
}
}
private static final void shiftRight(int start, int end, char[] array) {
for (int i=end; i>start; i--) {
array[i] = array[i-1];
}
}
private static final void shiftLeft(int start, int end, char[] array) {
for (int i=start; i<end; i++) {
array[i] = array[i+1];
}
}
I think onRestart() works better for this.
@Override
public void onRestart() {
super.onRestart();
//When BACK BUTTON is pressed, the activity on the stack is restarted
//Do what you want on the refresh procedure here
}
You could code what you want to do when the Activity is restarted (called again from the event 'back button pressed') inside onRestart().
For example, if you want to do the same thing you do in onCreate(), paste the code in onRestart() (eg. reconstructing the UI with the updated values).
You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.
I had a similar problem and it turned out the issue was having both versions 6 & 7 of OpenJDK. The answer comes from r-senior on ubuntu forums (http://ubuntuforums.org/showthread.php?t=1977619) --- just uninstall version 6:
sudo apt-get remove openjdk-6-*
make sure that JAVA_HOME and CLASSPATH aren't set to anything since that isn't actually the problem.
I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.
So make your query the following:
# vv or Job.find(1) vv
attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
# or
Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })
And then partition the data:
@logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }
That will get the data you're after in a neat and efficient manner.
for python3 user, install python3-tk package by following command
sudo apt-get install python3-tk
A neat alternative that is much more readable in my opinion, however, arguably a tad less efficient due to the conversions between double and String:
double num = 540.512;
double sum = 1978.8;
// NOTE: This does take care of rounding
String str = String.format("%.1f", (num/sum) * 100.0);
If you want the answer as a double, you could of course convert it back:
double ans = Double.parseDouble(str);
I figured out such data design:
Main sheet: Column A: Pump codes (numbers)
Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'
=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)
Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.
Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B
=INDIRECT("Ruhrpumpen!A"&$B2)
Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:
=INDIRECT("Ruhrpumpen!B"&$B2)
Sheet 'Ruhrpumpen':
Column A: some data about a certain pump
Column B: some more data
Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.
Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
If you want your PATH variable to correctly update based on your current working directory, add this to the end of your .bashrc
-equivalent (or after anything that defines PATH
):
__OLD_PATH=$PATH
function updatePATHForNPM() {
export PATH=$(npm bin):$__OLD_PATH
}
function node-mode() {
PROMPT_COMMAND=updatePATHForNPM
}
function node-mode-off() {
unset PROMPT_COMMAND
PATH=$__OLD_PATH
}
# Uncomment to enable node-mode by default:
# node-mode
This may add a short delay every time the bash prompt gets rendered (depending on the size of your project, most likely), so it's disabled by default.
You can enable and disable it within your terminal by running node-mode
and node-mode-off
, respectively.
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.
You can create your mask array in one step like this
mask_data = input_mask_data < 3
This creates a boolean array which can then be used as a pixel mask. Note that we haven't changed the input array (as in your code) but have created a new array to hold the mask data - I would recommend doing it this way.
>>> input_mask_data = np.random.randint(0, 5, (3, 4))
>>> input_mask_data
array([[1, 3, 4, 0],
[4, 1, 2, 2],
[1, 2, 3, 0]])
>>> mask_data = input_mask_data < 3
>>> mask_data
array([[ True, False, False, True],
[False, True, True, True],
[ True, True, False, True]], dtype=bool)
>>>
I have faced same problem and It will resolve this issue in all android versions
private void setCookie() {
try {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setCookie(Constant.BASE_URL, getCookie(), value -> {
String cookie = cookieManager.getCookie(Constant.BASE_URL);
CookieManager.getInstance().flush();
CustomLog.d("cookie", "cookie ------>" + cookie);
setupWebView();
});
} else {
cookieManager.setCookie(webUrl, getCookie());
new Handler().postDelayed(this::setupWebView, 700);
CookieSyncManager.getInstance().sync();
}
} catch (Exception e) {
CustomLog.e(e);
}
}
All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.
You can do the simple join case with
Joiner.on(" and ").join(names)
but also easily deal with nulls:
Joiner.on(" and ").skipNulls().join(names);
or
Joiner.on(" and ").useForNull("[unknown]").join(names);
and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:
Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35
which is extremely useful for debugging etc.
This works for me in iOS 9.3.x with Swift:
override func didMoveToParentViewController(parent: UIViewController?) {
super.didMoveToParentViewController(parent)
if parent == self.navigationController?.parentViewController {
print("Back tapped")
}
}
Unlike other solutions here, this doesn't seem to trigger unexpectedly.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".
I know this is an old question, but it seems to me that none of these answers seem to answer the question being asked so hopefully this will help someone in the future.
Yes you can always show 2 decimal places, but unfortunately it can't be done with the element attributes alone, you have to use JavaScript.
I should point out this isn't ideal for large numbers as it will always force the trailing zeros, so the user will have to move the cursor back instead of deleting characters to set a value greater than 9.99
//Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows_x000D_
$('.trailing-decimal-input').on('keyup mouseup', function (e) {_x000D_
_x000D_
// on keyup check for backspace & delete, to allow user to clear the input as required_x000D_
var key = e.keyCode || e.charCode;_x000D_
if (key == 8 || key == 46) {_x000D_
return false;_x000D_
};_x000D_
_x000D_
// get the current input value_x000D_
let correctValue = $(this).val().toString();_x000D_
_x000D_
//if there is no decimal places add trailing zeros_x000D_
if (correctValue.indexOf('.') === -1) {_x000D_
correctValue += '.00';_x000D_
}_x000D_
_x000D_
else {_x000D_
_x000D_
//if there is only one number after the decimal add a trailing zero_x000D_
if (correctValue.toString().split(".")[1].length === 1) {_x000D_
correctValue += '0'_x000D_
}_x000D_
_x000D_
//if there is more than 2 decimal places round backdown to 2_x000D_
if (correctValue.toString().split(".")[1].length > 2) {_x000D_
correctValue = parseFloat($(this).val()).toFixed(2).toString();_x000D_
}_x000D_
}_x000D_
_x000D_
//update the value of the input with our conditions_x000D_
$(this).val(correctValue);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="0.00" />
_x000D_
You haven't specified the database. If it is one that allows analytical functions it may be faster to use this approach than the GROUP BY one(definitely faster in Oracle, most likely faster in the late SQL Server editions, don't know about others).
Syntax in SQL Server would be:
SELECT c.*, p.*
FROM customer c INNER JOIN
(SELECT RANK() OVER (PARTITION BY customer_id ORDER BY date DESC) r, *
FROM purchase) p
ON (c.id = p.customer_id)
WHERE p.r = 1
<p>Please click in the following {{link}} to verify the account</p>
function renderHTML(templatePath: string, object) {
const template = fileSystem.readFileSync(path.join(Application.staticDirectory, templatePath + '.html'), 'utf8');
return template.match(/\{{(.*?)\}}/ig).reduce((acc, binding) => {
const property = binding.substring(2, binding.length - 2);
return `${acc}${template.replace(/\{{(.*?)\}}/, object[property])}`;
}, '');
}
renderHTML(templateName, { link: 'SomeLink' })
for sure you can improve the reading template function to read as stream and compose the bytes by line to make it more efficient
You need add masksToBounds = true
for combined between corderRadius
shadowRadius
.
button.layer.masksToBounds = false;
This handles not only accents, but also "strokes" (as in ø etc.):
import unicodedata as ud
def rmdiacritics(char):
'''
Return the base character of char, by "removing" any
diacritics like accents or curls and strokes and the like.
'''
desc = ud.name(char)
cutoff = desc.find(' WITH ')
if cutoff != -1:
desc = desc[:cutoff]
try:
char = ud.lookup(desc)
except KeyError:
pass # removing "WITH ..." produced an invalid name
return char
This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed. In fact, it's more of a hack, as pointed out in comments, since Unicode names are – really just names, they give no guarantee to be consistent or anything.
There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.
Incorporated suggestions from the comments (handling lookup errors, Python-3 code).
//By each()
var testval = [];
$('.hobbies_class:checked').each(function() {
testval.push($(this).val());
});
//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");
//HTML Code
<input type="checkbox" value="cricket" name="hobbies[]" class="hobbies_class">Cricket
<input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey
Example
Demo
you can create a link ln -s nodejs
node in /usr/bin
hope this solves your problem.
Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.
Use pymysql. It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies. This makes the installation process on all operating systems consistent and easy. pymysql
is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - PTSD from installing MySQLDb on Mac OSX and *Nix systems
, but that's just me.
Installation
pip install pymysql
That's it... you are ready to play.
Example usage from pymysql Github repo
import pymysql.cursors
import pymysql
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('[email protected]',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
ALSO - Replace MySQLdb in existing code quickly and transparently
If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:
# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
All subsequent references to MySQLdb will use pymysql transparently.
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
Another way to do it in async function :
const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()
// Create.R.U.D
router.post('/new-order', async function (req, res, next) {
// security check
if (Object.keys(req.body).length === 0) {
res.status(404).send({
msg: "Error",
code: 404
});
return;
}
try {
// operations
let orderNumber = await db.collection('orders').countDocuments()
let number = orderNumber + 1
let order = {
number: number,
customer: req.body.customer,
products: req.body.products,
totalProducts: req.body.totalProducts,
totalCost: req.body.totalCost,
type: req.body.type,
time: req.body.time,
date: req.body.date,
timeStamp: Date.now(),
}
if (req.body.direction) {
order.direction = req.body.direction
}
if (req.body.specialRequests) {
order.specialRequests = req.body.specialRequests
}
// Here newOrder will store some informations in result of this process.
// You can find the inserted id and some informations there too.
let newOrder = await db.collection('orders').insertOne({...order})
if (newOrder) {
// MARK: Server response
res.status(201).send({
msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
code: 201
});
} else {
// MARK: Server response
res.status(404).send({
msg: `Order N°${number} not created`,
code: 404
});
}
} catch (e) {
print(e)
return
}
})
// C.Read.U.D
// C.R.Update.D
// C.R.U.Delete
module.exports = router;
If someone is having trouble with installing php-mbstring
package in ubuntu do following
sudo apt-get install libapache2-mod-php5
add layout_gravity="center"
or "center_horizontal"
to the parent layout.
On a side note, your LinearLayout
inside your TableRow
seems un-necessary, as a TableRow
is already an horizontal LinearLayout
.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
In the new alpha versions they've introduced utility spacing classes. The structure can then be tweaked if you use them in a clever way.
Spacing utility classes
<div class="container-fluid">
<div class="row">
<div class="col-sm-4 col-md-3 pl-0">…</div>
<div class="col-sm-4 col-md-3">…</div>
<div class="col-sm-4 col-md-3">…</div>
<div class="col-sm-4 col-md-3 pr-0">…</div>
</div>
</div>
pl-0
and pr-0
will remove leading and trailing padding from the columns.
One issue left is the embedded rows of a column, as they still have negative margin. In this case:
<div class="col-sm-12 col-md-6 pl-0">
<div class="row ml-0">
</div>
Version differences
Also note the utility spacing classes were changed since version 4.0.0-alpha.4
.
Before they were separated by 2 dashes e.g. => p-x-0
and p-l-0
and so on ...
To stay on topic for the version 3: This is what I use on Bootstrap 3 projects and include the compass setup, for this particular spacing utility, into bootstrap-sass
(version 3) or bootstrap
(version 4.0.0-alpha.3) with double dashes or bootstrap
(version 4.0.0-alpha.4 and up) with single dashes.
Also, latest version(s) go up 'till 5 times a ratio (ex: pt-5
padding-top 5) instead of only 3.
Compass
$grid-breakpoints: (xs: 0, sm: 576px, md: 768px, lg: 992px, xl: 1200px) !default;
@import "../scss/mixins/breakpoints"; // media-breakpoint-up, breakpoint-infix
@import "../scss/utilities/_spacing.scss";
CSS output
You can ofcourse always copy/paste the padding spacing classes only from a generated css file.
.p-0 { padding: 0 !important; }
.pt-0 { padding-top: 0 !important; }
.pr-0 { padding-right: 0 !important; }
.pb-0 { padding-bottom: 0 !important; }
.pl-0 { padding-left: 0 !important; }
.px-0 { padding-right: 0 !important; padding-left: 0 !important; }
.py-0 { padding-top: 0 !important; padding-bottom: 0 !important; }
.p-1 { padding: 0.25rem !important; }
.pt-1 { padding-top: 0.25rem !important; }
.pr-1 { padding-right: 0.25rem !important; }
.pb-1 { padding-bottom: 0.25rem !important; }
.pl-1 { padding-left: 0.25rem !important; }
.px-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; }
.py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }
.p-2 { padding: 0.5rem !important; }
.pt-2 { padding-top: 0.5rem !important; }
.pr-2 { padding-right: 0.5rem !important; }
.pb-2 { padding-bottom: 0.5rem !important; }
.pl-2 { padding-left: 0.5rem !important; }
.px-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; }
.py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }
.p-3 { padding: 1rem !important; }
.pt-3 { padding-top: 1rem !important; }
.pr-3 { padding-right: 1rem !important; }
.pb-3 { padding-bottom: 1rem !important; }
.pl-3 { padding-left: 1rem !important; }
.px-3 { padding-right: 1rem !important; padding-left: 1rem !important; }
.py-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; }
.p-4 { padding: 1.5rem !important; }
.pt-4 { padding-top: 1.5rem !important; }
.pr-4 { padding-right: 1.5rem !important; }
.pb-4 { padding-bottom: 1.5rem !important; }
.pl-4 { padding-left: 1.5rem !important; }
.px-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; }
.py-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; }
.p-5 { padding: 3rem !important; }
.pt-5 { padding-top: 3rem !important; }
.pr-5 { padding-right: 3rem !important; }
.pb-5 { padding-bottom: 3rem !important; }
.pl-5 { padding-left: 3rem !important; }
.px-5 { padding-right: 3rem !important; padding-left: 3rem !important; }
.py-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; }
You may be overcomplicating things, is there any reason you need the stringr package?
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, "%m/%d/%Y %H:%M:%S")
[1] "2009-10-09" "2009-10-15"
More generally and if you need the time component as well, use strptime:
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
If it has been staged and committed, then the following will reset the file:
git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path
This will work for a deletion that occurred several commits previous.