This is based on the other answers, but is exactly what I was after:
(Get-Command C:\Path\YourFile.Dll).FileVersionInfo.FileVersion
Using Powershell it is possible to get just the Version string, i.e. 2.3.4 from any dll or exe with the following command
(Get-Item "C:\program files\OpenVPN\bin\openvpn.exe").VersionInfo.ProductVersion
Tested on Windows 10
That URL will points to your own server-side file upload action. The documentation doesn't go into much detail, but fortunately Don Jones fills in some of the blanks here:
How can you integrate a custom file browser/uploader with CKEditor?
See also:
http://zerokspot.com/weblog/2009/09/09/custom-filebrowser-callbacks-ckeditor/
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
localStorage
only supports strings. Use JSON.stringify()
and JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
For an Omnibus install, it is a little different.
The correct place in an Omnibus install is:
/etc/gitlab/gitlab.rb
external_url 'http://gitlab.example.com'
Finally, you'll need to execute sudo gitlab-ctl reconfigure
and sudo gitlab-ctl restart
so the changes apply.
I was making changes in the wrong places and they were getting blown away.
The incorrect paths are:
/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf
Pay attention to those warnings that read:
# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.
I'm using Kotlin here
Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example
var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
strwrt=FileWriter(File("sdcard/${NamaFile}"))
strwrt.write(teks)
strwrt.close()
after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.
It sounds like you are doing everything exactly as the client credential section of the Subversion book suggests. The only thing I can think of is that the server isn't asking for the username and password because is getting it from somewhere else.
try this javascript:
function checkTextAreaMaxLength(textBox,e, length)
{
var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;
var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...)
in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index
). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController
and an action method inside of it called DoSomething
, then the expected default url ExampleController/DoSomething
will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething
action of the ExampleController
class will be mapped to the url hey/now
. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
Give the submit buttons for both forms different names and use PHP to check which button has submitted data.
Form one button - btn1 Form two button -btn2
PHP Code:
if($_POST['btn1']){
//Login
}elseif($_POST['btn2']){
//Register
}
This error is usually caused by running a command from a directory that no longer exist.
Try changing your directory and re-run the command.
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:
jdbc:sqlserver://localhost;integratedSecurity=true;
And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)
MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
I guess this question could mean two different things...
Height is the number of nodes in the longest branch:-
int calcHeight(node* root){
if(root==NULL)
return 0;
int l=calcHeight(root->left);
int r=calcHeight(root->right);
if(l>r)
return l+1;
else
return r+1;
}
Height is the total number of nodes in the tree itself:
int calcSize(node* root){
if(root==NULL)
return 0;
return(calcSize(root->left)+1+calcSize(root->right));
}
grep -e -X
will do the trick.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Put it all in one document and use this:
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px)
only screen and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px)
only screen and (-webkit-device-pixel-ratio: 3) {
/*** You've spent way too much on a phone ***/
}
/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
/* Styles */
}
Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
At this point, I would definitely consider using em
values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.
@jeminar has the best solution above.
I cleaned it up a bit though.
I recommend adding this to a FunctionsArray module
isInitialised=false
is not needed because Booleans are false when createdOn Error GoTo 0
wrap and indent code inside error blocks similar to with
blocks for visibility. these methods should be avoided as much as possible but ... VBA ...Function isInitialised(ByRef a() As Variant) As Boolean
On Error Resume Next
isInitialised = IsNumeric(UBound(a))
On Error GoTo 0
End Function
Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.
Actually a name can be used however it cannot have spaces so
window.open("../myPage","MyWindows",...)
should work with no problem (window.open).
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
The regular expression I ended up using for when I want to allow spaces in the middle of my string, but not at the beginning or end was this:
[\S]+(\s[\S]+)*
or
^[\S]+(\s[\S]+)*$
So, I know this is an old question, but you could do something like:
if (/^\s+$/.test(myString)) {
//string contains characters and white spaces
}
or you can do what nickf said and use:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
ClsConectaBanco bd = new ClsConectaBanco();
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO FAT_BALANCETE ");
sb.Append(" ([DT_LANCAMENTO] ");
sb.Append(" ,[ID_LANCAMENTO_CONTABIL] ");
sb.Append(" ,[NR_DOC_CONTABIL] ");
sb.Append(" ,[TP_LANCAMENTO_GERADO] ");
sb.Append(" ,[VL_LANCAMENTO] ");
sb.Append(" ,[TP_NATUREZA] ");
sb.Append(" ,[CD_EMPRESA] ");
sb.Append(" ,[CD_FILIAL] ");
sb.Append(" ,[CD_CONTA_CONTABIL] ");
sb.Append(" ,[DS_CONTA_CONTABIL] ");
sb.Append(" ,[ID_CONTA_CONTABIL] ");
sb.Append(" ,[DS_TRIMESTRE] ");
sb.Append(" ,[DS_SEMESTRE] ");
sb.Append(" ,[NR_TRIMESTRE] ");
sb.Append(" ,[NR_SEMESTRE] ");
sb.Append(" ,[NR_ANO] ");
sb.Append(" ,[NR_MES] ");
sb.Append(" ,[NM_FILIAL]) ");
sb.Append(" VALUES ");
sb.Append(" (@DT_LANCAMENTO ");
sb.Append(" ,@ID_LANCAMENTO_CONTABIL ");
sb.Append(" ,@NR_DOC_CONTABIL ");
sb.Append(" ,@TP_LANCAMENTO_GERADO ");
sb.Append(" ,@VL_LANCAMENTO ");
sb.Append(" ,@TP_NATUREZA ");
sb.Append(" ,@CD_EMPRESA ");
sb.Append(" ,@CD_FILIAL ");
sb.Append(" ,@CD_CONTA_CONTABIL ");
sb.Append(" ,@DS_CONTA_CONTABIL ");
sb.Append(" ,@ID_CONTA_CONTABIL ");
sb.Append(" ,@DS_TRIMESTRE ");
sb.Append(" ,@DS_SEMESTRE ");
sb.Append(" ,@NR_TRIMESTRE ");
sb.Append(" ,@NR_SEMESTRE ");
sb.Append(" ,@NR_ANO ");
sb.Append(" ,@NR_MES ");
sb.Append(" ,@NM_FILIAL) ");
SqlCommand cmd = new SqlCommand(sb.ToString(), bd.CriaConexaoSQL());
bd.AbrirConexao();
cmd.Parameters.Add("@DT_LANCAMENTO", SqlDbType.Date);
cmd.Parameters.Add("@ID_LANCAMENTO_CONTABIL", SqlDbType.Int);
cmd.Parameters.Add("@NR_DOC_CONTABIL", SqlDbType.VarChar,255);
cmd.Parameters.Add("@TP_LANCAMENTO_GERADO", SqlDbType.VarChar,255);
cmd.Parameters.Add("@VL_LANCAMENTO", SqlDbType.Decimal);
cmd.Parameters["@VL_LANCAMENTO"].Precision = 15;
cmd.Parameters["@VL_LANCAMENTO"].Scale = 2;
cmd.Parameters.Add("@TP_NATUREZA", SqlDbType.VarChar, 1);
cmd.Parameters.Add("@CD_EMPRESA",SqlDbType.Int);
cmd.Parameters.Add("@CD_FILIAL", SqlDbType.Int);
cmd.Parameters.Add("@CD_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@DS_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@ID_CONTA_CONTABIL", SqlDbType.VarChar,50);
cmd.Parameters.Add("@DS_TRIMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@DS_SEMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@NR_TRIMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_SEMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_ANO", SqlDbType.Int);
cmd.Parameters.Add("@NR_MES", SqlDbType.Int);
cmd.Parameters.Add("@NM_FILIAL", SqlDbType.VarChar, 255);
cmd.Prepare();
foreach (dtoVisaoBenner obj in lista)
{
cmd.Parameters["@DT_LANCAMENTO"].Value = obj.CTLDATA;
cmd.Parameters["@ID_LANCAMENTO_CONTABIL"].Value = obj.CTLHANDLE.ToString();
cmd.Parameters["@NR_DOC_CONTABIL"].Value = obj.CTLDOCTO.ToString();
cmd.Parameters["@TP_LANCAMENTO_GERADO"].Value = obj.LANCAMENTOGERADO;
cmd.Parameters["@VL_LANCAMENTO"].Value = obj.CTLANVALORF;
cmd.Parameters["@TP_NATUREZA"].Value = obj.NATUREZA;
cmd.Parameters["@CD_EMPRESA"].Value = obj.EMPRESA;
cmd.Parameters["@CD_FILIAL"].Value = obj.FILIAL;
cmd.Parameters["@CD_CONTA_CONTABIL"].Value = obj.CONTAHANDLE.ToString();
cmd.Parameters["@DS_CONTA_CONTABIL"].Value = obj.CONTANOME.ToString();
cmd.Parameters["@ID_CONTA_CONTABIL"].Value = obj.CONTA;
cmd.Parameters["@DS_TRIMESTRE"].Value = obj.TRIMESTRE;
cmd.Parameters["@DS_SEMESTRE"].Value = obj.SEMESTRE;
cmd.Parameters["@NR_TRIMESTRE"].Value = obj.NRTRIMESTRE;
cmd.Parameters["@NR_SEMESTRE"].Value = obj.NRSEMESTRE;
cmd.Parameters["@NR_ANO"].Value = obj.NRANO;
cmd.Parameters["@NR_MES"].Value = obj.NRMES;
cmd.Parameters["@NM_FILIAL"].Value = obj.NOME;
cmd.ExecuteNonQuery();
rowAffected++;
}
Depending on what kind of image you have, it might be better to rework the design so that the main image fades to a set solid color or repeatable pattern. If you center the image in the page and have the solid color as the backgroud.
See http://www.webdesignerwall.com/trends/80-large-background-websites/ for examples of sites using large or scalable backgrounds.
I know that It's very too late, still I will give my answer.
I used this line of code to check the inputted Email
format:
!TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();
The problem is, it will only check for the FORMAT
not the SPELLING
.
When I entered @gmal.com
missing i
,and @yaho.com
missing another o
.
It return true
. Since it satisfies the condition for Email Format
.
What I did is, I used the code above. Since it will give / return true
if
the if the user inputted @gmail.com
ONLY, no text at the start.
FORMAT CHECKER
If I enter this email it will give me: true
but the spelling is wrong. In
my textInputLayout error
EMAIL ADDRESS @yahoo.com
, @gmail.com
, @outlook.com
CHECKER
//CHECK EMAIL
public boolean checkEmailValidity(AppCompatEditText emailFormat){
String getEmail = emailFormat.getText().toString();
boolean getEnd;
//CHECK STARTING STRING IF THE USER
//entered @gmail.com / @yahoo.com / @outlook.com only
boolean getResult = !TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();
//CHECK THE EMAIL EXTENSION IF IT ENDS CORRECTLY
if (getEmail.endsWith("@gmail.com") || getEmail.endsWith("@yahoo.com") || getEmail.endsWith("@outlook.com")){
getEnd = true;
}else {
getEnd = false;
}
//TEST THE START AND END
return (getResult && getEnd);
}
RETURN: false
RETURN:true
XML:
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextEmailAddress"
android:inputType="textEmailAddress|textWebEmailAddress"
android:cursorVisible="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:maxLength="50"
android:theme="@style/EditTextCustom"/>
Note: I tried to get the value
from EditText and used split
on it and even StringTokenizer
. Both return false
to me.
I am using it.............
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK)
Toast.makeText(getApplicationContext(), "back press",
Toast.LENGTH_LONG).show();
return false;
// Disable back button..............
}
Note: my answer is about really deleting the tables and other database objects; for deleting all data in the tables, i.e. truncating all tables, Endre Both has provided a similarily well-executed (direct execution) statement a month later.
For the cases where you can’t just DROP SCHEMA public CASCADE;
, DROP OWNED BY current_user;
or something, here’s a stand-alone SQL script I wrote, which is transaction-safe (i.e. you can put it between BEGIN;
and either ROLLBACK;
to just test it out or COMMIT;
to actually do the deed) and cleans up “all” database objects… well, all those used in the database our application uses or I could sensibly add, which is:
CHECK
, UNIQUE
)VIEW
s (normal or materialised)public
or DB-internal) schemata “we” own: the script is useful when run as “not a database superuser”; a superuser can drop all schemata (the really important ones are still explicitly excluded, though)Not dropped are (some deliberate; some only because I had no example in our DB):
public
schema (e.g. for extension-provided stuff in them)This is really useful for the cases when the dump you want to restore is of a different database schema version (e.g. with Debian dbconfig-common
, Flyway or Liquibase/DB-Manul) than the database you want to restore it into.
I’ve also got a version which deletes “everything except two tables and what belongs to them” (a sequence, tested manually, sorry, I know, boring) in case someone is interested; the diff is small. Contact me or check this repo if interested.
-- Copyright © 2019, 2020
-- mirabilos <[email protected]>
--
-- Provided that these terms and disclaimer and all copyright notices
-- are retained or reproduced in an accompanying document, permission
-- is granted to deal in this work without restriction, including un-
-- limited rights to use, publicly perform, distribute, sell, modify,
-- merge, give away, or sublicence.
--
-- This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
-- the utmost extent permitted by applicable law, neither express nor
-- implied; without malicious intent or gross negligence. In no event
-- may a licensor, author or contributor be held liable for indirect,
-- direct, other damage, loss, or other issues arising in any way out
-- of dealing in the work, even if advised of the possibility of such
-- damage or existence of a defect, except proven that it results out
-- of said person’s immediate fault when using the work as intended.
-- -
-- Drop everything from the PostgreSQL database.
DO $$
DECLARE
q TEXT;
r RECORD;
BEGIN
-- triggers
FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pt.tgisinternal=false
) LOOP
EXECUTE format('DROP TRIGGER %I ON %I.%I;',
r.tgname, r.nspname, r.relname);
END LOOP;
-- constraints #1: foreign key
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype='f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- constraints #2: the rest
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype<>'f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- indices
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='i'
) LOOP
EXECUTE format('DROP INDEX %I.%I;',
r.nspname, r.relname);
END LOOP;
-- normal and materialised views
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind IN ('v', 'm')
) LOOP
EXECUTE format('DROP VIEW %I.%I;',
r.nspname, r.relname);
END LOOP;
-- tables
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='r'
) LOOP
EXECUTE format('DROP TABLE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- sequences
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='S'
) LOOP
EXECUTE format('DROP SEQUENCE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- extensions (only if necessary; keep them normally)
FOR r IN (SELECT pns.nspname, pe.extname
FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
WHERE pns.oid=pe.extnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
) LOOP
EXECUTE format('DROP EXTENSION %I;', r.extname);
END LOOP;
-- aggregate functions first (because they depend on other functions)
FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pagg.aggfnoid=pp.oid
) LOOP
EXECUTE format('DROP AGGREGATE %I.%I(%s);',
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- routines (functions, aggregate functions, procedures, window functions)
IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='prokind' -- PostgreSQL 11+
) THEN
q := 'CASE pp.prokind
WHEN ''p'' THEN ''PROCEDURE''
WHEN ''a'' THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='proisagg' -- PostgreSQL =10
) THEN
q := 'CASE pp.proisagg
WHEN true THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSE
q := '''FUNCTION''';
END IF;
FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
' LOOP
EXECUTE format('DROP %s %I.%I(%s);', r.pt,
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- non-default schemata we own; assume to be run by a not-superuser
FOR r IN (SELECT pns.nspname
FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
WHERE pr.oid=pns.nspowner
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
AND pr.rolname=current_user
) LOOP
EXECUTE format('DROP SCHEMA %I;', r.nspname);
END LOOP;
-- voilà
RAISE NOTICE 'Database cleared!';
END; $$;
Tested, except later additions (extensions
contributed by Clément Prévost), on PostgreSQL 9.6 (jessie-backports
). Aggregate removal tested on 9.6 and 12.2, procedure removal tested on 12.2 as well. Bugfixes and further improvements welcome!
To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
If you wanted to center it vertically, the canvas element needs to be absolutely positioned:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
If you wanted to center it horizontally and vertically, do:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
For more info visit: https://www.w3.org/Style/Examples/007/center.en.html
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
function foo(x) {
// Function with other context
// Modify `x` property, increasing the value
x.value++;
}
// Initialize `ref` as object
var ref = {
// The `value` is inside `ref` variable object
// The initial value is `1`
value: 1
};
// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);
console.log(ref.value); // Prints "3"
_x000D_
rvar
/**
* Aux function to create by-references variables
*/
function rvar(name, value, context) {
// If `this` is a `rvar` instance
if (this instanceof rvar) {
// Inside `rvar` context...
// Internal object value
this.value = value;
// Object `name` property
Object.defineProperty(this, 'name', { value: name });
// Object `hasValue` property
Object.defineProperty(this, 'hasValue', {
get: function () {
// If the internal object value is not `undefined`
return this.value !== undefined;
}
});
// Copy value constructor for type-check
if ((value !== undefined) && (value !== null)) {
this.constructor = value.constructor;
}
// To String method
this.toString = function () {
// Convert the internal value to string
return this.value + '';
};
} else {
// Outside `rvar` context...
// Initialice `rvar` object
if (!rvar.refs) {
rvar.refs = {};
}
// Initialize context if it is not defined
if (!context) {
context = window;
}
// Store variable
rvar.refs[name] = new rvar(name, value, context);
// Define variable at context
Object.defineProperty(context, name, {
// Getter
get: function () { return rvar.refs[name]; },
// Setter
set: function (v) { rvar.refs[name].value = v; },
// Can be overrided?
configurable: true
});
// Return object reference
return context[name];
}
}
// Variable Declaration
// Declare `test_ref` variable
rvar('test_ref_1');
// Assign value `5`
test_ref_1 = 5;
// Or
test_ref_1.value = 5;
// Or declare and initialize with `5`:
rvar('test_ref_2', 5);
// ------------------------------
// Test Code
// Test Function
function Fn1 (v) { v.value = 100; }
// Declare
rvar('test_ref_number');
// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);
// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);
// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);
// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);
// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');
// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');
// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true
// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true
// Increase value
test_ref_number++;
test_ref_number.value === 101; // true
// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true
test_ref_str.value === "a"; // true
// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true
_x000D_
You can use a circular buffer :
Code
// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());
Maven dependency
<dependency>
<groupId>org.ostermiller</groupId>
<artifactId>utils</artifactId>
<version>1.07.00</version>
</dependency>
Mode details
This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:
@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)
The below code absolutely works and it is great if you keep all your queries in orm.xml
from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type
If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.
Notes:
The issue may be a specific MySql quirk. I only tested with Oracle.
The above query assumes that there are table rows where c.status is null
The where clause is prioritized so that the parameter is checked first.
The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.
If you needed to skip the :status where_clause altogether; you can code like so:
from CountryDTO c where (:status is null or c.status = :status) and c.type =:type
and it is equivalent to:
sql.append(" where ");
if(status != null){
sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.
Check it out here
An example of its use for your case:
import cookie from "react-cookie";
setCookie() => {
let d = new Date();
d.setTime(d.getTime() + (minutes*60*1000));
cookie.set("onboarded", true, {path: "/", expires: d});
};
As an augmentation to the other answers, on Mac OS X, the "Preferences" menu is under Eclipse, not Window (unlike Windows/Linux Eclipse distributions). Everything else is still the same as pointed out by other answers past this point.
IE: Java Formatter available under:
Eclipse > | # Not Window!
Preferences > |
Java > |
Code Style > |
Formatter |
From here, edit the formatter and the tab policy can be set under "Indentation".
This worked for me on Kali-linux 2018 :
apt-get install php7.0-mbstring
service apache2 restart
You can also use INT_MAX:
http://www.cplusplus.com/reference/climits/
it's equivalent to using numeric_limits.
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
You can get maximum column value and increment it:
InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:
SELECT MAX(ai_col) FROM t FOR UPDATE;
InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
After changing the TestNG Output path(Project Properties-->TestNG-->Output Directory), its worked for me.
You can try this: https://github.com/msqrt/shader-printf which is an implementation called appropriately "Simple printf functionality for GLSL."
You might also want to try ShaderToy, and maybe watch a video like this one (https://youtu.be/EBrAdahFtuo) from "The Art of Code" YouTube channel where you can see some of the techniques that work well for debugging and visualising. I can strongly recommend his channel as he writes some really good stuff and he also has a knack for presenting complex ideas in novel, highly engaging and and easy to digest formats (His Mandelbrot video is a superb example of exactly that : https://youtu.be/6IWXkV82oyY)
I hope nobody minds this late reply, but the question ranks high on Google searches for GLSL debugging and much has of course changed in 9 years :-)
PS: Other alternatives could also be NVIDIA nSight and AMD ShaderAnalyzer which offer a full stepping debugger for shaders.
Declare your function pointer like this:
bool (*f)();
f = A;
f();
It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659
The monkey patch detailed on this issue has resolved the problem for me:
# monkeypatches.py
# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
libc.malloc_trim(0)
except (OSError, AttributeError):
libc = None
__old_del = getattr(pd.DataFrame, '__del__', None)
def __new_del(self):
if __old_del:
__old_del(self)
libc.malloc_trim(0)
if libc:
print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
pd.DataFrame.__del__ = __new_del
else:
print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)
The simplest and most reliable solution is inserting flex items at the right places. If they are wide enough (width: 100%
), they will force a line break.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(4n - 1) {_x000D_
background: silver;_x000D_
}_x000D_
.line-break {_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
<div class="line-break"></div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
But that's ugly and not semantic. Instead, we could generate pseudo-elements inside the flex container, and use order
to move them to the right places.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
background: silver;_x000D_
}_x000D_
.container::before, .container::after {_x000D_
content: '';_x000D_
width: 100%;_x000D_
order: 1;_x000D_
}_x000D_
.item:nth-child(n + 4) {_x000D_
order: 1;_x000D_
}_x000D_
.item:nth-child(n + 7) {_x000D_
order: 2;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
</div>
_x000D_
But there is a limitation: the flex container can only have a ::before
and a ::after
pseudo-element. That means you can only force 2 line breaks.
To solve that, you can generate the pseudo-elements inside the flex items instead of in the flex container. This way you won't be limited to 2. But those pseudo-elements won't be flex items, so they won't be able to force line breaks.
But luckily, CSS Display L3 has introduced display: contents
(currently only supported by Firefox 37):
The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.
So you can apply display: contents
to the children of the flex container, and wrap the contents of each one inside an additional wrapper. Then, the flex items will be those additional wrappers and the pseudo-elements of the children.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
display: contents;_x000D_
}_x000D_
.item > div {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px;_x000D_
}_x000D_
.item:nth-child(3n) > div {_x000D_
background: silver;_x000D_
}_x000D_
.item:nth-child(3n)::after {_x000D_
content: '';_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item"><div>1</div></div>_x000D_
<div class="item"><div>2</div></div>_x000D_
<div class="item"><div>3</div></div>_x000D_
<div class="item"><div>4</div></div>_x000D_
<div class="item"><div>5</div></div>_x000D_
<div class="item"><div>6</div></div>_x000D_
<div class="item"><div>7</div></div>_x000D_
<div class="item"><div>8</div></div>_x000D_
<div class="item"><div>9</div></div>_x000D_
<div class="item"><div>10</div></div>_x000D_
</div>
_x000D_
Alternatively, according to Fragmenting Flex Layout and CSS Fragmentation, Flexbox allows forced breaks by using break-before
, break-after
or their CSS 2.1 aliases:
.item:nth-child(3n) {
page-break-after: always; /* CSS 2.1 syntax */
break-after: always; /* New syntax */
}
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
.item:nth-child(3n) {_x000D_
page-break-after: always;_x000D_
background: silver;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
Forced line breaks in flexbox are not widely supported yet, but it works on Firefox.
From your code
<input type=button value="Select" onClick="sendValue(this.form.details);"
Im not sure that your this.form.details
valid or not.
IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;
I can't found an input's id contain details
I'm just found only id=sku1
(recommend you to add "
like id="sku1"
).
And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.
<html>
<head>
<script>
function callFromDialog(id,data){ //for callback from the dialog
document.getElementById(id).value = data;
// do some thing other if you want
}
function choose(id){
var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
}
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>
Look in function choose
I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#
)
<html>
<head>
<script>
function goSelect(data){
var idFromCallPage = getUrlVars()["id"];
window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
window.close();
}
function getUrlVars(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>
I have add function getUrlVars for get URL param that the parent has pass to child.
Okay, when select data in the popup, for this case it's will call function goSelect
In that function will get URL param to sent back.
And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog
By fully is window.opener.callFromDialog(idFromCallPage,data);
Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data;
It's ok too.
In one line, using a lambda
:
timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)
Passing a function to list.sort
:
def foo(x):
return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]
timestamps.sort(key=foo, reverse=True)
Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack
Take a table with class name column-bordered-table
then add this below css.This will work with bootstrap
table too
.column-bordered-table thead td {
border-left: 1px solid #c3c3c3;
border-right: 1px solid #c3c3c3;
}
.column-bordered-table td {
border-left: 1px solid #c3c3c3;
border-right: 1px solid #c3c3c3;
}
.column-bordered-table tfoot tr {
border-top: 1px solid #c3c3c3;
border-bottom: 1px solid #c3c3c3;
}
see the output below
N:B You have to add table header backgorund color as per you requirement
In case anyone new is coming along and catching this thread, you can specify multiple animations--each with their own properties--with a comma.
Example:
animation: rotate 1s, spin 3s;
$('.PDatePicker').MdPersianDateTimePicker({
Placement: 'top',
});
In Simpler words, Pig is a high-level platform for creating MapReduce programs used with Hadoop, using pig scripts we will process the large amount of data into desired format.
Once the processed data obtained, this processed data is kept in HDFS for later processing to obtain the desired results.
On top of the stored processed data we will apply HIVE SQL commands to get the desired results, internally this hive sql commands runs MAP Reduce programs.
Move path\to\anaconda
in the PATH above path\to\python
Look at getpass module
import getpass
getpass.getuser()
'kostya'
Availability: Unix, Windows
p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.
I fixed just calling the manifest.json correctly on html headers.
My html headers:
<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">
And the manifest.json file content:
{
"display": "standalone",
"orientation": "portrait",
"start_url": "/",
"theme_color": "#000000",
"background_color": "#ffffff",
"icons": [
{
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
}
}
To generate your favicons and icons use this webtool: https://realfavicongenerator.net/
To generate your manifest file use: https://tomitm.github.io/appmanifest/
My PWA Works great, hope it helps!
With dplyr
it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}}
around the desired column name within the function body, e.g. for col_name
:
library(tidyverse)
fun <- function(df, col_name){
df %>%
filter({{col_name}} == "test_string")
}
You can access your keys and/or values by calling items() on your dictionary.
for key, value in d.iteritems():
print(key, value)
You could always do just:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]
a==b #returns False
a==c #returns False
a==d #returns True
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
You can use the contenteditable attribute on the cells, rows, or table in question.
Updated for IE8 compatibility
<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>
Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.
You'd also need to check whether your target audience's browsers supported this attribute.
As far as listening for the changes (so you can send to the server), see contenteditable change events
My class was annotated with JsonSerialize, and the include parameter was set to JsonSerialize.Inclusion.NON_DEFAULT
. This caused Jackson to determine the default values for each bean property. I had a bean property that returned an int. The problem in my case was that the bean getter made a call to a method which has an inferred return type (i.e.: a generic method). For some odd reason this code compiled; it shouldn't have compiled because you cannot use an int for an inferred return type. I changed the 'int' to an 'Integer' for that bean property and I no longer got a 406. The odd thing is, the code now fails to compile if I change the Integer back to an int.
You can try yourself:
>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
0 1
0 1 2
1 5 6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
0 1
0 3 4
1 5 6
All Integers are modulo of 1. So below check must give you the answer.
if(d % 1 == 0)
I had same issue as mentioned " Your PHP installation appears to be missing the MySQL extension which is required by WordPress" in resellerclub hosting.
I went through this thread and came to know that php version should be greater than > 5.6 so that wordpress will automatically gets converted to mysqli
Then logged into my cpanel searched for php in cpanel to check for the version, luckly was able to find that my version of php was 5.2 and changed that to 5.6 by making sure mysqli is tick marked in the option window and saved it is working fine now.
If you're looking for a more generic method:
public static List<U> FindDuplicates<T, U>(this List<T> list, Func<T, U> keySelector)
{
return list.GroupBy(keySelector)
.Where(group => group.Count() > 1)
.Select(group => group.Key).ToList();
}
EDIT: Here's an example:
public class Person {
public string Name {get;set;}
public int Age {get;set;}
}
List<Person> list = new List<Person>() { new Person() { Name = "John", Age = 22 }, new Person() { Name = "John", Age = 30 }, new Person() { Name = "Jack", Age = 30 } };
var duplicateNames = list.FindDuplicates(p => p.Name);
var duplicateAges = list.FindDuplicates(p => p.Age);
foreach(var dupName in duplicateNames) {
Console.WriteLine(dupName); // Will print out John
}
foreach(var dupAge in duplicateAges) {
Console.WriteLine(dupAge); // Will print out 30
}
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
So in your case, when: deployed_revision is not defined
should work
This is a very fast and clean way of doing it. It also supports empty columns where as none of the answers above worked for empty columns.
Usage: SelectFirstBlankCell("F")
Public Sub SelectFirstBlankCell(col As String)
Dim i As Integer
For i = 1 To 10000
If Range(col & CStr(i)).Value = "" Then
Exit For
End If
Next i
Range(col & CStr(i)).Select
End Sub
you have to use nested angular.forEach loops for JSON as shown below:
var values = [
{
"name":"Thomas",
"password":"thomas"
},
{
"name":"linda",
"password":"linda"
}];
angular.forEach(values,function(value,key){
angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop
console.log(k1+":"+v1);
});
});
This will work starting from Oracle 10
select version
, regexp_substr(banner, '[^[:space:]]+', 1, 4) as edition
from v$instance
, v$version where regexp_like(banner, 'edition', 'i');
Just to correct mingos' answer:
If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.
Example:
Instead of:
document.cookie = "cookie_name=cookie_value; 0; path=/";
Just write:
document.cookie = "cookie_name=cookie_value; path=/";
As the answers above point out, there are a number of ways to determine the most significant bit. However, as was also pointed out, the methods are likely to be unique to either 32bit or 64bit registers. The stanford.edu bithacks page provides solutions that work for both 32bit and 64bit computing. With a little work, they can be combined to provide a solid cross-architecture approach to obtaining the MSB. The solution I arrived at that compiled/worked across 64 & 32 bit computers was:
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64 1
#endif
#include <stdio.h>
#include <stdint.h> /* for uint32_t */
/* CHAR_BIT (or include limits.h) */
#ifndef CHAR_BIT
#define CHAR_BIT 8
#endif /* CHAR_BIT */
/*
* Find the log base 2 of an integer with the MSB N set in O(N)
* operations. (on 64bit & 32bit architectures)
*/
int
getmsb (uint32_t word)
{
int r = 0;
if (word < 1)
return 0;
#ifdef BUILD_64
union { uint32_t u[2]; double d; } t; // temp
t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000;
t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = word;
t.d -= 4503599627370496.0;
r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] >> 20) - 0x3FF;
#else
while (word >>= 1)
{
r++;
}
#endif /* BUILD_64 */
return r;
}
I recently tried installing python 2.6.7 on my Ubuntu 11.04 desktop for some dev work. Came across similar problems to this thread. I mamaged to fix it by:
Adjusting the setup.py file to include the correct sqlite dev path. Code snippet from setup.py:
def sqlite_incdir:
sqlite_dirs_to_check = [
os.path.join(sqlite_incdir, '..', 'lib64'),
os.path.join(sqlite_incdir, '..', 'lib'),
os.path.join(sqlite_incdir, '..', '..', 'lib64'),
os.path.join(sqlite_incdir, '..', '..', 'lib'),
'/usr/lib/x86_64-linux-gnu/'
]
With the bit that I added being '/usr/lib/x86_64-linux-gnu/'.
After running make I did not get any warnings saying the sqlite support was not built (i.e., it built correctly :P ), but after running make install
, sqlite3 still did not import with the same "ImportError: No module named _sqlite3" whe running "import sqlite3
".
So, the library was compiled, but not moved to the correct installation path, so I copied the .so
file (cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/
— these are my build paths, you will probably need to adjust them to your setup).
Voila! SQLite3 support now works.
Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.
var object = new Object();
if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.
var object1 = new Object();
var object2 = object1;
JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.
var object1 = new Object();
// do something
object1 = null; // dereference
Dereferencing objects is especially important in very large applications that use millions of objects.
from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
Using jQuery 1.9 and above:
$("#mySelect :selected").prop('selected', false);
val = -3.1234
fraction = abs(val - as.integer(val) )
The error your seeing is probably due to a non-MySQL created directory in MySQL's data directory. MySQL maps the database structure pretty directly onto the file system, databases are mapped to directories and tables are files in those directories.
The name of the non-working database looks suspiciously like someone has copied the mysql database directory to a backup at some point and left it in MySQL's data directory. This isn't a problem as long as you don't try and use the database for anything. Unfortunately the information schema scans all of the databases it finds and finds that this one isn't a real database and gets upset.
The solution is to find the mysql.bak directory on the hard disk and move it well away from MySQL.
You should also set this parameter to log every statement:
log_min_duration_statement = 0
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
You need to use ?param instead of @param when performing queries to MySQL
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Change the catch block to see the actual exception:
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
If B
is a Boolean array, write
B = B*1
(A bit code golfy.)
For ppl who are still facing this issue, try adding s3_host as follows to the config hash
:storage => :s3,
:s3_credentials => {:access_key_id => access key,
:secret_access_key => secret access key},
:bucket => bucket name here,
:s3_host_name => s3-us-west-1.amazonaws.com or whatever comes as per your region}.
This fixed the issue for me.
A decimal type can not contain formatting information. You can create another property, say FormattedProperty
of a string type that does what you want.
The @RequestBody
javadoc states
Annotation indicating a method parameter should be bound to the body of the web request.
It uses registered instances of HttpMessageConverter
to deserialize the request body into an object of the annotated parameter type.
And the @RequestParam
javadoc states
Annotation which indicates that a method parameter should be bound to a web request parameter.
Spring binds the body of the request to the parameter annotated with @RequestBody
.
Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name
, to map the parameter.
Parameters are resolved in order. The @RequestBody
is processed first. Spring will consume all the HttpServletRequest
InputStream
. When it then tries to resolve the @RequestParam
, which is by default required
, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.
The handler for @RequestParam
acts first, reading what it can of the HttpServletRequest
InputStream
to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc
mapped to the parameter name
. When the handler for @RequestBody
runs, there's nothing left in the request body, so the argument used is the empty string.
The handler for @RequestBody
reads the body and binds it to the parameter. The handler for @RequestParam
can then get the request parameter from the URL query string.
The handler for @RequestParam
reads from both the body and the URL query String. It would usually put them in a Map
, but since the parameter is of type String
, Spring will serialize the Map
as comma separated values. The handler for @RequestBody
then, again, has nothing left to read from the body.
No. Not necessarily.
If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.
According to the HTML Specification
A <div>
can be placed where flow content is expected1, which is the <td>
content model2.
In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable
I always use the below function:
public static String prettyPrintXml(String xmlStringToBeFormatted) {
String formattedXmlString = null;
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xmlStringToBeFormatted));
Document document = documentBuilder.parse(inputSource);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult streamResult = new StreamResult(new StringWriter());
DOMSource dOMSource = new DOMSource(document);
transformer.transform(dOMSource, streamResult);
formattedXmlString = streamResult.getWriter().toString().trim();
} catch (Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
System.err.println(sw.toString());
}
return formattedXmlString;
}
In my case I was able to fix that issue by using min-width: 100px
instead of width: 100px
for the cells th
or td
.
.table td, .table th {
min-width: 100px;
}
This can be done with lodash _.tail
and _.dropRight
:
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
You do not need to do this. Here is how to create a co-variance method:
http://www.youtube.com/watch?v=RqAfC4JXd4A
Alternatively you can use statistical analysis package that Excel has.
A radio button is a native element specific to each OS/browser. There is no way to change its color/style, unless you want to implement custom images or use a custom Javascript library which includes images (e.g. this - cached link)
You can use date_parse_from_format()
function ...
Check this link..you will get clear idea
>>> # small array
>>> a = [12,3,65,33,12,3,123,888000]
>>>
>>> import collections
>>> collections.Counter(a).most_common()[0][0]
3
>>> %timeit collections.Counter(a).most_common()[0][0]
100000 loops, best of 3: 11.3 µs per loop
>>>
>>> import numpy
>>> numpy.bincount(a).argmax()
3
>>> %timeit numpy.bincount(a).argmax()
100 loops, best of 3: 2.84 ms per loop
>>>
>>> import scipy.stats
>>> scipy.stats.mode(a)[0][0]
3.0
>>> %timeit scipy.stats.mode(a)[0][0]
10000 loops, best of 3: 172 µs per loop
>>>
>>> from collections import defaultdict
>>> def jjc(l):
... d = defaultdict(int)
... for i in a:
... d[i] += 1
... return sorted(d.iteritems(), key=lambda x: x[1], reverse=True)[0]
...
>>> jjc(a)[0]
3
>>> %timeit jjc(a)[0]
100000 loops, best of 3: 5.58 µs per loop
>>>
>>> max(map(lambda val: (a.count(val), val), set(a)))[1]
12
>>> %timeit max(map(lambda val: (a.count(val), val), set(a)))[1]
100000 loops, best of 3: 4.11 µs per loop
>>>
Best is 'max' with 'set' for small arrays like the problem.
According to @David Sanders, if you increase the array size to something like 100,000 elements, the "max w/set" algorithm ends up being the worst by far whereas the "numpy bincount" method is the best.
DO $$
DECLARE tableId integer;
BEGIN
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
INSERT INTO Table2 (val) VALUES (tableId);
END $$;
Tested with psql (10.3, server 9.6.8)
If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").
It makes a nice clean list of file names.
You can sort an array using usort function.
$array = array(
array('price'=>'1000.50','product'=>'product 1'),
array('price'=>'8800.50','product'=>'product 2'),
array('price'=>'200.0','product'=>'product 3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output :
Array
(
[0] => Array
(
[price] => 134.50
[product] => product 1
)
[1] => Array
(
[price] => 2033.0
[product] => product 3
)
[2] => Array
(
[price] => 8340.50
[product] => product 2
)
)
It's easy to do multiline replace in Notepad++. You have to use \n
to represent the newline in your string, and it works for both search and replace strings. You have to make sure to select "Extended" search mode in the bottom left corner of the search window.
I found a good article describing the features here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
in C#:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)
By creating a custom JavaScriptConverter you can map any name to any property. But it does require hand coding the map, which is less than ideal.
public class DataObjectJavaScriptConverter : JavaScriptConverter
{
private static readonly Type[] _supportedTypes = new[]
{
typeof( DataObject )
};
public override IEnumerable<Type> SupportedTypes
{
get { return _supportedTypes; }
}
public override object Deserialize( IDictionary<string, object> dictionary,
Type type,
JavaScriptSerializer serializer )
{
if( type == typeof( DataObject ) )
{
var obj = new DataObject();
if( dictionary.ContainsKey( "user_id" ) )
obj.UserId = serializer.ConvertToType<int>(
dictionary["user_id"] );
if( dictionary.ContainsKey( "detail_level" ) )
obj.DetailLevel = serializer.ConvertToType<DetailLevel>(
dictionary["detail_level"] );
return obj;
}
return null;
}
public override IDictionary<string, object> Serialize(
object obj,
JavaScriptSerializer serializer )
{
var dataObj = obj as DataObject;
if( dataObj != null )
{
return new Dictionary<string,object>
{
{"user_id", dataObj.UserId },
{"detail_level", dataObj.DetailLevel }
}
}
return new Dictionary<string, object>();
}
}
Then you can deserialize like so:
var serializer = new JavaScriptSerializer();
serialzer.RegisterConverters( new[]{ new DataObjectJavaScriptConverter() } );
var dataObj = serializer.Deserialize<DataObject>( json );
I needed to kill credential-helper processes (were multiple) and it solved the issue after providing credentials once again.
killall git-credential-cache--daemon
const FindDate = (date, allDate) => {
// moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
let nearestDate = -1;
allDate.some(d => {
const currentDate = moment(d)
const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
if(difference >= 0){
nearestDate = d
}
});
console.log(nearestDate)
}
You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point
float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");
y1 = Float.valueOf(df.format(y1));
The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.
UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!
Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.
Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.
Thanks!
At least as of Apache commons-io 2.5, the IOUtils.toString() method supports an URI argument and returns contents of files located inside jars on the classpath:
IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)
Perhaps the easiest way:
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(ciphertext);
output.write(mac);
byte[] out = output.toByteArray();
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
As you can see, the difference really lies in lib.js
, not main1.js
.
To summarize:
import
-ed variables, no matter how you declare the corresponding variables in the module.let
-vs-const
semantics applies to the declared variable in the module.
const
, it cannot be reassigned or rebound in anywhere.let
, it can only be reassigned in the module (but not the user). If it is changed, the import
-ed variable changes accordingly.I think the closest to the OP's intuition is an inline if statement:
df['que'] = (df['one'] if ((df['one'] >= df['two']) and (df['one'] <= df['three']))
will print all but very first column:
awk '{$1=""; print $0}' somefile
will print all but two first columns:
awk '{$1=$2=""; print $0}' somefile
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
if you want to 'add to the id' rather than replace it
capture the current id first, then append your new id. especially useful for twitter bootstrap which uses input states on their forms.
new_id = '{{old_id}} inputSuccess';
old_id = that.attr('id');
that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));
if you do not - you will lose any properties you previous set.
hth,
You might not have created the jar file properly:
ex: missing option m in jar creation
The following works:
jar -cvfm MyJar.jar Manifest.txt *.class
To prevent the jump, this is what I used
export function toggleBodyScroll(disable) {
if (!window.tempScrollTop) {
window.tempScrollTop = window.pageYOffset;
// save the current position in a global variable so I can access again later
}
if (disable) {
document.body.classList.add('disable-scroll');
document.body.style.top = `-${window.tempScrollTop}px`;
} else {
document.body.classList.remove('disable-scroll');
document.body.style.top = `0px`;
window.scrollTo({top: window.tempScrollTop});
window.tempScrollTop = 0;
}
}
and in my css
.disable-scroll {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
iotop with the -a flag:
-a, --accumulated show accumulated I/O instead of bandwidth
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
Here's how to do it from a csv:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Load data from CSV
dat = np.genfromtxt('dat.xyz', delimiter=' ',skip_header=0)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]
# Convert from pandas dataframes to numpy arrays
X, Y, Z, = np.array([]), np.array([]), np.array([])
for i in range(len(X_dat)):
X = np.append(X, X_dat[i])
Y = np.append(Y, Y_dat[i])
Z = np.append(Z, Z_dat[i])
# create x-y points to be used in heatmap
xi = np.linspace(X.min(), X.max(), 1000)
yi = np.linspace(Y.min(), Y.max(), 1000)
# Interpolate for plotting
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')
# I control the range of my colorbar by removing data
# outside of my range of interest
zmin = 3
zmax = 12
zi[(zi<zmin) | (zi>zmax)] = None
# Create the contour plot
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
vmax=zmax, vmin=zmin)
plt.colorbar()
plt.show()
where dat.xyz
is in the form
x1 y1 z1
x2 y2 z2
...
To get the DB path for iOS, the simplest way is to:
(lldb)
) and type: po RLMRealm.defaultRealmPath
Tada...you have the path to your realm database
Firstly, run the command below:
apt-get update && apt-get install procps
and then run:
ps -ef
Truncate the contents of a variable
$ var="abcde"; echo ${var%d*}
abc
Make substitutions similar to sed
$ var="abcde"; echo ${var/de/12}
abc12
Use a default value
$ default="hello"; unset var; echo ${var:-$default}
hello
The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);
According to Map.computeIfAbsent
docs:
If the specified key is not already associated with a value (or is mapped to
null
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.Returns:
the current (existing or computed) value associated with the specified key, or null if the computed value is null
The most idiomatic way to iterate a map of lists is using Map.forEach
and Iterable.forEach
:
map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));
Or, as shown in other answers, a traditional for
loop:
for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
String k = e.getKey();
for (Integer v : e.getValue()) {
/* use k and v here */
}
}
df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings $settings=getGlobalSettings(); // Apply User Theme Choice $theme_choice = $settings['theme']; .. etc etc etc .... function getGlobalSettings(){ $dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error()); mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error()); $MySQL = "SELECT * FROM systemSettings"; $result = mysqli_query($dbc, $MySQL); while($row = mysqli_fetch_array($result)) { $settings[$row['item']] = $row['value']; // NO NEED FOR PUSH } mysqli_close($dbc); return $settings; }
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
Use gettimeofday()
to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.
Change HH
to hh
as
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());
Note that dd/mm/yyyy
- will give you minutes instead of the month.
Goals are executed in phases which help determine the order goals get executed in. The best understanding of this is to look at the default Maven lifecycle bindings which shows which goals get run in which phases by default. The compile
phase goals will always be executed before the test
phase goals, which will always be executed before the package
phase goals and so on.
Part of the confusion is exacerbated by the fact that when you execute Maven you can specify a goal or a phase. If you specify a phase then Maven will run all phases up to the phase you specified in order (e.g. if you specify package it will first run through the compile phase and then the test phase and finally the package phase) and for each phase it will run all goals attached to that phase.
When you create a plugin execution in your Maven build file and you only specify the goal then it will bind that goal to a given default phase. For example, the jaxb:xjc
goal binds by default to the generate-resources
phase. However, when you specify the execution you can also explicitly specify the phase for that goal as well.
If you specify a goal when you execute Maven then it will run that goal and only that goal. In other words, if you specify the jar:jar
goal it will only run the jar:jar
goal to package your code into a jar. If you have not previously run the compile goal or prepared your compiled code in some other way this may very likely fail.
public enum Gender {
MALE,
FEMALE
}
The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset
and git checkout
.
After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:
That is basically it. The
reset
command overwrites these three trees in a specific order, stopping when you tell it to.
- Move whatever branch HEAD points to (stop if
--soft
)- THEN, make the Index look like that (stop here unless
--hard
)- THEN, make the Working Directory look like that
There are also
--merge
and--keep
options, but I would rather keep things simpler for now - that will be for another article.
Had this problem in vs2017, I already got MVC via nuget but System.Web.Mvc didn't appear in the "Assemblies" list under "Add Reference".
The solution was to select "Extensions" under "Assemblies" in the "Add Reference" dialog.
This is based on another answer, but is just reformated:
Assuming you mean you want the non-numbers stripped out, you should be able to use something like:
'
' Skips all characters in the input string except digits
'
Function GetDigits(ByVal s As String) As String
Dim char As String
Dim i As Integer
GetDigits = ""
For i = 1 To Len(s)
char = Mid(s, i, 1)
If char >= "0" And char <= "9" Then
GetDigits = GetDigits + char
End If
Next i
End Function
Calling this with:
Dim myStr as String
myStr = GetDigits("3d1fgd4g1dg5d9gdg")
Call MsgBox(myStr)
will give you a dialog box containing:
314159
and those first two lines show how you can store it into an arbitrary string variable, to do with as you wish.
This can be done using the numeric_limits in C++:
http://www.cplusplus.com/reference/limits/numeric_limits/
These are the methods you probably want to look at:
infinity() T Representation of positive infinity, if available.
quiet_NaN() T Representation of quiet (non-signaling) "Not-a-Number", if available.
signaling_NaN() T Representation of signaling "Not-a-Number", if available.
This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:
I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM")
, drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".
I am using Android Studio 3.3.
Go to View -> Tools Window -> Device File Explorer. Or you can find it on the Bottom Right corner of the Android Studio.
If the Emulator is running, the Device File Explorer will display the File structure on Emulator Storage.
Here you can right click on a Folder and select "Upload" to place the file
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
You can use this:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Here put your code
Map<String, String> map = new HashMap<String, String>();
map.put("Content-Type","application/json");
view.loadUrl(url, map);
return false;
}
The fastest method is regex
#Try with regex first
t0 = timeit.timeit("""
s = r2.sub('', st)
""", setup = """
import re
r2 = re.compile(r'[^a-zA-Z0-9]', re.MULTILINE)
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
#Try with join method on filter
t0 = timeit.timeit("""
s = ''.join(filter(str.isalnum, st))
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""",
number = 1000000)
print(t0)
#Try with only join
t0 = timeit.timeit("""
s = ''.join(c for c in st if c.isalnum())
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
2.6002226710006653 Method 1 Regex
5.739747313000407 Method 2 Filter + Join
6.540099570000166 Method 3 Join
There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
You can specify minDate as today by adding minDate: 0
to the options.
$("input.DateFrom").datepicker({
minDate: 0,
...
});
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
I had something similar and got it to work by effectively adding some padding-top to the child.
I'm sure some of the other answers here would get to the solution, but I couldn't get them to easily work after a lot of time; I instead ended up with the padding-top solution which is elegant in its simplicity, but seems kind of hackish to me (not to mention the pixel value it sets would probably depend on the parent height).
Actually, I solved the problem. I run it by eclipse jetty plugin.
I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.
I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!
You can create user instances and have each app talk to its very own SQL Express.
There is no limit on the number of databases.
SELECT TOP (0) [toID]
,[sourceID]
,[name]
,[address]
FROM [ReportDatabase].[Ticket].[To]
Simple and doesnt require any sys tables
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
Just wondering - why would you want to clone a function when you have prototypes AND can set the scope of a function call to anything you wish?
var funcA = {};
funcA.data = 'something';
funcA.changeData = function(d){ this.data = d; }
var funcB = {};
funcB.data = 'else';
funcA.changeData.call(funcB.data);
alert(funcA.data + ' ' + funcB.data);
we have to find label tag for attribute value based on that.we have replace label text.
Script:
<script type="text/javascript">
$(document).ready(function()
{
$("label[for*='test']").html("others");
});
</script>
Html
<label for="test_992918d5-a2f4-4962-b644-bd7294cbf2e6_FillInButton">others</label>
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.
Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.
Hope the explanation is clear enough.
since your form has a field called 'q', leaving it blank still sends an empty string.
try
if 'q' in request.GET and request.GET['q'] != "" :
message
else
error message
Java 8 provides different utility api methods to help us sort the streams better.
If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.
List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);
Creating comparator on fly:
integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);
With default comparator provided by java 8 when no argument passed to sorted():
integerList.stream().sorted().forEach(System.out::println); //Natural order
If you want to sort the same list in reverse order:
integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order
If your list is a list of user defined objects, then:
List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
new Person(2000, "Second", 30, 45000),
new Person(3000, "Third", 35, 25000));
Creating comparator on fly:
personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
.forEach(person -> System.out.println(person.getName()));
Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):
personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
Using Comparator.comparing() method(Generic method which compares based on the getter method provided):
personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
We can do chaining too using thenComparing() method:
personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.
Person class
public class Person {
private long personId;
private String name;
private int age;
private double salary;
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public Person(long personId, String name, int age, double salary) {
this.personId = personId;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Because b + a ="someonedamage"
, try this to achieve :
if (d.Contains(b) && d.Contains(a))
{
Console.WriteLine(" " + d);
Console.ReadLine();
}
For me it was like this...
Window->Show View->Other->General->Project Explorer
Or
Window->Open Perspective->Other->Java (default)
> mtcars %>%
+ summarise_all(typeof) %>%
+ gather
key value
1 mpg double
2 cyl double
3 disp double
4 hp double
5 drat double
6 wt double
7 qsec double
8 vs double
9 am double
10 gear double
11 carb double
I try class
and typeof
functions, but all fails.
Write a:hover::before
instead of a::before:hover
: example.
Here are the steps that worked for me for Ubuntu OS and using nvm
Go to nodejs website and get the last LTS version (for example in your current dater the version will be: x.y.z)
nvm install x.y.z
# In my case current version is: 14.15.4 (and had 14.15.3)
After that, execute nvm list
and you will get list of node versions installed by nvm.
Now you need to switch to the default last installed one by executing:
nvm alias default x.y.z
List again or run nvm --version
to check:
Update: sometimes even if i go over the steps above it doesn't work, so what i did was removing the symbolic links in /usr/local/bin
cd /usr/local/bin
sudo rm node npm npx
And relink:
sudo ln -s $(which node) /usr/local/bin/node
sudo ln -s $(which npm) /usr/local/bin/npm
sudo ln -s $(which npx) /usr/local/bin/npx
EDIT: A more structured approach, including all escape sequences for string
s and char
s.
Doesn't replace unicode characters with their literal equivalent.
Doesn't cook eggs, either.
public class ReplaceString
{
static readonly IDictionary<string, string> m_replaceDict
= new Dictionary<string, string>();
const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";
public static string StringLiteral(string i_string)
{
return Regex.Replace(i_string, ms_regexEscapes, match);
}
public static string CharLiteral(char c)
{
return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
}
private static string match(Match m)
{
string match = m.ToString();
if (m_replaceDict.ContainsKey(match))
{
return m_replaceDict[match];
}
throw new NotSupportedException();
}
static ReplaceString()
{
m_replaceDict.Add("\a", @"\a");
m_replaceDict.Add("\b", @"\b");
m_replaceDict.Add("\f", @"\f");
m_replaceDict.Add("\n", @"\n");
m_replaceDict.Add("\r", @"\r");
m_replaceDict.Add("\t", @"\t");
m_replaceDict.Add("\v", @"\v");
m_replaceDict.Add("\\", @"\\");
m_replaceDict.Add("\0", @"\0");
//The SO parser gets fooled by the verbatim version
//of the string to replace - @"\"""
//so use the 'regular' version
m_replaceDict.Add("\"", "\\\"");
}
static void Main(string[] args){
string s = "here's a \"\n\tstring\" to test";
Console.WriteLine(ReplaceString.StringLiteral(s));
Console.WriteLine(ReplaceString.CharLiteral('c'));
Console.WriteLine(ReplaceString.CharLiteral('\''));
}
}
People have suggested using INetAddress.isReachable. The problem is that some sites configure their firewalls to block ICMP Ping messages. So a "ping" might fail even though the web service is accessible.
And of course, the reverse is true as well. A host may respond to a ping even though the webserver is down.
And of course, a machine may be unable to connect directly to certain (or all) web servers due to local firewall restrictions.
The fundamental problem is that "can connect to the internet" is an ill-defined question, and this kind of thing is difficult to test without:
So generally, the simplest solution is for an app to just try to access whatever it needs to access, and fall back on human intelligence to do the diagnosis.
What is the
dict.get()
method?
As already mentioned the get
method contains an additional parameter which indicates the missing value. From the documentation
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a
KeyError
.
An example can be
>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1
Are there speed improvements anywhere?
As mentioned here,
It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.
Earlier get
was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)
def getway(d):
for i in range(100):
s = d.get(i)
def lookup(d):
for i in range(100):
s = d[i]
Now timing these two functions using timeit
>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979
As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis
>>> def lookup(d,val):
... return d[val]
...
>>> def getway(d,val):
... return d.get(val)
...
>>> dis.dis(getway)
2 0 LOAD_FAST 0 (d)
3 LOAD_ATTR 0 (get)
6 LOAD_FAST 1 (val)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>> dis.dis(lookup)
2 0 LOAD_FAST 0 (d)
3 LOAD_FAST 1 (val)
6 BINARY_SUBSCR
7 RETURN_VALUE
Where will it be useful?
It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces
if key in dic:
val = dic[key]
else:
val = def_val
To a single line, val = dic.get(key,def_val)
Where will it be NOT useful?
Whenever you want to return a KeyError
stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!
Is it possible to have
get
like feature indict['key']
?
Yes! We need to implement the __missing__
in a dict subclass.
A sample program can be
class MyDict(dict):
def __missing__(self, key):
return None
A small demonstration can be
>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'
You need to include the jQuery library on your page.
You can download jQuery here and host it yourself or you can link from an external source like from Google or Microsoft.
Google's:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
Microsoft's:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
Michael Dowling's very actively maintained Guzzle is a good way to go. Apart from the elegant interface, asynchronous calling and PSR compliance, it makes the authentication headers for REST calls dead simple:
// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'http://myservices.io']);
// Send a request to http://myservices.io/status with basic authentication
$response = $client->get('/status', ['auth' => ['username', 'password']]);
See the docs.
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
ls -sh video.mp4 | sed s/video.mp4//g
output, 5.6M
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.
Just to add to other answers, if you're using Django, it is advisable that you install mysql-python BEFORE installing Django.
Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:
f"({self.goals} goals, ${self.penalties})"
This is similar to the previous .format
standard, but lets one easily do things like:
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result: 12.35'
When I wrote the first version of this answer, I was only looking at the title question about < vs. <= in general, not the specific example of a constant a < 901
vs. a <= 900
. Many compilers always shrink the magnitude of constants by converting between <
and <=
, e.g. because x86 immediate operand have a shorter 1-byte encoding for -128..127.
For ARM, being able to encode as an immediate depends on being able to rotate a narrow field into any position in a word. So cmp r0, #0x00f000
would be encodeable, while cmp r0, #0x00efff
would not be. So the make-it-smaller rule for comparison vs. a compile-time constant doesn't always apply for ARM. AArch64 is either shift-by-12 or not, instead of an arbitrary rotation, for instructions like cmp
and cmn
, unlike 32-bit ARM and Thumb modes.
In assembly language on most machines, a comparison for <=
has the same cost as a comparison for <
. This applies whether you're branching on it, booleanizing it to create a 0/1 integer, or using it as a predicate for a branchless select operation (like x86 CMOV). The other answers have only addressed this part of the question.
But this question is about the C++ operators, the input to the optimizer. Normally they're both equally efficient; the advice from the book sounds totally bogus because compilers can always transform the comparison that they implement in asm. But there is at least one exception where using <=
can accidentally create something the compiler can't optimize.
As a loop condition, there are cases where <=
is qualitatively different from <
, when it stops the compiler from proving that a loop is not infinite. This can make a big difference, disabling auto-vectorization.
Unsigned overflow is well-defined as base-2 wrap around, unlike signed overflow (UB). Signed loop counters are generally safe from this with compilers that optimize based on signed-overflow UB not happening: ++i <= size
will always eventually become false. (What Every C Programmer Should Know About Undefined Behavior)
void foo(unsigned size) {
unsigned upper_bound = size - 1; // or any calculation that could produce UINT_MAX
for(unsigned i=0 ; i <= upper_bound ; i++)
...
Compilers can only optimize in ways that preserve the (defined and legally observable) behaviour of the C++ source for all possible input values, except ones that lead to undefined behaviour.
(A simple i <= size
would create the problem too, but I thought calculating an upper bound was a more realistic example of accidentally introducing the possibility of an infinite loop for an input you don't care about but which the compiler must consider.)
In this case, size=0
leads to upper_bound=UINT_MAX
, and i <= UINT_MAX
is always true. So this loop is infinite for size=0
, and the compiler has to respect that even though you as the programmer probably never intend to pass size=0. If the compiler can inline this function into a caller where it can prove that size=0 is impossible, then great, it can optimize like it could for i < size
.
Asm like if(!size) skip the loop;
do{...}while(--size);
is one normally-efficient way to optimize a for( i<size )
loop, if the actual value of i
isn't needed inside the loop (Why are loops always compiled into "do...while" style (tail jump)?).
But that do{}while can't be infinite: if entered with size==0
, we get 2^n iterations. (Iterating over all unsigned integers in a for loop C makes it possible to express a loop over all unsigned integers including zero, but it's not easy without a carry flag the way it is in asm.)
With wraparound of the loop counter being a possibility, modern compilers often just "give up", and don't optimize nearly as aggressively.
Using unsigned i <= n
defeats clang's idiom-recognition that optimizes sum(1 .. n)
loops with a closed form based on Gauss's n * (n+1) / 2
formula.
unsigned sum_1_to_n_finite(unsigned n) {
unsigned total = 0;
for (unsigned i = 0 ; i < n+1 ; ++i)
total += i;
return total;
}
x86-64 asm from clang7.0 and gcc8.2 on the Godbolt compiler explorer
# clang7.0 -O3 closed-form
cmp edi, -1 # n passed in EDI: x86-64 System V calling convention
je .LBB1_1 # if (n == UINT_MAX) return 0; // C++ loop runs 0 times
# else fall through into the closed-form calc
mov ecx, edi # zero-extend n into RCX
lea eax, [rdi - 1] # n-1
imul rax, rcx # n * (n-1) # 64-bit
shr rax # n * (n-1) / 2
add eax, edi # n + (stuff / 2) = n * (n+1) / 2 # truncated to 32-bit
ret # computed without possible overflow of the product before right shifting
.LBB1_1:
xor eax, eax
ret
But for the naive version, we just get a dumb loop from clang.
unsigned sum_1_to_n_naive(unsigned n) {
unsigned total = 0;
for (unsigned i = 0 ; i<=n ; ++i)
total += i;
return total;
}
# clang7.0 -O3
sum_1_to_n(unsigned int):
xor ecx, ecx # i = 0
xor eax, eax # retval = 0
.LBB0_1: # do {
add eax, ecx # retval += i
add ecx, 1 # ++1
cmp ecx, edi
jbe .LBB0_1 # } while( i<n );
ret
GCC doesn't use a closed-form either way, so the choice of loop condition doesn't really hurt it; it auto-vectorizes with SIMD integer addition, running 4 i
values in parallel in the elements of an XMM register.
# "naive" inner loop
.L3:
add eax, 1 # do {
paddd xmm0, xmm1 # vect_total_4.6, vect_vec_iv_.5
paddd xmm1, xmm2 # vect_vec_iv_.5, tmp114
cmp edx, eax # bnd.1, ivtmp.14 # bound and induction-variable tmp, I think.
ja .L3 #, # }while( n > i )
"finite" inner loop
# before the loop:
# xmm0 = 0 = totals
# xmm1 = {0,1,2,3} = i
# xmm2 = set1_epi32(4)
.L13: # do {
add eax, 1 # i++
paddd xmm0, xmm1 # total[0..3] += i[0..3]
paddd xmm1, xmm2 # i[0..3] += 4
cmp eax, edx
jne .L13 # }while( i != upper_limit );
then horizontal sum xmm0
and peeled cleanup for the last n%3 iterations, or something.
It also has a plain scalar loop which I think it uses for very small n
, and/or for the infinite loop case.
BTW, both of these loops waste an instruction (and a uop on Sandybridge-family CPUs) on loop overhead. sub eax,1
/jnz
instead of add eax,1
/cmp/jcc would be more efficient. 1 uop instead of 2 (after macro-fusion of sub/jcc or cmp/jcc). The code after both loops writes EAX unconditionally, so it's not using the final value of the loop counter.
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}
npm start -- --port "port number"
This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow
import tkinter as tk
import time
def GetDateTime():
# Get current date and time in ISO8601
# https://en.wikipedia.org/wiki/ISO_8601
# https://xkcd.com/1179/
return (time.strftime("%Y%m%d", time.gmtime()),
time.strftime("%H%M%S", time.gmtime()),
time.strftime("%Y%m%d", time.localtime()),
time.strftime("%H%M%S", time.localtime()))
class Application(tk.Frame):
def __init__(self, master):
fontsize = 12
textwidth = 9
tk.Frame.__init__(self, master)
self.pack()
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Time').grid(row=0, column=0)
self.LocalDate = tk.StringVar()
self.LocalDate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalDate).grid(row=0, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Date').grid(row=1, column=0)
self.LocalTime = tk.StringVar()
self.LocalTime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalTime).grid(row=1, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Time').grid(row=2, column=0)
self.nowGdate = tk.StringVar()
self.nowGdate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGdate).grid(row=2, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Date').grid(row=3, column=0)
self.nowGtime = tk.StringVar()
self.nowGtime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGtime).grid(row=3, column=1)
tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)
self.gettime()
pass
def gettime(self):
gdt, gtm, ldt, ltm = GetDateTime()
gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'
ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]
self.nowGtime.set(gdt)
self.nowGdate.set(gtm)
self.LocalTime.set(ldt)
self.LocalDate.set(ltm)
self.after(100, self.gettime)
#print (ltm) # Prove it is running this and the external code, too.
pass
root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)
w = 200 # width for the Tk root
h = 125 # height for the Tk root
# get display screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
# calculate x and y coordinates for positioning the Tk root window
#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)
#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35 # -35 fixes it, more or less, for Win10
#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.mainloop()
Above solutions did not work for bitbucket. I figured this does the trick:
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts \
&& eval `ssh-agent` \
&& ssh-add ~/.ssh/[key] \
&& git clone [email protected]:[team]/[repo].git
This looks like a pretty clean solution: UIDevice BIdentifier
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
free(buf);
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}
//THIS IS WORKING CODE
Microsoft.Office.Interop.Excel.Range Range_Number,r2;
Range_Number = wsheet.UsedRange.Find("smth");
string f_number="";
r2 = wsheet.Cells;
int n_c = Range_Number.Column;
int n_r = Range_Number.Row;
var number = ((Range)r2[n_r + 1, n_c]).Value;
f_number = (string)number;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;
List<Address> addList=new ArrayList<Address>();
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
return addList;
}
public void setAddList(List<Address> addList) {
this.addList = addList;
}
}
We have two entities Employee and Address with One to Many relationship.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private int address_id;
private String address;
Employee employee;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
return address_id;
}
public void setAddress_id(int address_id) {
this.address_id = address_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
By this way we can implement inner join between two tables
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
saveEmployee();
retrieveEmployee();
}
private static void saveEmployee() {
Employee employee=new Employee();
Employee employee1=new Employee();
Employee employee2=new Employee();
Employee employee3=new Employee();
Address address=new Address();
Address address1=new Address();
Address address2=new Address();
Address address3=new Address();
address.setAddress("1485,Sector 42 b");
address1.setAddress("1485,Sector 42 c");
address2.setAddress("1485,Sector 42 d");
address3.setAddress("1485,Sector 42 a");
employee.setEmpName("Varun");
employee1.setEmpName("Krishan");
employee2.setEmpName("Aasif");
employee3.setEmpName("Dut");
address.setEmployee(employee);
address1.setEmployee(employee1);
address2.setEmployee(employee2);
address3.setEmployee(employee3);
employee.getAddList().add(address);
employee1.getAddList().add(address1);
employee2.getAddList().add(address2);
employee3.getAddList().add(address3);
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(employee);
session.save(employee1);
session.save(employee2);
session.save(employee3);
session.getTransaction().commit();
session.close();
}
private static void retrieveEmployee() {
try{
String sqlQuery="select e from Employee e inner join e.addList";
Session session=HibernateUtil.getSessionFactory().openSession();
Query query=session.createQuery(sqlQuery);
List<Employee> list=query.list();
list.stream().forEach((p)->{System.out.println(p.getEmpName());});
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Address.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
When using jQuery, the usage of $
symbol as a prefix in the variable name is merely by convention; it is completely optional and serves only to indicate that the variable holds a jQuery object, as in your example.
This means that when another jQuery function needs to be called on the object, you wouldn't need to wrap it in $()
again. For instance, compare these:
// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this
// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary
With the $
prefix the variables already holding jQuery objects are instantly recognizable and the code more readable, and eliminates double/multiple wrapping with $()
.
You can use radius but it will not work on IE: border-radius: 5px 5px;
.
To help everyone avoid confusion, I will reformulate the question in two parts.
First : "how can make an authenticated HTTP request with a browser, using BASIC auth?".
In the browser you can do a http basic auth first by waiting the prompt to come, or by editing the URL if you follow this format: http://myusername:[email protected]
NB: the curl command mentionned in the question is perfectly fine, if you have a command-line and curl installed. ;)
References:
Also according to the CURL manual page https://curl.haxx.se/docs/manual.html
HTTP
Curl also supports user and password in HTTP URLs, thus you can pick a file
like:
curl http://name:[email protected]/full/path/to/file
or specify user and password separately like in
curl -u name:passwd http://machine.domain/full/path/to/file
HTTP offers many different methods of authentication and curl supports
several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which
method to use, curl defaults to Basic. You can also ask curl to pick the
most secure ones out of the ones that the server accepts for the given URL,
by using --anyauth.
NOTE! According to the URL specification, HTTP URLs can not contain a user
and password, so that style will not work when using curl via a proxy, even
though curl allows it at other times. When using a proxy, you _must_ use
the -u style for user and password.
The second and real question is "However, on somesite.com, I'm not getting an authorization prompt at all, just a page that says I'm not authorized. Did somesite not implement the Basic Auth workflow correctly, or is there something else I need to do?"
The curl documentation says the -u
option supports many method of authentication, Basic being the default.
Single Liner to Drop, Create and Seed from Package Manager Console:
update-database -TargetMigration:0 | update-database -force
Kaboom.
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
If you are only interested to see the files that differ, you may use:
diff -qr dir_one dir_two | sort
Option "q" will only show the files that differ but not the content that differ, and "sort" will arrange the output alphabetically.
String newstr = "08/16/2011";
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
Calendar c = Calendar.getInstance();
c.setTime(format1.parse(newstr));
System.out.println(format.format(c.getTime()));
make sure your css reads:
margin: 0 auto;
Even though you're saying you have the left and right set to auto, you may be placing an error. Of course we wouldn't know though because you did not show us any code.
You can use env package to manage your environment variables per project:
.env
file under the project directory and put all of your
variables there.require('dotenv').config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
This is how I configure it on my server:
0 19 * * 1,3,5 root bash /home/divo/data/support_files/support_files_inc_backup.sh
The above command will run my script at 19:00 on Monday, Wednesday, and Friday.
NB: For cron entries for day of the week (dow)
0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();
That's my way to bind to code behind (see property DataTemplateSelector
)
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataTemplateSelector = new MyDataTemplateSelector();
InitializeComponent();
// ... more initializations ...
}
public DataTemplateSelector DataTemplateSelector { get; }
// ... more code stuff ...
}
In XAML will referenced by RelativeSource
via Ancestors up to containing Window
, so I'm at my Window
class and use the property via Path
declaration:
<GridViewColumn Header="Value(s)"
CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>
Setting of property DataTemplateSelector
before call InitializeComponent
depends on missing implementation of IPropertyChanged
or use of implementation with DependencyProperty
so no communication run on change of property DataTemplateSelector
.
To get around the process launch failed: Security
issue and immediately launch the app on your device, tap the app icon on your iOS device after running the app via Xcode.
This will allow you to immediately run the app. It may not actually "fix" the root issue that is causing these permission alerts.
Be sure to tap the app icon while the Xcode alert is still shown. Otherwise the app will not run. I continually forget this vital step and am unable to run the app on my device. Thus I am documenting it here for myself and everyone else :)
After tapping the icon, you should now see an alert asking you to "Trust" the Untrusted App Developer. After doing so the app will immediately run, unconnected to the Xcode debugger.
Best solution: Don't use global
s
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.
To generate key refer here
@Override
public void onDraw(Canvas canvas){
canvas.drawCircle(xPos, yPos,radius, paint);
}
Above is the code to render a circle. Tweak the parameters to your suiting.
.superscript {
position: relative;
top: 5px;
font-size: 90%;
vertical-align: super;
}
Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...
HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...
Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...
ruby on rails notes has a very nice blogpost about commenting in erb-files
the short version is
to comment a single line use
<%# commented line %>
to comment a whole block use a if false
to surrond your code like this
<% if false %>
code to comment
<% end %>
If you are running the command from a POSIX-compliant shell, like bash
, you can set the environment variable like this:
PYTHONPATH="/path/to" python somescript.py somecommand
If it's all on one line, the PYTHONPATH environment value applies only to that one command.
$ echo $PYTHONPATH
$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH