Check if there is a file called maintenance.flag and if so delete it.
Magento 1.x : maintenance.flag file is in : magento root directory
Magento 2.x : maintenance.flag file is in : var folder
When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.
It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.
Smallest code:
def contains(a,b):
str(a)[1:-1].find(str(b)[1:-1])>=0
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
str = str.replace(/^"(.*)"$/, '$1');
This regexp will only remove the quotes if they are the first and last characters of the string. F.ex:
"I am here" => I am here (replaced)
I "am" here => I "am" here (untouched)
I am here" => I am here" (untouched)
With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');
Do you have a _ViewStart.cshtml
in this directory? I had the same problem you're having when I tried using _ViewStart. Then I renamed it _mydefaultview, moved it to the Views/Shared
directory, and switched to specifying no view in cshtml files where I don't want it, and specifying _mydefaultview for the rest. Don't know why this was necessary, but it worked.
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
WSDL - It contains the Operation such as Methods which a webservice provides.and these method can accept simple data types such as int,float etc and complex data types such as objects ,vectors, arrays etc. so mapping this to an xml datatype xsd are used. and based upon the xsd an user who wants to acccess webservice from different platform can provide the data appropriately.
Refer : ayazroomy-java.blogspot.com to read about basics of webservice.
Use the extern
keyword to declare the variable in the other .c
file. E.g.:
extern int counter;
means that the actual storage is located in another file. It can be used for both variables and function prototypes.
For some reason no one suggested the obvious and the most straight forward way to force re-install:
> composer remove vendor-name/package-name && composer vendor-name/package-name
I found that it was necessary to enter the architecture names by hand:
I don't know why this was necessary, i.e. why these values were not inherited from Xcode itself. But as soon as I did this, the problem went away.
If you are on windows machine follow these steps.
c:/project/
cd tmp
c:/project/tmp
cd pids
c:/project/tmp/pids
dir
There you will a file called server.pid
delete it.
c:/project/tmp/pid> del *.pid
Thats it.
EDIT: Please refer this
Everybody has said your code is fine, and you know it works on other browsers without problems. So it's time to drop the science and just try stuff :)
Try putting the background color IN the body tag itself instead of/as-well-as in the CSS. Maybe insist again (redudantly) in Javascript. At some point, Chrome will have to place the background as you want it every time. Might be a timing-interpreting issue...
[Should any of this work, of course, you can toggle it on the server-side so the funny code only shows up in Chrome. And in a few months, when Chrome has changed and the problem disappears... well, worry about that later.]
The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction
may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.
Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.
Method 1: Machine's timezone dependent
By default, JavaScript returns a Date considering the machine's timezone, so getTime()
result varies from computer to computer. You can check this behavior running:
new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
// Since 1970-01-01 is Epoch, you may expect ZERO
// but in fact the result varies based on computer's timezone
This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.
// Seconds since Epoch (Unix timestamp format)
new Date().getTime() / 1000 // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000 // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
new Date().getTime() // local Date/Time since Epoch in milliseconds
new Date(2020, 0, 2).getTime() // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
Method 2: Machine's timezone independent
However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC
method or shift the date from your timezone to UTC:
Date.UTC(1970, 0, 1)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime() // difference in milliseconds between your timezone and UTC
(new Date(1970, 0, 1).getTime() - timezone_diff)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
So, using this method (or, alternatively, subtracting the difference), the result should be:
// Seconds since Epoch (Unix timestamp format)
Date.UTC(2020, 0, 1) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
(new Date(2020, 11, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-12-01 00:00 UTC in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
Date.UTC(2020, 0, 2) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 2).getTime() - timezone_diff) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.
End note
Although the recomendations in this answer, and since Date.UTC
does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff) // <-- !!! new Date() without arguments
// means "local Date/Time subtracted by timezone since Epoch" (?)
This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.
dict.iteritems
is gone in Python3.x So use iter(dict.items())
to get the same output and memory alocation
How can i do something like that but without using absolute position and float?
Apart from using the inline-block
approach (as mentioned in other answers) here are some other approaches:
.container {_x000D_
display: table;_x000D_
width: 100%;_x000D_
}_x000D_
.container div {_x000D_
display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</div>
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
.container div {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</div>
_x000D_
For a reference, this CSS-tricks post seems to sum up the various approaches to acheive this.
int[][] myNums = { {1, 2, 3, 4, 5, 6, 7}, {5, 6, 7, 8, 9, 10, 11} };
for (int x = 0; x < myNums.length; ++x) {
for(int y = 0; y < myNums[i].length; ++y) {
System.out.print(myNums[x][y]);
}
}
Output
1 2 3 4 5 6 7 5 6 7 8 9 10 11
JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.
I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install
angular-cli was broken. Even trying to do ng version
would produce an error. So I couldn't do the ng init
command. See error below:
$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
...
To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install
.
After this I was able to do ng init
. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.
ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts
This error is tied to the following factory provider in my AppModule
{ provide: Http, useFactory:
(backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}
To address this error, I had use an exported function and made the following change to the provider.
{
provide: Http,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}
... // elsewhere in AppModule
export function httpFactory(backend: XHRBackend,
options: RequestOptions,
router: Router,
navigationService: NavigationService,
errorService: ErrorService) {
return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}
To summarize what I understand to be the most important details, the following changes were required:
Update angular-cli version using the steps detailed in JJB's answer (and on their github page).
Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24
With the assistance of angular-cli and the ng init
command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.
Make code changes to export functions before I reference them, as captured in the solution details.
angular-cli.json changes
{
"project": {
"version": "1.0.0-beta.16",
"name": "frontend"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": "assets",
...
changed to...
{
"project": {
"version": "1.0.0-beta.24",
"name": "frontend"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
...
My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.
{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"ng": "ng",
"start": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update --standalone false --gecko false",
"e2e": "protractor",
"build": "ng build",
"buildProd": "ng build --env=prod"
},
"private": true,
"dependencies": {
"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",
"@angular/forms": "^2.3.1",
"@angular/http": "^2.3.1",
"@angular/platform-browser": "^2.3.1",
"@angular/platform-browser-dynamic": "^2.3.1",
"@angular/router": "^3.3.1",
"@angular/material": "^2.0.0-beta.1",
"@types/google-libphonenumber": "^7.4.8",
"angular2-datatable": "^0.4.2",
"apollo-client": "^0.4.22",
"core-js": "^2.4.1",
"rxjs": "^5.0.1",
"ts-helpers": "^1.1.1",
"zone.js": "^0.7.2",
"google-libphonenumber": "^2.0.4",
"graphql-tag": "^0.1.15",
"hammerjs": "^2.0.8",
"ng2-bootstrap": "^1.1.16"
},
"devDependencies": {
"@types/hammerjs": "^2.0.33",
"@angular/compiler-cli": "^2.3.1",
"@types/jasmine": "2.5.38",
"@types/lodash": "^4.14.39",
"@types/node": "^6.0.42",
"angular-cli": "1.0.0-beta.24",
"codelyzer": "~2.0.0-beta.1",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "~4.0.13",
"ts-node": "1.2.1",
"tslint": "^4.0.2",
"typescript": "~2.0.3",
"typings": "1.4.0"
}
}
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Use:
dt.Columns["Name"].ColumnName = "xyz";
dt.AcceptChanges();
or
dt.Columns[0].ColumnName = "xyz";
dt.AcceptChanges();
You need to Add C:\Program Files\nodejs
to your PATH environment variable. To do this follow these steps:
C:\Program Files\nodejs
. Make sure it is separated from any other paths by a ;
.You will have to restart any currently-opened command prompts before it will take effect.
It can also be done with an IsoDateTimeConverter
instance, without changing global formatting settings:
string json = JsonConvert.SerializeObject(yourObject,
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
This uses the JsonConvert.SerializeObject
overload that takes a params JsonConverter[]
argument.
Using async / await:
const mkdirP = async (directory) => {
try {
return await fs.mkdirAsync(directory);
} catch (error) {
if (error.code != 'EEXIST') {
throw e;
}
}
};
You will need to promisify fs
:
import nodeFs from 'fs';
import bluebird from 'bluebird';
const fs = bluebird.promisifyAll(nodeFs);
The which
command might be useful. man which
It returns 0 if the executable is found and returns 1 if it's not found or not executable:
NAME
which - locate a command
SYNOPSIS
which [-a] filename ...
DESCRIPTION
which returns the pathnames of the files which would
be executed in the current environment, had its
arguments been given as commands in a strictly
POSIX-conformant shell. It does this by searching
the PATH for executable files matching the names
of the arguments.
OPTIONS
-a print all matching pathnames of each argument
EXIT STATUS
0 if all specified commands are
found and executable
1 if one or more specified commands is nonexistent
or not executable
2 if an invalid option is specified
The nice thing about which
is that it figures out if the executable is available in the environment that which
is run in - it saves a few problems...
You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.
Please refer to this for the example .The main point is to use the groupProperty()
, and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
As many have suggested, JRE v1.7 and above has File.toPath();
File yourFile = ...;
Path yourPath = yourFile.toPath();
On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;
File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());
Try the file
command with -i
option.
-i
option Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii
rather than ASCII text
.
remember
is undefined … and the checked
property is a boolean not a number.
function validate(){
var remember = document.getElementById('remember');
if (remember.checked){
alert("checked") ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
Make sure that your sas.png
is marked as Build Action: Content
and Copy To Output Directory: Copy Always
in its Visual Studio Properties
...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext
is string
path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image
would be automatically loaded at runtime.
Make a List
out of the array with Arrays.asList()
, and call remove()
on all the appropriate elements. Then call toArray()
on the 'List' to make back into an array again.
Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.
I face this problem too. And ofc I looked for help in SO instead of use the common sense and check the error message.
The last part of the error message was the same as you.
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 11
But few lines above I found:
In file included from /Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/RealEstateFinder-Prefix.pch:26:
/Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/Config/Config.h:174:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
http://www.myserver.com/apps/mobile/rest.php?id=12
Which points to my Config.h file.
Happy coding!
isset
is not appropriate.According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists
is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
If you're using Kotlin, API 14+, and just wish to show uninstall dialog for your app:
startActivity(Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply {
data = Uri.parse("package:$packageName")
})
You can change packageName
to any other package name if you want to prompt the user to uninstall another app on the device
You can use the below code inside your code when you get any web browser pop-up alert message box.
// Accepts (Click on OK) Chrome Alert Browser for RESET button.
Alert alertOK = driver.switchTo().alert();
alertOK.accept();
//Rejects (Click on Cancel) Chrome Browser Alert for RESET button.
Alert alertCancel = driver.switchTo().alert();
alertCancel.dismiss();
I am sharing my code. form1.cs:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BorderExp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
private void ExitClick(object sender, EventArgs e)
{
Application.Exit();
}
private void MaxClick(object sender, EventArgs e)
{
if (WindowState ==FormWindowState.Normal)
{
this.WindowState = FormWindowState.Maximized;
}
else
{
this.WindowState = FormWindowState.Normal;
}
}
private void MinClick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
Now, the designer:-
namespace BorderExp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button1.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Location = new System.Drawing.Point(376, 1);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(27, 26);
this.button1.TabIndex = 0;
this.button1.Text = "X";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.ExitClick);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button2.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button2.FlatAppearance.BorderSize = 0;
this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Location = new System.Drawing.Point(343, 1);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(27, 26);
this.button2.TabIndex = 1;
this.button2.Text = "[]";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.MaxClick);
//
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button3.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button3.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button3.FlatAppearance.BorderSize = 0;
this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button3.Location = new System.Drawing.Point(310, 1);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(27, 26);
this.button3.TabIndex = 2;
this.button3.Text = "___";
this.button3.UseVisualStyleBackColor = false;
this.button3.Click += new System.EventHandler(this.MinClick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.ClientSize = new System.Drawing.Size(403, 320);
this.ControlBox = false;
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
}
}
the screenshot:- NoBorderForm
Valerio is almost right with his solution, but there is some logical mistake.
you must firstly check wether angle2 is bigger than angle, before adding 360 at a negative.
otherwise you always have a bigger value than angle
So the correct solution is:
var west = calculateMin(data.longitudes);
var east = calculateMax(data.longitudes);
var angle = east - west;
var north = calculateMax(data.latitudes);
var south = calculateMin(data.latitudes);
var angle2 = north - south;
var zoomfactor;
var delta = 0;
var horizontal = false;
if(angle2 > angle) {
angle = angle2;
delta = 3;
}
if (angle < 0) {
angle += 360;
}
zoomfactor = Math.floor(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2) - 2 - delta;
Delta is there, because i have a bigger width than height.
If you don't want to implement your connector customizer
, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer
. According to the README, you only have to create your keystore, configure connector.https.*
, import the library and add @ComponentScan("org.ycavatars.sboot.kit")
. Then you'll have HTTPS connection.
I wrote a class that implemented the GDI method for screen capture. I too wanted extra speed so, after discovering the DirectX method (via GetFrontBuffer) I tried that, expecting it to be faster.
I was dismayed to find that GDI performs about 2.5x faster. After 100 trials capturing my dual monitor display, the GDI implementation averaged 0.65s per screen capture, while the DirectX method averaged 1.72s. So GDI is definitely faster than GetFrontBuffer, according to my tests.
I was unable to get Brandrew's code working to test DirectX via GetRenderTargetData. The screen copy came out purely black. However, it could copy that blank screen super fast! I'll keep tinkering with that and hope to get a working version to see real results from it.
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
Passable for getting multiple values with scanf()
int r,m,v,i,e,k;
scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);
It ’s 2020 now, let me summarize the progress of the mathematical formula rendering support of source code repository hosts.
GitHub and Bitbucket still do not support the rendering of mathematical formulas, whether it is the default delimiters or other.
Bitbucket Cloud / BCLOUD-11192 -- Add LaTeX Support in MarkDown Documents (BB-12552)
GitHub / markup -- Rendering math equations
GitHub / markup -- Support latex
GitHub Community Forum -- [FEATURE REQUEST] LaTeX Math in Markdown
talk.commonmark.org -- Can math formula added to the markdown
GitHub has hardly made any substantial progress in recent years.
GitLab is already supported, but not the most common way. It uses its own delimiter.
This math is inline $`a^2+b^2=c^2`$.
This is on a separate line
```math
a^2+b^2=c^2
```
A Markdown parser used by Hugo
Use web api to render according to A hack for showing LaTeX formulas in GitHub markdown, you can even write jupyter notebook.
The way I did it while navigating to different page add a query param by passing current location
this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }
Read this query param in your component
this.router.queryParams.subscribe((params) => {
this.returnUrl = params.returnUrl;
});
If returnUrl is present enable the back button and when user clicks the back button
this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa
This should able to navigate to previous page. Instead of using location.back I feel the above method is more safe consider the case where user directly lands to your page and if he presses the back button with location.back it will redirects user to previous page which will not be your web page.
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
This has been the cleanest way to do it for me:-
ssh -n -f user@host "sh -c 'cd /whereever; nohup ./whatever > /dev/null 2>&1 &'"
The only thing running after this is the actual command on the remote machine
What I did to disable the hover state of the iframe, was to use pointer-events:none
in a css style. It shows the info on load, but after that hover shouldn't trigger showing the info.
ViewBag, ViewData, TempData and View State in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
Similarities between ViewBag & ViewData :
Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
In View, we call like below:
@ViewBag.Name
@ViewData["Name"]
TempData:
Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only
The only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view.
It requires typecasting for complex data type and check for null values to avoid error.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
You should use TryParse
- Parse
throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:
int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
If you want to test for a valid floating-point number:
double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
Note also that Double.TryParse
has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.
Foreign key and check constraints have the concept of being trusted or untrusted, as well as being enabled and disabled. See the MSDN page for ALTER TABLE
for full details.
WITH CHECK
is the default for adding new foreign key and check constraints, WITH NOCHECK
is the default for re-enabling disabled foreign key and check constraints. It's important to be aware of the difference.
Having said that, any apparently redundant statements generated by utilities are simply there for safety and/or ease of coding. Don't worry about them.
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
You can also use HTML5 replaceState if you want to change the url but don't want to add the entry to the browser history:
if (window.history.replaceState) {
//prevents browser from storing history with each change:
window.history.replaceState(statedata, title, url);
}
This would 'break' the back button functionality. This may be required in some instances such as an image gallery (where you want the back button to return back to the gallery index page instead of moving back through each and every image you viewed) whilst giving each image its own unique url.
You do with this too...
.p{
writing-mode: vertical-rl;
text-orientation: upright;
}
Change your method from
public void updateReceiptsList(List<Receipt> newlist) {
receiptlist = newlist;
this.notifyDataSetChanged();
}
To
public void updateReceiptsList(List<Receipt> newlist) {
receiptlist.clear();
receiptlist.addAll(newlist);
this.notifyDataSetChanged();
}
So you keep the same object as your DataSet in your Adapter.
I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
Here is a Swift way to get screen sizes, this also takes current interface orientation into account:
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
These are included as a standard function in:
This works , this is my case ...
C:\xampp\htdocs\your_dir>SET HTTP_PROXY="http://192.168.1.103:8080"
Replace with your IP and Port
One solution which avoids MultiIndex is to create a new datetime
column setting day = 1. Then group by this column.
df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
'Values': [5, 10, 15, 20]})
# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)
Then use groupby
as normal:
g = df.groupby('YearMonth')
res = g['Values'].sum()
# YearMonth
# 2017-09-01 20
# 2017-10-01 30
# Name: Values, dtype: int64
pd.Grouper
The subtle benefit of this solution is, unlike pd.Grouper
, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group
:
some_group = g.get_group('2017-10-01')
Calculating the last day of October is slightly more cumbersome. pd.Grouper
, as of v0.23, does support a convention
parameter, but this is only applicable for a PeriodIndex
grouper.
An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX
to string '2017-10'
. However, this is not recommended since you lose all the efficiency benefits of a datetime
series (stored internally as numerical data in a contiguous memory block) versus an object
series of strings (stored as an array of pointers).
The way to do it without projection:
StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);
To list files based on size in asending order.
find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}' | sort -n\
A 2019 answer if you're using .NET Core - use the Nuget ToDataTable library. Advantages:
Disclaimer - I'm the author of ToDataTable
Performance - I span up some Benchmark .Net tests and included them in the ToDataTable repo. The results were as follows:
Creating a 100,000 Row Datatable:
MacOS Windows
Reflection 818.5 ms 818.3 ms
FastMember from 1105.5 ms 976.4 ms
Mark's answer
Improved FastMember 524.6 ms 456.4 ms
ToDataTable 449.0 ms 376.5 ms
The FastMember method suggested in Marc's answer seemed to perform worse than Mary's answer which used reflection, but I rolled another method using a FastMember TypeAccessor
and it performed much better. Nevertheless the ToDataTable package outperformed the lot.
Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.
Our target is to copy the table atlanta from allmsa.db to atlanta.db.
ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM;
note that we give the entire path of the database to be attached.sqlite> .databases
you can see the output asseq name file --- --------------- ---------------------------------------------------------- 0 main /mnt/fastaccessDS/core/csv/atlanta.db 2 AM /mnt/fastaccessDS/core/csv/allmsa.db
INSERT INTO atlanta SELECT * FROM AM.atlanta;
This should serve your purpose.
For HP Ultra book with windows 7 enabling hyper-v through bios worked for intel haxm problem.
For enabling hyper-v:-
F10-> Bios advanced setting-> device configurations->enable Hyper-V then install.
It will work.
Since java 8 just use ZonedDateTime.parse("2010-04-05T17:16:00Z")
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
I used the nice answer of @Reid, but struggled with moving an element from the end of an array one step further - to the beginning (like in a loop). E.g. ['a', 'b', 'c'] should become ['c', 'a', 'b'] by calling .move(2,3)
I achieved this by changing the case for new_index >= this.length.
Array.prototype.move = function (old_index, new_index) {
console.log(old_index + " " + new_index);
while (old_index < 0) {
old_index += this.length;
}
while (new_index < 0) {
new_index += this.length;
}
if (new_index >= this.length) {
new_index = new_index % this.length;
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
You shouldn't have to set height: 100%
at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden
to the container.
#container { overflow: hidden; }
Should be enough to solve whatever height problem you're having.
I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.
To delete all your package follow this;
It's possible to uninstall packages installed with --user
flag. This one worked for me;
pip freeze --user | xargs pip uninstall -y
For python 3;
pip3 freeze --user | xargs pip3 uninstall -y
But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;
pip uninstall setuptools && pip uninstall pip
I think the most correct answer, assuming the use of jQuery, is a consolidation of aspects of all the answers in this page, plus the use of the event that Bootstrap passes:
$(document).on('shown.bs.modal', function(e) {
$('input:visible:enabled:first', e.target).focus();
});
It also would work changing $(document)
to $('.modal')
or to add a class to the modal that signals that this focus should occur, like $('.modal.focus-on-first-input')
I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.
MS SQL 2008 can also use the string version of true or false...
select * from users where active = 'true'
-- or --
select * from users where active = 'false'
. first step delete db.sqlite3 file . go to terminal and run commands:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
. go to admin page
every thing ok now.You can use the following little trick:
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
The call
there causes another layer of variable expansion, making it necessary to quote the original %
signs but it all works out in the end.
Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');
will replace /r
with /
using String.prototype.replace
.
Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with
mystring = mystring.replace(/\/r/g, '/');
EDIT: Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:
String.prototype.removeCharAt = function (i) {
var tmp = this.split(''); // convert to an array
tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
return tmp.join(''); // reconstruct the string
}
console.log("crt/r2002_2".removeCharAt(4));
Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt
works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1)
instead.
I've made an attempt to implement a pull to refresh component, it's far from complete but demonstrates a possible implementation, https://github.com/johannilsson/android-pulltorefresh.
Main logic is implemented in PullToRefreshListView
that extends ListView
. Internally it controls the scrolling of a header view using The widget is now updated with support for 1.5 and later, please read the README for 1.5 support though.smoothScrollBy
(API Level 8).
In your layouts you simply add it like this.
<com.markupartist.android.widget.PullToRefreshListView
android:id="@+id/android:list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
I think functional requirement is from client to developer side that is regarding functionality to the user by the software and non-functional requirement is from developer to client i.e. the requirement is not given by client but it is provided by developer to run the system smoothly e.g. safety, security, flexibility, scalability, availability, etc.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Building on @user3114046's answer:
x <- data.frame(q=1,w=2,e=3)
x
# q w e
#1 1 2 3
names(x)[match(oldnames,names(x))] <- newnames
x
# A w B
#1 1 2 3
This won't be reliant on a specific ordering of columns in the x
dataset.
For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.
DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
If possible I would suggest creating the Path
directly from the path elements:
Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"
Just to reinforce: java.util.Calender
is not for Timestamps. java.util.Date
is for a moment in time, agnostic of regional things like timezones. Most database store things in this fashion (even if they appear not to; this is usually a timezone setting in the client software; the data is good)
According to pywin32 github you must run
pip install pywin32
and after that, you must run
python Scripts/pywin32_postinstall.py -install
I know I'm reviving an old thread, but I just had this problem and this was the only way to solve it.
If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.
From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.
Windows command Unix command
rmdir rmdir
rmdir /s rm -r
move mv
I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".
All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.
(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\
gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt
dirwithsubdirs, Are you sure (Y/N)?
and that when I typed Y
, the result was that my top directory and its constituent files and subdirectories went away.
Edit
I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.
Windows command Unix command
rmdir rmdir
rmdir /s /q rm -r
rmdir /s /q rm -rf
rmdir /s rm -ri
move mv
del <file> rm <file>
If you want the equivalent for
rm -rf
you can use
rmdir /s /q
or, as the author of the answer I sourced described,
But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply
ECHO
the needed response and pipe the value into the command.
echo y | rmdir /s
I tested each of the commands using Windows CMD and Cygwin (with its bash
).
Before each test, I made the following setup.
Windows CMD
>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory
Cygwin bash
$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory
That resulted in the following file structure for both.
base
|-- this_directory
| `-- some.txt
`-- this_empty_directory
Here are the results. Note that I'll not mark each as CMD or bash
; the CMD will have a >
in front, and the bash
will have a $
in front.
RMDIR
>rmdir this_directory
The directory is not empty.
>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
| some.txt
|
\---this_empty_directory
> rmdir this_empty_directory
>tree /a /f .
base
\---this_directory
some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty
$ tree --charset=ascii
base
|-- this_directory
| `-- some.txt
`-- this_empty_directory
2 directories, 1 file
$ rmdir this_empty_directory
$ tree --charset=ascii
base
`-- this_directory
`-- some.txt
RMDIR /S /Q and RM -R ; RM -RF
>rmdir /s /q this_directory
>tree /a /f
base
\---this_empty_directory
>rmdir /s /q this_empty_directory
>tree /a /f
base
No subfolders exist
$ rm -r this_directory
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -r this_empty_directory
$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -rf this_empty_directory
$ tree --charset=ascii
base
0 directories, 0 files
RMDIR /S AND RM -RI
Here, we have a bit of a difference, but they're pretty close.
>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y
>tree /a /f
base
\---this_empty_directory
>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y
>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y
$ tree --charset=ascii
base
0 directories, 0 files
I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST
Copyright © Ben Bullock 2009-2018. All rights reserved.
and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.
I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.
I will include the disclaimer (archived) from the site:
Disclaimer Please read the following disclaimer before using any of the computer program code on this site.
There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.
In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.
https://www.google.com/search?q=cmd+equivalent+of+rm
The information I'm sharing came up first.
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).
npm update browser-sync
-------
yarn upgrade browser-sync
- Use
npm|yarn outdated
to see which modules have newer versions- Use
npm update|yarn upgrade
(without a package name) to update all modules- Include
--save-dev|--dev
if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary fordevDependencies
).
Major version upgrades:
In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x
by doing:
npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev
...or the latest 2.1.x
by doing:
npm install [email protected] --save-dev
-------
yarn add [email protected] --dev
...or the latest and greatest by doing:
npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev
Note: the last one is no different than doing this:
npm uninstall browser-sync --save-dev npm install browser-sync --save-dev ------- yarn remove browser-sync --dev yarn add browser-sync --dev
The
--save-dev
part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.
@rahul-kumar 's solution works good for me, but i wanted to call my javascript function in my typescript
foo.myFunctions() // works in browser console, but foo can't be used in typescript file
I fixed it by declaring it in my typescript :
import { Component } from '@angular/core';
import { ScriptService } from './script.service';
declare var foo;
And now, i can call foo anywhere in my typecript file
I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.
print("code sample");
select top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18 union
select 19 union
select 20 union
select 21
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
It far easier to use the scripting runtime which is installed by default on Windows
Just go project Reference and check Microsoft Scripting Runtime and click OK.
Then you can use this code which is way better than the default file commands
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
TempS = TS.ReadLine
Final = Final & TempS & vbCrLf
Loop
TS.Close
Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing
As for what is wrong with your original code here you are reading each line of the text file.
Input #iFileNo, sFileText
Then here you write it out
Write #iFileNo, sFileText
sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.
So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.
Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo
iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo
Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).
If you need to process the incoming data then you need to do something like this.
Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
C.Add sFileText
Loop
Close #iFileNo
For Each vTemp in C
Process vTemp
Next sTemp
iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo
You can use the Session object
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')
i have faced same problem
my initial json
{"items":
[
{"id":1,
"Name":"test4"
},
{"id":2,
"Name":"test1"
}
]
}
i have changed my json inside []
[{"items":
[
{"id":1,
"Name":"test4"
},
{"id":2,
"Name":"test1"
}
]
}]
In order to work where either given number could be larger I wrote this:
function getRange(start, end) {
return Array.from({
length: 1 + Math.abs(end - start)
}, (_, i) => end > start ? start + i : start - i);
}
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";
You can directly call the
method and pass your list as parameter.
l = ['Thanks You','Its fine no problem','Are you sure']
pd.DataFrame(l)
Output:
0
0 Thanks You
1 Its fine no problem
2 Are you sure
And if you have multiple lists and you want to make a dataframe out of it.You can do it as following:
import pandas as pd
names =["A","B","C","D"]
salary =[50000,90000,41000,62000]
age = [24,24,23,25]
data = pd.DataFrame([names,salary,age]) #Each list would be added as a row
data = data.transpose() #To Transpose and make each rows as columns
data.columns=['Names','Salary','Age'] #Rename the columns
data.head()
Output:
Names Salary Age
0 A 50000 24
1 B 90000 24
2 C 41000 23
3 D 62000 25
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
In my case, the tomcat directory was owned by root, and I was not running eclipse as root.
So I had to
sudo chown -R $USER apache-tomcat-VERSION/
Have seen so many that don't really work. when a temp table is created it must be deleted from the tempdb!
The only code that works is:
IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL --Remove dbo here
DROP TABLE #tempdbname -- Remoeve "tempdb.dbo"
Here is another solution using only matplotlib.pyplot
and numpy
packages.
It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic.
Here is the corresponding code :
# Python version : 2.7.9
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
# For the explanation, I simulate the data :
N=1000
data = np.random.randn(N)
# But in reality, you would read data from file, for example with :
#data = np.loadtxt("data.txt")
# Empirical average and variance are computed
avg = np.mean(data)
var = np.var(data)
# From that, we know the shape of the fitted Gaussian.
pdf_x = np.linspace(np.min(data),np.max(data),100)
pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)
# Then we plot :
plt.figure()
plt.hist(data,30,normed=True)
plt.plot(pdf_x,pdf_y,'k--')
plt.legend(("Fit","Data"),"best")
plt.show()
and here is the output.
HTML
<a href="#" class="button"> HOME </a>
CSS
.button {
background-color: #00CCFF;
padding: 8px 16px;
display: inline-block;
text-decoration: none;
color: #FFFFFF;
border-radius: 3px;
}
.button:hover{ background-color: #0066FF;}
Draemon is correct. You can also declare m
as taking varargs:
void m(String... strs) {
// strs is seen as a normal String[] inside the method
}
m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here
public static JSONObject doPostRequestWithSingleFile(String url,HashMap<String, String> data, File file,String fileParam) {
try {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody;
MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
for (String key : data.keySet()) {
String value = data.get(key);
Utility.printLog("Key Values", key + "-----------------" + value);
mBuilder.addFormDataPart(key, value);
}
if(file!=null) {
Log.e("File Name", file.getName() + "===========");
if (file.exists()) {
mBuilder.addFormDataPart(fileParam, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
}
requestBody = mBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String result=response.body().string();
Utility.printLog("Response",result+"");
return new JSONObject(result);
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
public static JSONObject doGetRequest(HashMap<String, String> param,String url) {
JSONObject result = null;
String response;
Set keys = param.keySet();
int count = 0;
for (Iterator i = keys.iterator(); i.hasNext(); ) {
count++;
String key = (String) i.next();
String value = (String) param.get(key);
if (count == param.size()) {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value);
} else {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value) + "&";
}
}
/*
try {
url= URLEncoder.encode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
Log.e("URL", url);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response responseClient = null;
try {
responseClient = client.newCall(request).execute();
response = responseClient.body().string();
result = new JSONObject(response);
Log.e("response", response+"==============");
} catch (Exception e) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
return jsonObject;
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return result;
}
I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:
var startOfDay = dateFns.startOfDay;_x000D_
var endOfDay = dateFns.endOfDay;_x000D_
_x000D_
console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));_x000D_
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
_x000D_
Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)
Strange that noone posted this way:
debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
This actually prints backtrace without the garbage - just what method was called and where.
If we declare variable using val
then it will be read-only variable. We cannot change it's value. It's like final variable of Java. It's immutable
.
But if we declare variable using var
then it will be a variable which we can read or write. We can change it's value. It's mutable
.
data class Name(val firstName: String, var lastName: String)
fun printName(name: Name): Name {
val myName = Name("Avijit", "Karmakar") // myName variable is read only
// firstName variable is read-only.
//You will get a compile time error. Val cannot be reassigned.
myName.firstName = myName.firstName
// lastName variable can be read and write as it's a var.
myName.lastName = myName.lastName
return myName
}
val
cannot be initialized lately by the keyword lateinit
but non-primitive var
can be initialized lately by the keyword lateinit
.
Add this line into Manifiest File:
android:windowSoftInputMode="adjustResize"
If you're using a functional component, you can define defaults in the destructuring assignment, like so:
export default ({ children, id="menu", side="left", image={menu} }) => {
...
};
You could create Util class:
public final class CollectionHelpers {
public static <T> boolean addNullSafe(List<T> list, T element) {
if (list == null || element == null) {
return false;
}
return list.add(element);
}
}
And then use it:
Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);
You can use sp_MSforeachdb to search all databases.
declare @RETURN_VALUE int
declare @command1 nvarchar(2000)
set @command1 = "Your command goes here"
exec @RETURN_VALUE = sp_MSforeachdb @command1 = @command1
Raj
If you are using this module with Python3 and having trouble with import. try this.
pip uninstall crypto
pip uninstall pycryptodome
pip install pycryptodome
Good Luck!
I've always used sort_by
. You need to wrap the #sort_by
output with Hash[]
to make it output a hash, otherwise it outputs an array of arrays. Alternatively, to accomplish this you can run the #to_h
method on the array of tuples to convert them to a k=>v
structure (hash).
hsh ={"a" => 1000, "b" => 10, "c" => 200000}
Hash[hsh.sort_by{|k,v| v}] #or hsh.sort_by{|k,v| v}.to_h
There is a similar question in "How to sort a Ruby Hash by number value?".
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
The problem with all these types is that a certain imprecision subsists AND that this problem can occur with small decimal numbers like in the following example
Dim fMean as Double = 1.18
Dim fDelta as Double = 0.08
Dim fLimit as Double = 1.1
If fMean - fDelta < fLimit Then
bLower = True
Else
bLower = False
End If
Question: Which value does bLower variable contain ?
Answer: On a 32 bit machine bLower contains TRUE !!!
If I replace Double by Decimal, bLower contains FALSE which is the good answer.
In double, the problem is that fMean-fDelta = 1.09999999999 that is lower that 1.1.
Caution: I think that same problem can certainly exists for other number because Decimal is only a double with higher precision and the precision has always a limit.
In fact, Double, Float and Decimal correspond to BINARY decimal in COBOL !
It is regrettable that other numeric types implemented in COBOL don't exist in .Net. For those that don't know COBOL, there exist in COBOL following numeric type
BINARY or COMP like float or double or decimal
PACKED-DECIMAL or COMP-3 (2 digit in 1 byte)
ZONED-DECIMAL (1 digit in 1 byte)
In my case, I was getting an error on JsonConvert.PopulateObject(). My request was returning JSON that was wrapped in an extra pair of '[ ]' brackets, making my result an array of one object rather than just an object. Here's what I did to get inside these brackets (only for that type of model):
T jsonResponse = new T();
var settings = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.DateTimeOffset,
NullValueHandling = NullValueHandling.Ignore,
};
var jRslt = response.Content.ReadAsStringAsync().Result;
if (jsonResponse.GetType() == typeof(myProject.Models.myModel))
{
var dobj = JsonConvert.DeserializeObject<myModel[]>(jRslt);
var y = dobj.First();
var szObj = JsonConvert.SerializeObject(y);
JsonConvert.PopulateObject(szObj, jsonResponse, settings);
}
else
{
JsonConvert.PopulateObject(jRslt, jsonResponse);
}
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "@Session["SessionName"]";
There is a really simple way to do this in a CSS only way.
Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.
#mouse_over {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
Hearing a good explanation of why using rand()
to produce uniformly distributed random numbers in a given range is a bad idea, I decided to take a look at how skewed the output actually is. My test case was fair dice throwing. Here's the C code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
int i;
int dice[6];
for (i = 0; i < 6; i++)
dice[i] = 0;
srand(time(NULL));
const int TOTAL = 10000000;
for (i = 0; i < TOTAL; i++)
dice[(rand() % 6)] += 1;
double pers = 0.0, tpers = 0.0;
for (i = 0; i < 6; i++) {
pers = (dice[i] * 100.0) / TOTAL;
printf("\t%1d %5.2f%%\n", dice[i], pers);
tpers += pers;
}
printf("\ttotal: %6.2f%%\n", tpers);
}
and here's its output:
$ gcc -o t3 t3.c
$ ./t3
1666598 16.67%
1668630 16.69%
1667682 16.68%
1666049 16.66%
1665948 16.66%
1665093 16.65%
total: 100.00%
$ ./t3
1667634 16.68%
1665914 16.66%
1665542 16.66%
1667828 16.68%
1663649 16.64%
1669433 16.69%
total: 100.00%
I don't know how uniform you need your random numbers to be, but the above appears uniform enough for most needs.
Edit: it would be a good idea to initialize the PRNG with something better than time(NULL)
.
if you want to use signalr you haveto add startup.cs Class in your project
Right Click In You Project Then Add New Item And Select OWIN Startup Class
then inside Configuration Method Add Code Below
app.MapSignalR();
I Hope it will be useful for you
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
You can use read-excel-file npm.
In that, you can specify JSON Schema to convert XLSX into JSON Format.
const readXlsxFile = require('read-excel-file/node');
const schema = {
'Segment': {
prop: 'Segment',
type: String
},
'Country': {
prop: 'Country',
type: String
},
'Product': {
prop: 'Product',
type: String
}
}
readXlsxFile('sample.xlsx', { schema }).then(({ rows, errors }) => {
console.log(rows);
});
This is the way I handled this.
Let's say you have a <select> for Month and a <select> for Day.
The number of days depends on the selected month.
Both lists are owned by a third object, the left panel. Both <select> are also children of the leftPanel <div>
It's a game with the callbacks and the handlers in the LeftPanel component.
To test it, just copy the code into two separated files and run the index.html. Then select a month and see how the number of days changes.
dates.js
/** @jsx React.DOM */
var monthsLength = [0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var MONTHS_ARR = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var DayNumber = React.createClass({
render: function() {
return (
<option value={this.props.dayNum}>{this.props.dayNum}</option>
);
}
});
var DaysList = React.createClass({
getInitialState: function() {
return {numOfDays: 30};
},
handleMonthUpdate: function(newMonthix) {
this.state.numOfDays = monthsLength[newMonthix];
console.log("Setting days to " + monthsLength[newMonthix] + " month = " + newMonthix);
this.forceUpdate();
},
handleDaySelection: function(evt) {
this.props.dateHandler(evt.target.value);
},
componentDidMount: function() {
this.props.readyCallback(this.handleMonthUpdate)
},
render: function() {
var dayNodes = [];
for (i = 1; i <= this.state.numOfDays; i++) {
dayNodes = dayNodes.concat([<DayNumber dayNum={i} />]);
}
return (
<select id={this.props.id} onChange = {this.handleDaySelection}>
<option value="" disabled defaultValue>Day</option>
{dayNodes}
</select>
);
}
});
var Month = React.createClass({
render: function() {
return (
<option value={this.props.monthIx}>{this.props.month}</option>
);
}
});
var MonthsList = React.createClass({
handleUpdate: function(evt) {
console.log("Local handler:" + this.props.id + " VAL= " + evt.target.value);
this.props.dateHandler(evt.target.value);
return false;
},
render: function() {
var monthIx = 0;
var monthNodes = this.props.data.map(function (month) {
monthIx++;
return (
<Month month={month} monthIx={monthIx} />
);
});
return (
<select id = {this.props.id} onChange = {this.handleUpdate}>
<option value="" disabled defaultValue>Month</option>
{monthNodes}
</select>
);
}
});
var LeftPanel = React.createClass({
dayRefresh: function(newMonth) {
// Nothing - will be replaced
},
daysReady: function(refreshCallback) {
console.log("Regisering days list");
this.dayRefresh = refreshCallback;
},
handleMonthChange: function(monthIx) {
console.log("New month");
this.dayRefresh(monthIx);
},
handleDayChange: function(dayIx) {
console.log("New DAY: " + dayIx);
},
render: function() {
return(
<div id="orderDetails">
<DaysList id="dayPicker" dateHandler={this.handleDayChange} readyCallback = {this.daysReady} />
<MonthsList data={MONTHS_ARR} id="monthPicker" dateHandler={this.handleMonthChange} />
</div>
);
}
});
React.renderComponent(
<LeftPanel />,
document.getElementById('leftPanel')
);
And the HTML for running the left panel component index.html
<!DOCTYPE html>
<html>
<head>
<title>Dates</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="//fb.me/react-0.11.1.js"></script>
<script src="//fb.me/JSXTransformer-0.11.1.js"></script>
</head>
<style>
#dayPicker {
position: relative;
top: 97px;
left: 20px;
width: 60px;
height: 17px;
}
#monthPicker {
position: relative;
top: 97px;
left: 22px;
width: 95px;
height: 17px;
}
select {
font-size: 11px;
}
</style>
<body>
<div id="leftPanel">
</div>
<script type="text/jsx" src="dates.js"></script>
</body>
</html>
RUN: Can be many, and it is used in build process, e.g. install multiple libraries
CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"]
, ["node", "app.js"]
)
If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css
find the .navbar-light .navbar-toggler-icon
or the .navbar-dark .navbar-toggler-icon
selector
select the background-image
attribute and its value. The snippet looks like this:
.navbar-light .navbar-toggler-icon {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}
copy the snippet and paste it in your custom CSS
change the stroke='rgba(0, 0, 0, 0.5)'
value to your preferred rgba value
Leaving an incredibly simple example in case it helps.
When variable doesn't exist:
if defined? a then "hi" end
# => nil
When variable does exist:
a = 2
if defined? a then "hi" end
# => "hi"
Since Server.MapPath()
does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:
string AppContext.BaseDirectory { get;}
You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \
and not /
like they are in mvc.
Ex:
System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");
returns true- positing that this is a sound path in your example
This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:
$inputs = [
'email' => 'foo',
'password' => 'bar',
];
$rules = [
'email' => 'required|email',
'password' => [
'required',
'string',
'min:10', // must be at least 10 characters in length
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
'regex:/[@$!%*#?&]/', // must contain a special character
],
];
$validation = \Validator::make( $inputs, $rules );
if ( $validation->fails() ) {
print_r( $validation->errors()->all() );
}
Would output:
[
'The email must be a valid email address.',
'The password must be at least 10 characters.',
'The password format is invalid.',
]
(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)
You haven't got your SUMIF
in the correct order - it needs to be range, criteria, sum range. Try:
=SUMIF(A:A,">="&DATE(2012,1,1),B:B)
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.
So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.
Honestly, this took hours to get this fixed. Finally only one thing worked a reconfirmation to solution provided by "Basheer AL-MOMANI". Which is just putting statement
@RenderSection("scripts", required: false)
within _Layout.cshtml
file after all <script></script>
elements and also commenting the jquery script in the same file. Secondly, I had to add
$.noConflict();
within jquery function call at another *.cshtml file as:
$(document).readyfunction () {
$.noConflict();
$("#example1").DataTable();
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
});
});
Android 10 (Q) onwards wifi can not be enabled/disabled you need to open the setting intent,
// for android Q and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Intent panelIntent = new
Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY);
startActivityForResult(panelIntent, 0);
} else {
// for previous android version
WifiManager wifiManager = (WifiManager)
this.getApplicationContext().getSystemService(WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
In manifest,
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
Setting
onPressed: null // disables click
and
onPressed: () => yourFunction() // enables click
Try this:
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
The problem is that in a string, a \
is an escape character. By using the @
sign you tell the compiler to ignore the escape characters.
You can also get by with escaping the \
:
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
builder.setAutoCancel(true);
Tested on Android 9 also.
For paste in Git BASH
CTRL + P
Set ANSI NULLS OFF will make NULL = NULL comparision return true. EG :
SET ANSI_NULLS OFF
select * from sys.tables
where principal_id = Null
will return some result as displayed below: zcwInvoiceDeliveryType 744547 NULL zcExpenseRptStatusTrack 2099048 NULL ZCVendorPermissions 2840564 NULL ZCWOrgLevelClientFee 4322525 NULL
While this query will not return any results:
SET ANSI_NULLS ON
select * from sys.tables
where principal_id = Null
Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
Edit:
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:
Area is a continent or ocean name. Area currently includes:
Location is the city, island, or other regional name.
The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).
Here is a list all valid timezones
You can change time zone in your settings.py as follows
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
One can use this to pretty print a request, like so:
import requests
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
def pretty_print_POST(req):
"""
At this point it is completely built and ready
to be fired; it is "prepared".
However pay attention at the formatting used in
this function because it is programmed to be pretty
printed and may differ from the actual request.
"""
print('{}\n{}\r\n{}\r\n\r\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
pretty_print_POST(prepared)
which produces:
-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test
a=1&b=2
Then you can send the actual request with this:
s = requests.Session()
s.send(prepared)
These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes
you can use unlink
to remove the symlink.
For Example:
cd ~/projects/node-redis
npm link
cd ~/projects/node-bloggy
npm link redis # links to your local redis
To reinstall from your package.json:
npm unlink redis
npm install
https://www.tachyonstemplates.com/npm-cheat-sheet/#unlinking-a-npm-package-from-an-application
new Date(2015,1,3,15,30).toLocaleString()
//=> 2015-02-03 15:30:00
The changed it from change
to selectionChange
.
<mat-select (change)="doSomething($event)">
is now
<mat-select (selectionChange)="doSomething($event)">
In addition to the link provided by Floremin, which clears text selection using JavaScript to "clear" the selection, you can also use pure CSS to accomplish this. The CSS is here...
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Simply add the class="noSelect"
attribute to the element you wish to apply this class to. I would highly recommend giving this CSS solution a try. Nothing wrong with using the JavaScript, I just believe this could potentially be easier, and clean things up a little bit in your code.
For chrome on android
-webkit-tap-highlight-color: transparent;
is an additional rule you may want to experiment with for support in Android.
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
This is achieved through URL rewriting, not through URL obfuscating, which can't be done.
Another way to do this, as has been mentioned is by changing the hashtag, with
window.location.hash = "/2131/"
If your numbers are a, b and c then:
int a = 1;
int b = 2;
int c = 3;
int d = a > b ? a : b;
return c > d ? c : d;
This could turn into one of those "how many different ways can we do this" type questions!
For security reasons, your local drive is declared to be "other-domain" and will taint the canvas.
(That's because your most sensitive info is likely on your local drive!).
While testing try these workarounds:
Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).
Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)
Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).
This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
For the MySQL fans out there, I like the IFNULL()
function. Other answers here suggest similar functionality with the ISNULL()
function in some implementations. In my situation, I have a column of descriptions which is NOT NULL
, and a column of serial numbers which may be NULL
This is how I combined them into one column:
SELECT CONCAT(description,IFNULL(' SN: ', serial_number),'')) FROM my_table;
My results suggest that the results of concatenating a string with NULL
results in a NULL
. I have been getting the alternative value in those cases.
You can use CSS3 RGBA in this way:
rgba(255, 0, 0, 0.7);
0.7
means 70% opacity.
import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
print(h2,file=e)
with open("encrypted.txt","r") as e:
p = e.readline().strip()
print(p)
If you need to interact directly with the DOM element, why not just use document.getElementById
since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val()
is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.
Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o
, crti.o
, and crtn.o
provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
atomic_int acnt;
int cnt;
int f(void* thr_data) {
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
}
return 0;
}
int main(int argc, char **argv) {
/* Basic library version check. */
printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());
/* Exercise thrd_create from -pthread,
* which is not present in glibc 2.27 in Ubuntu 18.04.
* https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
Compile and run with test_glibc.sh
:
#!/usr/bin/env bash
set -eux
gcc \
-L "${glibc_install}/lib" \
-I "${glibc_install}/include" \
-Wl,--rpath="${glibc_install}/lib" \
-Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
-std=c11 \
-o test_glibc.out \
-v \
test_glibc.c \
-pthread \
;
ldd ./test_glibc.out
./test_glibc.out
The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674
Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot
made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install
so I removed it.
ldd
output confirms that the ldd
and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
linux-vdso.so.1 (0x00007ffe4bfd3000)
libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
/home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)
The gcc
compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
+#include <stdio.h>
+
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
+ puts("hacked");
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh
and we see hacked
printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o
, crti.o
, and crtn.o
.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl
flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig
The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a
which shows me:
4.15.0-34-generic
so in menuconfig
I do:
Operating System
Version of linux
so I select:
4.14.71
which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
and now wait for about thirty minutes to two hours for compilation.
The .config
that we generated with ./ct-ng x86_64-unknown-linux-gnu
has:
CT_GLIBC_V_2_27=y
To change that, in menuconfig
do:
C-library
Version of glibc
save the .config
, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:
Paths and misc options
Try features marked as EXPERIMENTAL
: set to trueC-library
Source of glibc
Custom location
: say yesCustom location
Custom source location
: point to a directory containing your glibc sourcewhere glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
x86_64-unknown-linux-gnu-gcc \
-Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
-Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
-v \
-o test_glibc.out \
test_glibc.c \
-pthread \
;
ldd test_glibc.out
./test_glibc.out
Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps
it gives a nice overview of the build steps:
Available build steps, in order:
- companion_tools_for_build
- companion_libs_for_build
- binutils_for_build
- companion_tools_for_host
- companion_libs_for_host
- binutils_for_host
- cc_core_pass_1
- kernel_headers
- libc_start_files
- cc_core_pass_2
- libc
- cc_for_build
- cc_for_host
- libc_post_cc
- companion_libs_for_target
- binutils_for_target
- debug
- test_suite
- finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.
therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files
comes before cc_core_pass_2
, which is likely the most expensive step together with cc_core_pass_1
.
In order to build just one step, you must first set the "Save intermediate steps" in .config
option for the intial build:
Paths and misc options
Debug crosstool-NG
Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`
but unfortunately, the +
required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536
Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).
and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc
step didn't seem to copy over the source again from Custom source location
, further making this method unusable.
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?
Declare @Username varchar(20)
Set @Username = 'Mike'
if not exists
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')
Begin
Create table tblEmp (ID int primary key, Name varchar(50))
Print (@Username + ' Table created successfully')
End
Else
Begin
Print (@Username + ' : this Table Already exists in the database')
End
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
I create this program:
import pygame, sys, time, random, easygui
skier_images = ["skier_down.png", "skier_right1.png",
"skier_right2.png", "skier_left2.png",
"skier_left1.png"]
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0
def turn(self, direction):
self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed
def move(self,speed):
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self,image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
def scroll(self, t_ptr):
self.rect.centery = self.location[1] - t_ptr
def create_map(start, end):
obstacles = pygame.sprite.Group()
gates = pygame.sprite.Group()
locations = []
for i in range(10):
row = random.randint(start, end)
col = random.randint(0, 9)
location = [col * 64 + 20, row * 64 + 20]
if not (location in locations) :
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles
def animate():
screen.fill([255,255,255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10,10])
pygame.display.flip()
def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0: obstacles.add(ob)
for ob in map1: obstacles.add(ob)
return obstacles
pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)
a = True
while a:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1]
if map_position >= 640 and activeMap == 0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1] - 1280
map_position = map_position - 1280
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0, map1)
for obstacle in obstacles:
obstacle.scroll(map_position)
hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit[0].type == "tree" and not hit[0].passed:
skier.image = pygame.image.load("skier_crash.png")
easygui.msgbox(msg="OOPS!!!")
choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
if choice == "Yes":
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
elif choice == "No":
a = False
quit()
elif hit[0].type == "flag" and not hit[0].passed:
points += 10
obstacles.remove(hit[0])
score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
animate()
Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit
Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
For those who are getting the path dynamicly... e.g. drag&drop:
Some main constructions get drag&dropped file with double quotes like:
"C:\MyPath\MyFile.txt"
Quick and nice solution is to use this function to remove chars from string:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );
myAbsolutepath
now contains just C:\MyPath\MyFile.txt
The function needs these libraries: <iostream>
<algorithm>
<cstring>
.
The function was based on this answer.
Working Fiddle: http://ideone.com/XOROjq
if you are using target sdk as 23 add below code in your build.gradle
android{
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary 'org.apache.http.legacy'
}
and change your buildscript to
classpath 'com.android.tools.build:gradle:1.3.0'
for more info follow this link
I had the same problem with Ubuntu 17, Ispconfig
was not processing the operations queued of any kind and also the server.sh
command was not working.
I checked and the running PHP version after the OS upgrade was 7.1 so the solution was to type:
apt-get install php7.1-mbstring
and now is everything ok
I've gotten the same issue and one of the posted example in the manual worked. A character set must be specified as one of the posters here already mentioned. http://www.php.net/manual/en/function.ob-flush.php#109314
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
echo $i . '<br />';
flush();
ob_flush();
sleep(1);
}
echo 'End ...<br />';
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
always use with statement like ;WITH
then you'll never get this error. The WITH command required a ;
between it and any previous command, by always using ;WITH
you'll never have to remember to do this.
see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:
When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.
Killing the process specified in the Dockerfile's CMD
/ ENTRYPOINT
works for me. (The container restarts automatically)
Rebooting was not allowed in my container, so I had to use this workaround.
I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.
See AES in ASP.NET with VB.NET for more information about encryption in .NET.
Testing if a value is numeric or a string representation of a numeric value.
function Test-Number
{
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[ValidatePattern("^[\d\.]+$")]
$Number
)
$Number -is [ValueType] -or [Double]::TryParse($Number,[ref]$null)
}
Testing if a value is numeric.
function Test-Number
{
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[ValidatePattern("^[\d\.]+$")]
$Number
)
$Number -is [ValueType]
}
Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.
Quoting from http://dev.mysql.com/doc/refman/5.1/en/create-table.html
{INDEX|KEY}
So KEY
is an INDEX
;)
A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.
Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?
I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale
Rationale
react
/react-dom
comes comes with 2 basic assumptions/ideas:
- every UI is hierarchical naturally. This why we have the idea of
components
which wrap each otherreact-dom
mounts (physically) child component to its parent DOM node by defaultThe problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.
Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your
UI element
: it'll render in fixed layer and should know its coordinates (which are thatUI element
coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.
Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:
import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
return (
<Cell {...props}>
// the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
<Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
hideMe, // alias for `hide(modalId)`
index } // useful to know to set zIndex, for example
, e) => // access to the arguments (click event data in this example)
<Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
<ConfirmationDialog
title={ 'Delete' }
message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
confirmButton={ <Button type="primary">DELETE</Button> }
onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
close={ hideMe } />
</Modal> }
</Layer>
// this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
<LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
<div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
<Icon type="trash" />
</div> }
</LayerContext>
</Cell>)
// ...
Try using delegate instead of live as here:
$('#link-wrapper').delegate('a', 'click', function() {
// do something ..
}
I like the following:
public String readLine(String tPromptString) {
byte[] tBuffer = new byte[256];
int tPos = 0;
System.out.print(tPromptString);
while(true) {
byte tNextByte = readByte();
if(tNextByte == 10) {
return new String(tBuffer, 0, tPos);
}
if(tNextByte != 13) {
tBuffer[tPos] = tNextByte;
++tPos;
}
}
}
and for example, I would do:
String name = this.readLine("What is your name?")
For document references, not collections, you need:
// when you know the 'id'
this.afs.doc(`items/${id}`)
.snapshotChanges().pipe(
map((doc: any) => {
const data = doc.payload.data();
const id = doc.payload.id;
return { id, ...data };
});
as .valueChanges({ idField: 'id'});
will not work here. I assume it was not implemented since generally you search for a document by the id...
I like to use a TreeWalker if the set of elements are children of a root node.
git log -1 --format="%an %ae%n%cn %ce" a2c25061
The Pretty Formats section of the git show
documentation contains
format:<string>
The
format:<string>
format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with%n
instead of\n
…The placeholders are:
%an
: author name%ae
: author email%cn
: committer name%ce
: committer email
To produce identical output to winver.exe in PowerShell v5 on Windows 10 1809:
$Version = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
"Version $($Version.ReleaseId) (OS Build $($Version.CurrentBuildNumber).$($Version.UBR))"
I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."
git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f
I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:
git checkout testing
git reset --hard abc1234
git push -f
I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)
ok i figure out :
DECLARE @dayName VARCHAR(9), @weekenda VARCHAR(9), @free INT
SET @weekenda =DATENAME(dw,GETDATE())
IF (@weekenda='Saturday' OR @weekenda='Sunday')
SET @free=1
ELSE
SET @free=0
than i use : .......... OR free=1
This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like
ctl00_ContentColumn_txt_model_code
There are a few ways round this:
Use the actual control name:
var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;
use the ClientID property within ASP script tags
document.getElementById('<%= txt_model_code.ClientID %>').value;
Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.
http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1
Had the same with IDEA 14.1.5, Kotlin v.1.0.0-beta-1038-IJ141-17.
Kotlin gets its own list entry (like Java) when creating new project, but the only working config was:
New | Project | Java | "Kotlin (Java)" (make sure you have Project SDK configured, too)
use library: Create, "Copy to: lib".
Late to the party, but this may help anyone looking for a quick solution:
you can use bin(ord('b')).replace('b', '')
bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.
Cheers
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.
Shortly it's:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc
In my case there was another directory within my workspace, having the same jar file as the one in my project. I hadn't created that directory or anything in it. It was created by Eclipse I believe. I just erased that directory and it just runs ok.
Please Start the MongoDB server first and try to connect.
Pre-requisite:
Create space for storing DB and tables in any directory
Example (windows): D:\mongodbdata\
Steps:
Start server
mongod --port 5000 --dbpath D:\mongodbdata\ (please mention above created path)
Connect mongodb server (Run in another terminal/console)
mongo --port 5000
You might have the same problem as I do. After creating your .jar file, write jar xf app.jar META-INF/MANIFEST.MF
. This will create a copy of the file to your current directory so you can read it. If it only says something like:
Manifest-Version: 1.0
Created-By: 1.8.0_51 (Oracle Corporation)
and does not contain the "Main-Class" declaration, then I think you found your problem.
I do not know how to solve it, though. I checked other people with same/similar problems on StackOverflow and couldn't find an answer. However with this information you can perhaps get some better help (given the fact that you have the same problem as I).
Edit: I had tried with a manifest-file but didn't get it to work, but my mistake was to only name one of the classes when creating the jar-file. I wrote *.class instead and it works now.
Although I don't know why there is a need to create a manifest-file. But I guess it's fine as long as it works.
Edit:
@t1m0thy's answer is more elegant than mine, better follow his advices.
Also, nice link proposed by @aldemarcalazans in the comments: https://davidwalsh.name/html5-buttons.
Original answer:
Use <a />
when you need a link (the a of anchor). Use <button />
when you need a button.
That said, if you really need to expand an <a />
, add the CSS attribute display: block;
on it. You'll then be able to specify a width and/or a height (i.e. as if it were a <div />
).
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE